Files
web/app/Controllers/BasicController.php
T

104 lines
2.9 KiB
PHP

<?php
/*
* Copyright (c) 2025, Антон Аксенов
* This file is part of iptv.axenov.dev web interface
* 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, array $data): ResponseInterface
{
$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);
}
}