Files
web/app/Controllers/BasicController.php
2026-01-03 01:12:18 +08:00

108 lines
3.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/*
* Copyright (c) 2025, Антон Аксенов
* This file is part of m3u.su project
* MIT License: https://git.axenov.dev/IPTV/web/src/branch/master/LICENSE
*/
declare(strict_types=1);
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Views\Twig;
use Throwable;
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
{
$code = $request->getAttributes()['code'] ?? '';
$response->withStatus(404);
$this->view($request, $response, 'notfound.twig', ['code' => $code]);
return $response;
}
/**
* Возвращает ответ в формате json
*
* @param ResponseInterface $response
* @param int $status
* @param array $data
* @return ResponseInterface
*/
protected function responseJson(ResponseInterface $response, int $status, mixed $data): ResponseInterface
{
is_scalar($data) && $data = [$data];
$data = array_merge(['timestamp' => time()], $data);
$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$response->getBody()->write($json);
return $response->withStatus($status)
->withHeader('Content-Type', 'application/json');
}
/**
* Возвращает ответ с ошибкой в формате json
*
* @param ResponseInterface $response
* @param int $status
* @param Throwable $t
* @return ResponseInterface
*/
protected function responseJsonError(ResponseInterface $response, int $status, Throwable $t): ResponseInterface
{
$data = [
'error' => [
'code' => array_last(explode('\\', $t::class)),
'message' => $t->getMessage(),
],
];
return $this->responseJson($response, $status, $data);
}
/**
* Возвращает ответ в формате html
*
* @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);
}
}