Разделение по отдельным репозиториям
This commit is contained in:
36
app/Controllers/ApiController.php
Normal file
36
app/Controllers/ApiController.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Random\RandomException;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class ApiController extends BasicController
|
||||
{
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @param ResponseInterface $response
|
||||
* @return ResponseInterface
|
||||
* @throws RandomException
|
||||
*/
|
||||
public function json(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
$code = $request->getAttributes()['code'];
|
||||
$playlist = $this->getPlaylist($code, true);
|
||||
$playlist->fetchContent();
|
||||
$playlist->parse();
|
||||
|
||||
$json = json_encode($playlist->toArray(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
$response->getBody()->write($json);
|
||||
|
||||
return $response
|
||||
->withHeader('Content-Type', 'application/json')
|
||||
->withHeader('Content-Length', strlen($json));
|
||||
}
|
||||
}
|
||||
58
app/Controllers/BasicController.php
Normal file
58
app/Controllers/BasicController.php
Normal file
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Playlist;
|
||||
use App\Errors\PlaylistNotFoundException;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Slim\Views\Twig;
|
||||
use Twig\Error\LoaderError;
|
||||
use Twig\Error\RuntimeError;
|
||||
use Twig\Error\SyntaxError;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class BasicController
|
||||
{
|
||||
/**
|
||||
* Отправляет сообщение о том, что метод не найден с кодом страницы 404
|
||||
*
|
||||
* @param ServerRequestInterface $request
|
||||
* @param ResponseInterface $response
|
||||
* @return ResponseInterface
|
||||
* @throws LoaderError
|
||||
* @throws RuntimeError
|
||||
* @throws SyntaxError
|
||||
*/
|
||||
public function notFound(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
$response->withStatus(404);
|
||||
$this->view($request, $response, 'notfound.twig');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @param ResponseInterface $response
|
||||
* @param string $template
|
||||
* @param array $data
|
||||
* @return ResponseInterface
|
||||
* @throws LoaderError
|
||||
* @throws RuntimeError
|
||||
* @throws SyntaxError
|
||||
*/
|
||||
protected function view(
|
||||
ServerRequestInterface $request,
|
||||
ResponseInterface $response,
|
||||
string $template,
|
||||
array $data = [],
|
||||
): ResponseInterface {
|
||||
$view = Twig::fromRequest($request);
|
||||
return $view->render($response, $template, $data);
|
||||
}
|
||||
}
|
||||
128
app/Controllers/WebController.php
Normal file
128
app/Controllers/WebController.php
Normal file
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\ChannelLogo;
|
||||
use App\Errors\PlaylistNotFoundException;
|
||||
use Exception;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Twig\Error\LoaderError;
|
||||
use Twig\Error\RuntimeError;
|
||||
use Twig\Error\SyntaxError;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class WebController extends BasicController
|
||||
{
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @param ResponseInterface $response
|
||||
* @return ResponseInterface
|
||||
* @throws LoaderError
|
||||
* @throws RuntimeError
|
||||
* @throws SyntaxError
|
||||
* @throws Exception
|
||||
*/
|
||||
public function home(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
ini()->load();
|
||||
|
||||
$playlists = ini()->playlists(false);
|
||||
$count = count($playlists);
|
||||
$page = (int)($request->getAttributes()['page'] ?? $request->getQueryParams()['page'] ?? 1);
|
||||
$pageSize = config('app.page_size');
|
||||
$pageCount = ceil($count / $pageSize);
|
||||
$offset = max(0, ($page - 1) * $pageSize);
|
||||
$list = array_slice($playlists, $offset, $pageSize, true);
|
||||
|
||||
return $this->view($request, $response, 'list.twig', [
|
||||
'updated_at' => ini()->updatedAt(),
|
||||
'playlists' => $list,
|
||||
'count' => $count,
|
||||
'pageCount' => $pageCount,
|
||||
'pageCurrent' => $page,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @param ResponseInterface $response
|
||||
* @return ResponseInterface
|
||||
* @throws LoaderError
|
||||
* @throws RuntimeError
|
||||
* @throws SyntaxError
|
||||
*/
|
||||
public function faq(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
return $this->view($request, $response, 'faq.twig');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @param ResponseInterface $response
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function redirect(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
ini()->load();
|
||||
$code = $request->getAttributes()['code'];
|
||||
try {
|
||||
$playlist = ini()->getPlaylist($code);
|
||||
return $response->withHeader('Location', $playlist->pls);
|
||||
} catch (PlaylistNotFoundException) {
|
||||
return $this->notFound($request, $response);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @param ResponseInterface $response
|
||||
* @return ResponseInterface
|
||||
* @throws \Random\RandomException
|
||||
* @throws LoaderError
|
||||
* @throws RuntimeError
|
||||
* @throws SyntaxError
|
||||
*/
|
||||
public function details(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
ini()->load();
|
||||
$code = $request->getAttributes()['code'];
|
||||
try {
|
||||
$playlist = ini()->getPlaylist($code);
|
||||
$response->withHeader('Location', $playlist->pls);
|
||||
} catch (PlaylistNotFoundException) {
|
||||
return $this->notFound($request, $response);
|
||||
}
|
||||
|
||||
$playlist->fetchContent();
|
||||
$playlist->parse();
|
||||
|
||||
return $this->view($request, $response, 'details.twig', $playlist->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @param ResponseInterface $response
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function logo(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
$input = $request->getQueryParams()['url'] ?? null;
|
||||
|
||||
$logo = new ChannelLogo($input);
|
||||
$logo->readFile() || $logo->fetch();
|
||||
$logo->size() === 0 && $logo->setDefault();
|
||||
$logo->store();
|
||||
$body = $logo->raw();
|
||||
$size = $logo->size();
|
||||
$mime = $logo->mimeType();
|
||||
|
||||
$response->getBody()->write($body);
|
||||
return $response->withHeader('Content-Type', $mime)
|
||||
->withHeader('Content-Length', $size);
|
||||
}
|
||||
}
|
||||
195
app/Core/ChannelLogo.php
Normal file
195
app/Core/ChannelLogo.php
Normal file
@@ -0,0 +1,195 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
class ChannelLogo implements \Stringable
|
||||
{
|
||||
/**
|
||||
* @var string Валидированная ссылка на изображение
|
||||
*/
|
||||
public readonly string $url;
|
||||
|
||||
/**
|
||||
* @var string|null Хэш от ссылки на изображение
|
||||
*/
|
||||
public readonly ?string $hash;
|
||||
|
||||
/**
|
||||
* @var string|null Путь к файлу изображению на диске
|
||||
*/
|
||||
protected ?string $path = '';
|
||||
|
||||
/**
|
||||
* @var string|null MIME-тип изображения
|
||||
*/
|
||||
protected ?string $mimeType = null;
|
||||
|
||||
/**
|
||||
* @var false|string|null Сырое изображение:
|
||||
* null -- не загружалось;
|
||||
* false -- ошибка загрузки;
|
||||
* string -- бинарные данные.
|
||||
*/
|
||||
protected false|string|null $rawData = null;
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param string $url Внешняя ссылка на изображение
|
||||
*/
|
||||
public function __construct(string $url)
|
||||
{
|
||||
$url = empty($url) ? base_url('public/no-tvg-logo.png') : $this->prepareUrl($url);
|
||||
if (is_string($url)) {
|
||||
$this->url = $url;
|
||||
$this->hash = md5($url);
|
||||
$this->path = cache_path("tv-logos/$this->hash");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Валидирует и очищает ссылку на изображение
|
||||
*
|
||||
* @param string $url
|
||||
* @return false|string
|
||||
*/
|
||||
protected function prepareUrl(string $url): false|string
|
||||
{
|
||||
$parts = parse_url(trim($url));
|
||||
if (!is_array($parts) || count($parts) < 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$result = $parts['scheme'] . '://' . $parts['host'];
|
||||
$result .= (empty($parts['port']) ? '' : ':' . $parts['port']);
|
||||
|
||||
return $result . $parts['path'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает сырое изображение по ссылке и определяет его MIME-тип
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function fetch(): bool
|
||||
{
|
||||
$this->rawData = @file_get_contents($this->url);
|
||||
$isFetched = is_string($this->rawData);
|
||||
if (!$isFetched) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->mimeType = $this->mimeType();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохраняет сырое изображение в кэш
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function store(): bool
|
||||
{
|
||||
return is_string($this->rawData)
|
||||
&& $this->prepareCacheDir()
|
||||
&& @file_put_contents($this->path, $this->rawData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Считывает изображение из кэша
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function readFile(): bool
|
||||
{
|
||||
if (!file_exists($this->path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->rawData = @file_get_contents($this->path);
|
||||
return is_string($this->rawData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Считывает дефолтный эскиз вместо логотипа
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function setDefault(): bool
|
||||
{
|
||||
$this->path = root_path('public/no-tvg-logo.png');
|
||||
return $this->readFile();
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает base64-кодированное изображение
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function asBase64(): ?string
|
||||
{
|
||||
if (!is_string($this->rawData)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return "data:$this->mimeType;base64," . base64_encode($this->rawData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает сырое изображение
|
||||
*
|
||||
* @return false|string|null
|
||||
*/
|
||||
public function raw(): false|string|null
|
||||
{
|
||||
return $this->rawData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет готовность директории кэша изображений, создавая её при необходимости
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function prepareCacheDir(): bool
|
||||
{
|
||||
$cacheFileDir = cache_path('tv-logos');
|
||||
|
||||
return is_dir($cacheFileDir)
|
||||
|| @mkdir($cacheFileDir, 0775, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает MIME-тип сырого изображения
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function mimeType(): ?string
|
||||
{
|
||||
if (!is_string($this->rawData)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$finfo = new \finfo(FILEINFO_MIME_TYPE);
|
||||
return $finfo->buffer($this->rawData) ?: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает размер сырого изображения в байтах
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function size(): int
|
||||
{
|
||||
return strlen((string)$this->rawData);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->asBase64();
|
||||
}
|
||||
}
|
||||
230
app/Core/Core.php
Normal file
230
app/Core/Core.php
Normal file
@@ -0,0 +1,230 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
use App\Core\TwigExtention as IptvTwigExtension;
|
||||
use Dotenv\Dotenv;
|
||||
use InvalidArgumentException;
|
||||
use Redis;
|
||||
use Slim\App;
|
||||
use Slim\Factory\AppFactory;
|
||||
use Slim\Views\Twig;
|
||||
use Slim\Views\TwigMiddleware;
|
||||
use Twig\Error\LoaderError;
|
||||
|
||||
/**
|
||||
* Загрузчик приложения
|
||||
*/
|
||||
final class Core
|
||||
{
|
||||
/**
|
||||
* @var Core
|
||||
*/
|
||||
private static Core $instance;
|
||||
|
||||
/**
|
||||
* @var App
|
||||
*/
|
||||
protected App $app;
|
||||
|
||||
/**
|
||||
* @var array Конфигурация приложения
|
||||
*/
|
||||
protected array $config = [];
|
||||
|
||||
/**
|
||||
* @var Redis
|
||||
*/
|
||||
protected Redis $redis;
|
||||
|
||||
/**
|
||||
* @var IniFile
|
||||
*/
|
||||
protected IniFile $iniFile;
|
||||
|
||||
/**
|
||||
* Закрытый конструктор
|
||||
*/
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает объект приложения
|
||||
*
|
||||
* @return Core
|
||||
*/
|
||||
public static function get(): Core
|
||||
{
|
||||
return self::$instance ??= new self();
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает приложение
|
||||
*
|
||||
* @return App
|
||||
* @throws LoaderError
|
||||
*/
|
||||
public function boot(): App
|
||||
{
|
||||
$this->app = AppFactory::create();
|
||||
|
||||
$this->bootSettings();
|
||||
$this->bootRoutes();
|
||||
$this->bootTwig();
|
||||
$this->bootRedis();
|
||||
$this->bootIni();
|
||||
|
||||
return $this->app;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает значение из конфига
|
||||
*
|
||||
* @param string $key Ключ в формате "config.key"
|
||||
* @param mixed|null $default Значение по умолчанию
|
||||
* @return mixed
|
||||
*/
|
||||
public function config(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$parts = explode('.', $key);
|
||||
return $this->config[$parts[0]][$parts[1]] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Redis
|
||||
*/
|
||||
public function redis(): Redis
|
||||
{
|
||||
return $this->redis;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return IniFile
|
||||
*/
|
||||
public function ini(): IniFile
|
||||
{
|
||||
return $this->iniFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return App
|
||||
*/
|
||||
public function app(): App
|
||||
{
|
||||
return $this->app;
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает файл .env или .env.$env
|
||||
*
|
||||
* @param string $env
|
||||
* @return array
|
||||
*/
|
||||
protected function loadDotEnvFile(string $env = ''): array
|
||||
{
|
||||
$filename = empty($env) ? '.env' : ".env.$env";
|
||||
if (!file_exists(root_path($filename))) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$dotenv = Dotenv::createMutable(root_path(), $filename);
|
||||
return $dotenv->safeLoad();
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает конфигурационные файлы
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function bootSettings(): void
|
||||
{
|
||||
$env = $this->loadDotEnvFile();
|
||||
|
||||
if (!empty($env['APP_ENV'])) {
|
||||
$this->loadDotEnvFile($env['APP_ENV']);
|
||||
}
|
||||
|
||||
foreach (glob(config_path() . '/*.php') as $file) {
|
||||
$key = basename($file, '.php');
|
||||
$this->config += [$key => require_once $file];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает маршруты
|
||||
*
|
||||
* @return void
|
||||
* @see https://www.slimframework.com/docs/v4/objects/routing.html
|
||||
*/
|
||||
protected function bootRoutes(): void
|
||||
{
|
||||
foreach ($this->config['routes'] as $route) {
|
||||
if (is_array($route['method'])) {
|
||||
$definition = $this->app->map($route['method'], $route['path'], $route['handler']);
|
||||
} else {
|
||||
$isPossible = in_array($route['method'], ['GET', 'POST', 'OPTIONS', 'PUT', 'PATCH', 'DELETE']);
|
||||
|
||||
$func = match (true) {
|
||||
$route['method'] === '*' => 'any',
|
||||
$isPossible => strtolower($route['method']),
|
||||
default => throw new InvalidArgumentException(sprintf('Неверный HTTP метод %s', $route['method']))
|
||||
};
|
||||
|
||||
$definition = $this->app->$func($route['path'], $route['handler']);
|
||||
}
|
||||
|
||||
if (!empty($route['name'])) {
|
||||
$definition->setName($route['name']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает шаблонизатор и его расширения
|
||||
*
|
||||
* @return void
|
||||
* @throws LoaderError
|
||||
* @see https://www.slimframework.com/docs/v4/features/twig-view.html
|
||||
*/
|
||||
protected function bootTwig(): void
|
||||
{
|
||||
$twig = Twig::create(root_path('views'), $this->config['twig']);
|
||||
$twig->addExtension(new IptvTwigExtension());
|
||||
$this->app->add(TwigMiddleware::create($this->app, $twig));
|
||||
}
|
||||
|
||||
/**
|
||||
* Инициализирует подключение к Redis
|
||||
*
|
||||
* @return void
|
||||
* @see https://github.com/phpredis/phpredis/?tab=readme-ov-file
|
||||
*/
|
||||
protected function bootRedis(): void
|
||||
{
|
||||
$options = [
|
||||
'host' => $this->config['redis']['host'],
|
||||
'port' => (int)$this->config['redis']['port'],
|
||||
];
|
||||
|
||||
if (!empty($this->config['redis']['password'])) {
|
||||
$options['auth'] = $this->config['redis']['password'];
|
||||
}
|
||||
|
||||
$this->redis = new Redis($options);
|
||||
$this->redis->select((int)$this->config['redis']['db']);
|
||||
$this->redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_JSON);
|
||||
}
|
||||
|
||||
/**
|
||||
* Инициализирует объект ini-файла
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function bootIni(): void
|
||||
{
|
||||
$this->iniFile = new IniFile();
|
||||
}
|
||||
}
|
||||
135
app/Core/IniFile.php
Normal file
135
app/Core/IniFile.php
Normal file
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
use App\Errors\PlaylistNotFoundException;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Класс для работы с ini-файлом плейлистов
|
||||
*/
|
||||
class IniFile
|
||||
{
|
||||
/**
|
||||
* @var array Считанное из файла содержимое ini-файла
|
||||
*/
|
||||
protected array $ini;
|
||||
|
||||
/**
|
||||
* @var Playlist[] Коллекция подгруженных плейлистов
|
||||
*/
|
||||
protected array $playlists = [];
|
||||
|
||||
/**
|
||||
* @var string[] Карта переадресаций плейлистов
|
||||
*/
|
||||
protected array $redirections = [];
|
||||
|
||||
/**
|
||||
* @var string Дата последнего обновления списка
|
||||
*/
|
||||
protected string $updated_at;
|
||||
|
||||
/**
|
||||
* Считывает ini-файл и инициализирует объекты плейлистов
|
||||
*
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function load(): void
|
||||
{
|
||||
$ini = redis()->hGetAll('_playlists_');
|
||||
if (empty($ini)) {
|
||||
$filepath = config_path('playlists.ini');
|
||||
$ini = parse_ini_file($filepath, true);
|
||||
$this->updated_at = date('d.m.Y h:i', filemtime($filepath));
|
||||
$order = array_keys($ini);
|
||||
}
|
||||
|
||||
$order ??= redis()->get('_order_');
|
||||
$this->ini ??= $ini;
|
||||
$this->updated_at ??= redis()->get('_updated_at_');
|
||||
$transaction = redis()->multi();
|
||||
foreach ($order as $id) {
|
||||
$data = $this->ini[$id];
|
||||
$this->playlists[(string)$id] = $pls = $this->makePlaylist($id, $data);
|
||||
$transaction->hSet('_playlists_', $id, $pls);
|
||||
}
|
||||
|
||||
$expireAfter = config('redis.ttl_days');
|
||||
$transaction
|
||||
->expire('_playlists_', $expireAfter)
|
||||
->set('_order_', $order, ['EX' => $expireAfter])
|
||||
->set('_updated_at_', $this->updated_at, ['EX' => $expireAfter])
|
||||
->exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает объекты плейлистов
|
||||
*
|
||||
* @param bool $all true - получить все, false - получить только НЕпереадресованные
|
||||
* @return Playlist[]
|
||||
*/
|
||||
public function playlists(bool $all = true): array
|
||||
{
|
||||
return $all
|
||||
? $this->playlists
|
||||
: array_filter($this->playlists, static fn ($playlist) => is_null($playlist->redirectId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает дату обновления ini-файла
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function updatedAt(): string
|
||||
{
|
||||
return $this->updated_at;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает ID плейлиста, на который нужно переадресовать указанный
|
||||
*
|
||||
* @param string $id ID плейлиста
|
||||
* @return string|null
|
||||
*/
|
||||
public function getRedirection(string $id): ?string
|
||||
{
|
||||
return $this->redirections[$id] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает объект плейлиста
|
||||
*
|
||||
* @param string $id ID плейлиста
|
||||
* @return Playlist|null
|
||||
* @throws PlaylistNotFoundException
|
||||
*/
|
||||
public function getPlaylist(string $id): ?Playlist
|
||||
{
|
||||
return $this->playlists[$id] ?? throw new PlaylistNotFoundException($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Создаёт объекты плейлистов, рекурсивно определяя переадресации
|
||||
*
|
||||
* @param int|string $id ID плейлиста
|
||||
* @param array $params Описание плейлиста
|
||||
* @param string|null $redirectId ID для переадресации
|
||||
* @return Playlist
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function makePlaylist(int|string $id, array $params, ?string $redirectId = null): Playlist
|
||||
{
|
||||
$id = (string)$id;
|
||||
if (isset($params['redirect'])) {
|
||||
$this->redirections[$id] = $redirectId = (string)$params['redirect'];
|
||||
$params = $this->ini[$redirectId];
|
||||
return $this->makePlaylist($id, $params, $redirectId);
|
||||
}
|
||||
|
||||
return new Playlist($id, $params, $redirectId);
|
||||
}
|
||||
}
|
||||
368
app/Core/Playlist.php
Normal file
368
app/Core/Playlist.php
Normal file
@@ -0,0 +1,368 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
use CurlHandle;
|
||||
use Exception;
|
||||
use Random\RandomException;
|
||||
|
||||
/**
|
||||
* Плейлист без редиректа
|
||||
*/
|
||||
class Playlist
|
||||
{
|
||||
/**
|
||||
* @var string|null Название плейлиста
|
||||
*/
|
||||
public ?string $name;
|
||||
|
||||
/**
|
||||
* @var string|null Описание плейлиста
|
||||
*/
|
||||
public ?string $desc;
|
||||
|
||||
/**
|
||||
* @var string Прямой URL до файла плейлиста на третьей стороне
|
||||
*/
|
||||
public string $pls;
|
||||
|
||||
/**
|
||||
* @var string|null Источник плейлиста
|
||||
*/
|
||||
public ?string $src;
|
||||
|
||||
/**
|
||||
* @var string Ссылка на плейлист в рамках проекта
|
||||
*/
|
||||
public string $url;
|
||||
|
||||
/**
|
||||
* @var string|null Сырое содержимое плейлиста
|
||||
*/
|
||||
protected ?string $rawContent = null;
|
||||
|
||||
/**
|
||||
* @var array Обработанное содержимое плейлиста
|
||||
*/
|
||||
protected array $parsedContent = [];
|
||||
|
||||
/**
|
||||
* @var array Статус скачивания плейлиста
|
||||
*/
|
||||
protected array $downloadStatus = [
|
||||
'httpCode' => 'unknown',
|
||||
'errCode' => 'unknown',
|
||||
'errText' => 'unknown',
|
||||
'possibleStatus' => 'unknown',
|
||||
];
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param string $id ID плейлиста
|
||||
* @param array $params Описание плейлиста
|
||||
* @param string|null $redirectId ID для переадресации
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $id,
|
||||
array $params,
|
||||
public readonly ?string $redirectId = null
|
||||
) {
|
||||
empty($params['pls']) && throw new Exception(
|
||||
"Плейлист с ID=$id обязан иметь параметр pls или redirect"
|
||||
);
|
||||
|
||||
$this->url = base_url($id);
|
||||
$this->name = empty($params['name']) ? "Плейлист #$id" : $params['name'];
|
||||
$this->desc = empty($params['desc']) ? null : $params['desc'];
|
||||
$this->pls = $params['pls'];
|
||||
$this->src = empty($params['src']) ? null : $params['src'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Получает содержимое плейлиста с третьей стороны
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function fetchContent(): void
|
||||
{
|
||||
$cached = redis()->get($this->id);
|
||||
if (is_array($cached)) {
|
||||
$this->downloadStatus['httpCode'] = $cached['httpCode'];
|
||||
$this->downloadStatus['errCode'] = $cached['errCode'];
|
||||
$this->downloadStatus['errText'] = $cached['errText'];
|
||||
$this->downloadStatus['possibleStatus'] = $cached['possibleStatus'];
|
||||
$this->rawContent = $cached['content'];
|
||||
return;
|
||||
}
|
||||
|
||||
$curl = $this->makeCurl();
|
||||
$content = curl_exec($curl);
|
||||
$this->rawContent = $content === false ? null : $content;
|
||||
$this->downloadStatus['httpCode'] = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
|
||||
$this->downloadStatus['errCode'] = curl_errno($curl);
|
||||
$this->downloadStatus['errText'] = curl_error($curl);
|
||||
$this->downloadStatus['possibleStatus'] = $this->guessStatus($this->downloadStatus['errCode']);
|
||||
curl_close($curl);
|
||||
|
||||
if ($cached === false) {
|
||||
redis()->set($this->id, [
|
||||
'httpCode' => $this->downloadStatus['httpCode'],
|
||||
'errCode' => $this->downloadStatus['errCode'],
|
||||
'errText' => $this->downloadStatus['errText'],
|
||||
'possibleStatus' => $this->downloadStatus['possibleStatus'],
|
||||
'content' => $this->rawContent,
|
||||
], ['EX' => config('redis.ttl_days')]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает статус проверки плейлиста по коду ошибки curl
|
||||
*
|
||||
* @param int $curlErrCode
|
||||
* @return string
|
||||
*/
|
||||
protected function guessStatus(int $curlErrCode): string
|
||||
{
|
||||
return match ($curlErrCode) {
|
||||
0 => 'online',
|
||||
28 => 'timeout',
|
||||
5, 6, 7, 22, 35 => 'offline',
|
||||
default => 'error',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Парсит полученный от третьей стороны плейлист
|
||||
*
|
||||
* @return array Информация о составе плейлиста
|
||||
* @throws RandomException
|
||||
*/
|
||||
public function parse(): array
|
||||
{
|
||||
if (!empty($this->parsed())) {
|
||||
return $this->parsed();
|
||||
}
|
||||
|
||||
$result = [
|
||||
'attributes' => [],
|
||||
'channels' => [],
|
||||
'groups' => [],
|
||||
'encoding' => [
|
||||
'name' => 'unknown',
|
||||
'alert' => false,
|
||||
],
|
||||
];
|
||||
|
||||
if (is_null($this->rawContent)) {
|
||||
return $this->parsedContent = $result;
|
||||
}
|
||||
|
||||
$enc = mb_detect_encoding($this->rawContent, config('app.pls_encodings'));
|
||||
$result['encoding']['name'] = $enc;
|
||||
if ($enc !== 'UTF-8') {
|
||||
$result['encoding']['alert'] = true;
|
||||
$this->rawContent = mb_convert_encoding($this->rawContent, 'UTF-8', $enc);
|
||||
}
|
||||
|
||||
$lines = explode("\n", $this->rawContent);
|
||||
$isHeader = $isGroup = $isChannel = false;
|
||||
foreach ($lines as $line) {
|
||||
if (empty($line = trim($line))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (str_starts_with($line, '#EXTM3U ')) {
|
||||
$isHeader = true;
|
||||
$isGroup = $isChannel = false;
|
||||
|
||||
$result['attributes'] = $this->parseAttributes($line);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (str_starts_with($line, '#EXTINF:')) {
|
||||
$isChannel = true;
|
||||
$isHeader = $isGroup = false;
|
||||
|
||||
$combined = trim(substr($line, strpos($line, ',') + 1));
|
||||
$exploded = explode(',', $line);
|
||||
$attrs = $this->parseAttributes($exploded[0]);
|
||||
$tvgid = empty($attrs['tvg-id']) ? ' неизвестен' : "='{$attrs['tvg-id']}'";
|
||||
$name = trim($exploded[1] ?? "(канал без названия, tvg-id$tvgid)");
|
||||
$channel = [
|
||||
'_id' => md5($name . random_int(1, 99999)),
|
||||
'name' => trim($name),
|
||||
'url' => null,
|
||||
'group' => $attrs['group-title'] ?? null,
|
||||
'attributes' => $attrs,
|
||||
];
|
||||
|
||||
unset($name, $attrs, $combined, $exploded);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (str_starts_with($line, '#EXTGRP:')) {
|
||||
$isGroup = true;
|
||||
$isHeader = false;
|
||||
|
||||
if ($isChannel) {
|
||||
$exploded = explode(':', $line);
|
||||
$channel['group'] = $exploded[1];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($isChannel) {
|
||||
$channel['url'] = str_starts_with($line, 'http') ? $line : null;
|
||||
$logoUrl = $channel['attributes']['tvg-logo'] ?? null;
|
||||
if (is_string($logoUrl)) {
|
||||
$logo = new ChannelLogo($logoUrl);
|
||||
$logo->readFile();
|
||||
$channel['logo'] = [
|
||||
'base64' => $logo->asBase64(),
|
||||
'size' => $logo->size(),
|
||||
'mime-type' => $logo->mimeType(),
|
||||
];
|
||||
}
|
||||
$result['channels'][] = $channel;
|
||||
$isChannel = false;
|
||||
unset($channel);
|
||||
}
|
||||
}
|
||||
|
||||
$groups = [];
|
||||
foreach ($result['channels'] as $channel) {
|
||||
$name = $channel['group'] ?? '(без группы)';
|
||||
$id = md5($name);
|
||||
if (empty($groups[$id])) {
|
||||
$groups[$id] = [
|
||||
'_id' => $id,
|
||||
'name' => $name,
|
||||
'channels' => [],
|
||||
];
|
||||
}
|
||||
$groups[$id]['channels'][] = $channel['_id'];
|
||||
}
|
||||
$result['groups'] = array_values($groups);
|
||||
|
||||
return $this->parsedContent = $result;
|
||||
}
|
||||
|
||||
public function check(): bool
|
||||
{
|
||||
$curl = $this->makeCurl([
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_NOBODY => true,
|
||||
CURLOPT_HEADER => true,
|
||||
CURLOPT_CUSTOMREQUEST => 'HEAD',
|
||||
]);
|
||||
|
||||
$content = curl_exec($curl);
|
||||
$this->rawContent = $content === false ? null : $content;
|
||||
$this->downloadStatus['httpCode'] = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
|
||||
$this->downloadStatus['errCode'] = curl_errno($curl);
|
||||
$this->downloadStatus['errText'] = curl_error($curl);
|
||||
$this->downloadStatus['possibleStatus'] = $this->guessStatus($this->downloadStatus['errCode']);
|
||||
curl_close($curl);
|
||||
|
||||
return $this->downloadStatus['httpCode'] < 400;
|
||||
}
|
||||
|
||||
protected function makeCurl(array $customOptions = []): CurlHandle
|
||||
{
|
||||
$options = [
|
||||
CURLOPT_URL => $this->pls,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 30,
|
||||
CURLOPT_HEADER => false,
|
||||
CURLOPT_FAILONERROR => true,
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_MAXREDIRS => 5,
|
||||
CURLOPT_USERAGENT => config('app.user_agent'),
|
||||
];
|
||||
|
||||
$curl = curl_init();
|
||||
|
||||
foreach ($options as $option => $value) {
|
||||
curl_setopt($curl, $option, $value);
|
||||
}
|
||||
|
||||
// array_merge($options, $customOptions) loses keys
|
||||
foreach ($customOptions as $option => $value) {
|
||||
curl_setopt($curl, $option, $value);
|
||||
}
|
||||
|
||||
return $curl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Парсит атрибуты строки и возвращает ассоциативный массив
|
||||
*
|
||||
* @param string $line
|
||||
* @return array
|
||||
*/
|
||||
protected function parseAttributes(string $line): array
|
||||
{
|
||||
if (str_starts_with($line, '#')) {
|
||||
$line = trim(substr($line, strpos($line, ' ') + 1));
|
||||
}
|
||||
|
||||
preg_match_all('#(?<key>[a-z-]+)="(?<value>.*)"#U', $line, $matches);
|
||||
return array_combine($matches['key'], $matches['value']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает содержимое объекта в виде массива
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'url' => $this->url,
|
||||
'name' => $this->name,
|
||||
'desc' => $this->desc,
|
||||
'pls' => $this->pls,
|
||||
'src' => $this->src,
|
||||
'status' => $this->status(),
|
||||
'content' => [
|
||||
...$this->parsed(),
|
||||
'channelCount' => count($this->parsed()['channels'])
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает ссылку на плейлист в рамках проекта
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function url(): string
|
||||
{
|
||||
return sprintf('%s/%s', base_url(), $this->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает статус скачивания плейлиста
|
||||
*
|
||||
* @return array|string[]
|
||||
*/
|
||||
public function status(): array
|
||||
{
|
||||
return $this->downloadStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает обработанное содержимое плейлиста
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function parsed(): array
|
||||
{
|
||||
return $this->parsedContent;
|
||||
}
|
||||
}
|
||||
41
app/Core/TwigExtention.php
Normal file
41
app/Core/TwigExtention.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
use Twig\Extension\AbstractExtension;
|
||||
use Twig\TwigFunction;
|
||||
|
||||
class TwigExtention extends AbstractExtension
|
||||
{
|
||||
public function getFunctions(): array
|
||||
{
|
||||
return [
|
||||
new TwigFunction('config', [$this, 'config']),
|
||||
new TwigFunction('commit', [$this, 'commit']),
|
||||
new TwigFunction('is_file', [$this, 'is_file']),
|
||||
new TwigFunction('base_url', [$this, 'base_url']),
|
||||
];
|
||||
}
|
||||
|
||||
public function config(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return config($key, $default);
|
||||
}
|
||||
|
||||
public function commit(): string
|
||||
{
|
||||
return file_get_contents(root_path('commit'));
|
||||
}
|
||||
|
||||
public function base_url(string $path = ''): string
|
||||
{
|
||||
return base_url($path);
|
||||
}
|
||||
|
||||
public function is_file(string $path): bool
|
||||
{
|
||||
return is_file($path);
|
||||
}
|
||||
}
|
||||
92
app/Errors/ErrorHandler.php
Normal file
92
app/Errors/ErrorHandler.php
Normal file
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Errors;
|
||||
|
||||
use Psr\Http\Message\{
|
||||
ResponseInterface,
|
||||
ServerRequestInterface};
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Slim\Handlers\ErrorHandler as SlimErrorHandler;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Обработчик ошибок
|
||||
*/
|
||||
class ErrorHandler extends SlimErrorHandler
|
||||
{
|
||||
/**
|
||||
* Логирует ошибку и отдаёт JSON-ответ с необходимым содержимым
|
||||
*
|
||||
* @param ServerRequestInterface $request
|
||||
* @param Throwable $exception
|
||||
* @param bool $displayErrorDetails
|
||||
* @param bool $logErrors
|
||||
* @param bool $logErrorDetails
|
||||
* @param LoggerInterface|null $logger
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function __invoke(
|
||||
ServerRequestInterface $request,
|
||||
Throwable $exception,
|
||||
bool $displayErrorDetails,
|
||||
bool $logErrors,
|
||||
bool $logErrorDetails,
|
||||
?LoggerInterface $logger = null
|
||||
): ResponseInterface {
|
||||
$payload = $this->payload($exception, $displayErrorDetails);
|
||||
|
||||
$response = app()->getResponseFactory()->createResponse();
|
||||
$response->getBody()->write(json_encode($payload, JSON_UNESCAPED_UNICODE));
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает структуру исключения для контекста
|
||||
*
|
||||
* @param Throwable $e Исключение
|
||||
* @param bool $logErrorDetails Признак дополнения деталями
|
||||
* @return array
|
||||
*/
|
||||
protected function context(Throwable $e, bool $logErrorDetails): array
|
||||
{
|
||||
$result = ['code' => $e->getCode()];
|
||||
|
||||
$logErrorDetails && $result += [
|
||||
'class' => $e::class,
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'trace' => $e->getTrace()
|
||||
];
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает структуру исключения для передачи в ответе
|
||||
*
|
||||
* @param Throwable $e Исключение
|
||||
* @param bool $displayErrorDetails Признак дополнения деталями
|
||||
* @return array
|
||||
*/
|
||||
protected function payload(Throwable $e, bool $displayErrorDetails): array
|
||||
{
|
||||
$result = [
|
||||
'error' => [
|
||||
'code' => $e->getCode(),
|
||||
'message' => $e->getMessage(),
|
||||
],
|
||||
];
|
||||
|
||||
$displayErrorDetails && $result['error'] += [
|
||||
'class' => $e::class,
|
||||
'file' => $e->getFile(),
|
||||
'line' => $e->getLine(),
|
||||
'trace' => $e->getTrace(),
|
||||
];
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
15
app/Errors/PlaylistNotFoundException.php
Normal file
15
app/Errors/PlaylistNotFoundException.php
Normal file
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Errors;
|
||||
|
||||
use Exception;
|
||||
|
||||
class PlaylistNotFoundException extends Exception
|
||||
{
|
||||
public function __construct(string $id)
|
||||
{
|
||||
parent::__construct("Плейлист $id не найден!");
|
||||
}
|
||||
}
|
||||
29
app/Middleware/RequestId.php
Normal file
29
app/Middleware/RequestId.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Middleware;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
|
||||
/**
|
||||
* Middleware для добавления запросу заголовка X-Request-ID
|
||||
*/
|
||||
class RequestId
|
||||
{
|
||||
/**
|
||||
* Добавляет запросу заголовок X-Request-ID
|
||||
*
|
||||
* @param ServerRequestInterface $request
|
||||
* @param RequestHandlerInterface $handler
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||||
{
|
||||
$request = $request->withHeader('X-Request-ID', uniqid());
|
||||
|
||||
return $handler->handle($request);
|
||||
}
|
||||
}
|
||||
159
app/helpers.php
Normal file
159
app/helpers.php
Normal file
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Core\Core;
|
||||
use App\Core\IniFile;
|
||||
use Slim\App;
|
||||
|
||||
/**
|
||||
* Returns path to root application directory
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
function root_path(string $path = ''): string
|
||||
{
|
||||
return rtrim(sprintf('%s/%s', dirname($_SERVER['DOCUMENT_ROOT']), $path), '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Return path to application configuration directory
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
function config_path(string $path = ''): string
|
||||
{
|
||||
return root_path("config/$path");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns path to app cache
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
function cache_path(string $path = ''): string
|
||||
{
|
||||
return root_path("cache/$path");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns path to app views
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
function views_path(string $path = ''): string
|
||||
{
|
||||
return root_path("views/$path");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns base URL
|
||||
*
|
||||
* @param string $route
|
||||
* @return string
|
||||
*/
|
||||
function base_url(string $route = ''): string
|
||||
{
|
||||
return rtrim(sprintf('%s/%s', env('APP_URL'), $route), '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns value of environment var
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed|null $default
|
||||
* @return mixed
|
||||
*/
|
||||
function env(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return $_ENV[$key] ?? $_SERVER[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template
|
||||
*
|
||||
* @param mixed $template
|
||||
* @param array $data
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
function view(mixed $template, array $data = []): void
|
||||
{
|
||||
$template = str_contains($template, '.twig') ? $template : "$template.twig";
|
||||
/** @noinspection PhpVoidFunctionResultUsedInspection */
|
||||
echo Flight::view()->render($template, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns core object
|
||||
*
|
||||
* @return Core
|
||||
*/
|
||||
function core(): Core
|
||||
{
|
||||
return Core::get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns app object
|
||||
*
|
||||
* @return App
|
||||
*/
|
||||
function app(): App
|
||||
{
|
||||
return Core::get()->app();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns any value as boolean
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return bool
|
||||
*/
|
||||
function bool(mixed $value): bool
|
||||
{
|
||||
is_string($value) && $value = strtolower(trim($value));
|
||||
if (in_array($value, [true, 1, '1', '+', 'y', 'yes', 'on', 'true', 'enable', 'enabled'], true)) {
|
||||
return true;
|
||||
}
|
||||
if (in_array($value, [false, 0, '0', '-', 'n', 'no', 'off', 'false', 'disable', 'disabled'], true)) {
|
||||
return false;
|
||||
}
|
||||
return (bool)$value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get config values
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed|null $default
|
||||
* @return mixed
|
||||
*/
|
||||
function config(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return Core::get()->config($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Redis instance
|
||||
*
|
||||
* @return Redis
|
||||
*/
|
||||
function redis(): Redis
|
||||
{
|
||||
return Core::get()->redis();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ini-file instance
|
||||
*
|
||||
* @return IniFile
|
||||
*/
|
||||
function ini(): IniFile
|
||||
{
|
||||
return Core::get()->ini();
|
||||
}
|
||||
Reference in New Issue
Block a user