initial commit
This commit is contained in:
commit
3f64f4a49a
221 files changed
+26665
No files matched your search
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Rsgrinko\Proton\Database\Model\RecordNotFound;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Validator;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Основа контроллера: короткие помощники для того, что делается в каждом
|
||||
* действии, — отрисовать страницу, проверить данные, вернуть человека назад.
|
||||
*
|
||||
* Зависимости контроллер получает через конструктор (их собирает контейнер),
|
||||
* а не создаёт сам: тогда в тестах можно подложить свои.
|
||||
*/
|
||||
abstract class Controller
|
||||
{
|
||||
/**
|
||||
* Страница внутри каркаса.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
protected function view(string $template, array $data = [], string $title = ''): Response
|
||||
{
|
||||
// Заполненная форма и ошибки после неудачной проверки — их положило ядро
|
||||
$data['old'] = $data['old'] ?? (array) View::takeStash('old', []);
|
||||
$data['errors'] = $data['errors'] ?? (array) View::takeStash('errors', []);
|
||||
|
||||
return View::page($template, $data, $title);
|
||||
}
|
||||
|
||||
/**
|
||||
* Страница без шапки и меню — вход, регистрация.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
protected function bare(string $template, array $data = [], string $title = ''): Response
|
||||
{
|
||||
$data['old'] = $data['old'] ?? (array) View::takeStash('old', []);
|
||||
$data['errors'] = $data['errors'] ?? (array) View::takeStash('errors', []);
|
||||
|
||||
return Response::html(View::renderBare($template, $data, $title), 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Перенаправление по имени маршрута.
|
||||
*
|
||||
* @param array<string, mixed> $params
|
||||
*/
|
||||
protected function redirect(string $route, array $params = []): Response
|
||||
{
|
||||
return Response::redirect(View::route($route, $params));
|
||||
}
|
||||
|
||||
/**
|
||||
* Назад, откуда пришли. Referer может не прийти вовсе — тогда на главную.
|
||||
*/
|
||||
protected function back(Request $request): Response
|
||||
{
|
||||
$referer = $request->header('referer');
|
||||
|
||||
return Response::redirect($referer !== '' ? $referer : View::route('home'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Сообщение на следующей странице.
|
||||
*/
|
||||
protected function flash(string $message, string $type = 'ok'): void
|
||||
{
|
||||
View::flash($message, $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка данных запроса. Не прошла — исключение, которое ядро превратит
|
||||
* в возврат на форму с сообщениями (или в 422 для API).
|
||||
*
|
||||
* @param array<string, string> $rules
|
||||
* @param array<string, string> $labels
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function validate(Request $request, array $rules, array $labels = []): array
|
||||
{
|
||||
return Validator::make($request->all(), $rules, $labels)->validate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Запись обязана быть, иначе — «не найдено» с возвратом в список.
|
||||
*
|
||||
* @template T of Model
|
||||
*
|
||||
* @param T|null $record
|
||||
*
|
||||
* @return T
|
||||
*/
|
||||
protected function require(?Model $record, string $route = '', string $message = 'Запись не найдена'): Model
|
||||
{
|
||||
if ($record === null) {
|
||||
throw new RecordNotFound($message, $route);
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сколько записей показывать на странице.
|
||||
*/
|
||||
protected function perPage(): int
|
||||
{
|
||||
return max(5, (int) Config::get('ui.per_page', 25));
|
||||
}
|
||||
|
||||
/**
|
||||
* Номер страницы из запроса.
|
||||
*/
|
||||
protected function page(Request $request): int
|
||||
{
|
||||
return max(1, (int) $request->query('page', 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Auth\Csrf;
|
||||
use Rsgrinko\Proton\Database\Model\RecordNotFound;
|
||||
use Rsgrinko\Proton\Http\Middleware\ApiKey;
|
||||
use Rsgrinko\Proton\Http\Middleware\Authenticate;
|
||||
use Rsgrinko\Proton\Http\Middleware\Can;
|
||||
use Rsgrinko\Proton\Http\Middleware\Guest;
|
||||
use Rsgrinko\Proton\Http\Middleware\Install;
|
||||
use Rsgrinko\Proton\Http\Middleware\Throttle;
|
||||
use Rsgrinko\Proton\Http\Middleware\VerifyCsrf;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Logger;
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
use Rsgrinko\Proton\Support\RequestId;
|
||||
use Rsgrinko\Proton\Support\ValidationException;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Ядро HTTP: собирает роутер, прогоняет запрос и превращает любое исключение
|
||||
* в понятный ответ.
|
||||
*
|
||||
* Файлы маршрутов перечислены в config/config.php (routes). Ответ на ошибку
|
||||
* зависит от того, чего ждёт клиент: браузеру — страница, API — JSON.
|
||||
*/
|
||||
final class Kernel
|
||||
{
|
||||
private ?Router $router = null;
|
||||
|
||||
private Logger $logger;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->logger = new Logger('http');
|
||||
}
|
||||
|
||||
public function handle(Request $request): Response
|
||||
{
|
||||
// Сквозная цепочка: клиент прислал свою или заводим новую
|
||||
RequestId::set($request->header(RequestId::HEADER));
|
||||
|
||||
try {
|
||||
return $this->finish($this->router()->dispatch($request));
|
||||
} catch (RecordNotFound $e) {
|
||||
return $this->finish($this->notFound($request, $e));
|
||||
} catch (ValidationException $e) {
|
||||
return $this->finish($this->invalid($request, $e));
|
||||
} catch (Throwable $e) {
|
||||
return $this->finish($this->crashed($request, $e));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Роутер собирается при первом запросе, а не в конструкторе: прослойки
|
||||
* ходят в базу, и её падение должно попасть в обработчик ошибок.
|
||||
*/
|
||||
public function router(): Router
|
||||
{
|
||||
if ($this->router !== null) {
|
||||
return $this->router;
|
||||
}
|
||||
|
||||
$router = new Router();
|
||||
|
||||
$router->middleware('csrf', new VerifyCsrf())
|
||||
->middleware('auth', new Authenticate())
|
||||
->middleware('guest', new Guest())
|
||||
->middleware('can', new Can())
|
||||
->middleware('api', new ApiKey())
|
||||
->middleware('throttle', new Throttle())
|
||||
->middleware('install', new Install());
|
||||
|
||||
foreach ((array) Config::get('routes', ['routes/web.php']) as $file) {
|
||||
$router->load(APP_ROOT . '/' . ltrim((string) $file, '/'));
|
||||
}
|
||||
|
||||
return $this->router = $router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Куки навешиваются здесь: их ставит Auth (долгая «запомнить меня») и Csrf
|
||||
* (токен форм), а заголовки есть только у ответа. Одно место на все ветки,
|
||||
* включая страницу ошибки, — про куку нельзя забыть.
|
||||
*/
|
||||
private function finish(Response $response): Response
|
||||
{
|
||||
return Csrf::applyCookie(Auth::applyCookies($response))
|
||||
->withHeader(RequestId::HEADER, RequestId::current());
|
||||
}
|
||||
|
||||
private function notFound(Request $request, RecordNotFound $e): Response
|
||||
{
|
||||
if ($request->wantsJson()) {
|
||||
return Response::error($e->getMessage(), 404);
|
||||
}
|
||||
|
||||
// Раздел сказал, куда возвращать человека, — вернём со словами
|
||||
if ($e->route() !== '') {
|
||||
View::flash($e->getMessage(), 'error');
|
||||
|
||||
return Response::redirect(View::route($e->route()));
|
||||
}
|
||||
|
||||
return Response::html(View::render('errors/404', ['message' => $e->getMessage()], 'Не найдено'), 404);
|
||||
}
|
||||
|
||||
private function invalid(Request $request, ValidationException $e): Response
|
||||
{
|
||||
if ($request->wantsJson()) {
|
||||
return Response::error('Данные не прошли проверку', 422, ['errors' => $e->errors()]);
|
||||
}
|
||||
|
||||
// Форму возвращаем человеку заполненной: перебивать всё заново незачем
|
||||
View::stash('old', $request->all());
|
||||
View::stash('errors', $e->errors());
|
||||
View::flash($e->first(), 'error');
|
||||
|
||||
return Response::redirect($request->header('referer') !== '' ? $request->header('referer') : $request->fullPath());
|
||||
}
|
||||
|
||||
private function crashed(Request $request, Throwable $e): Response
|
||||
{
|
||||
// По этому коду ошибку находят в логе: текст исключения пользователю не показываем
|
||||
$code = strtoupper(bin2hex(random_bytes(3)));
|
||||
|
||||
$this->logger->error('Ошибка запроса', [
|
||||
'code' => $code,
|
||||
'path' => $request->path,
|
||||
'error' => $e->getMessage(),
|
||||
'file' => $e->getFile() . ':' . $e->getLine(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
]);
|
||||
|
||||
$debug = (bool) Config::get('app.debug', false);
|
||||
|
||||
$details = $debug
|
||||
? $e->getMessage() . ' (' . $e->getFile() . ':' . $e->getLine() . ')'
|
||||
: 'Внутренняя ошибка. Подробности в логе, код ошибки: ' . $code;
|
||||
|
||||
if ($request->wantsJson()) {
|
||||
return Response::error($details, $e instanceof ProtonException && $e->getCode() >= 400 ? (int) $e->getCode() : 500);
|
||||
}
|
||||
|
||||
return Response::html(View::render('errors/500', [
|
||||
'message' => $details,
|
||||
'trace' => $debug ? $e->getTraceAsString() : '',
|
||||
], 'Ошибка'), 500);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Models\ApiToken;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Support\IpAllowlist;
|
||||
|
||||
/**
|
||||
* Ключ API: Authorization: Bearer ptn_xxx_yyy.
|
||||
*
|
||||
* Ключ — такой же вход в данные, как и пароль, поэтому область видимости
|
||||
* действует и здесь: в атрибуты кладётся владелец ключа, его viewer и scope,
|
||||
* и контроллер API работает ровно с теми записями, что и его хозяин в панели.
|
||||
*/
|
||||
final class ApiKey
|
||||
{
|
||||
public function __invoke(Request $request, callable $next): Response
|
||||
{
|
||||
$key = $request->bearerToken();
|
||||
|
||||
if ($key === '') {
|
||||
return Response::error('Не передан ключ доступа: Authorization: Bearer <ключ>', 401);
|
||||
}
|
||||
|
||||
$token = ApiToken::match($key);
|
||||
|
||||
if ($token === null) {
|
||||
return Response::error('Ключ доступа не найден или отключён', 401);
|
||||
}
|
||||
|
||||
$allowed = trim((string) $token->raw('allowed_ips'));
|
||||
|
||||
// Пустой список — ограничения нет; заполненный проверяем целиком,
|
||||
// включая сети CIDR
|
||||
if ($allowed !== '' && !IpAllowlist::allows($allowed, $request->ip())) {
|
||||
return Response::error('Этот ключ нельзя использовать с адреса ' . $request->ip(), 403);
|
||||
}
|
||||
|
||||
$user = User::find((int) $token->raw('user_id'));
|
||||
|
||||
if ($user === null || !$user->isActive()) {
|
||||
return Response::error('Владелец ключа отключён', 403);
|
||||
}
|
||||
|
||||
$token->markUsed($request->ip());
|
||||
|
||||
$viewer = Viewer::fromUser($user);
|
||||
|
||||
$request->setAttribute('token', $token)
|
||||
->setAttribute('user', $user)
|
||||
->setAttribute('viewer', $viewer)
|
||||
->setAttribute('scope', $viewer->scope());
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Install\Installer;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Пускает только вошедших. Заодно кладёт в атрибуты запроса пользователя,
|
||||
* viewer и область видимости — роутер подставит их в контроллер по именам
|
||||
* аргументов, и лезть в сессию из контроллера не придётся.
|
||||
*/
|
||||
final class Authenticate
|
||||
{
|
||||
public function __invoke(Request $request, callable $next): Response
|
||||
{
|
||||
// Приложение ещё не установлено — сначала установщик, а не форма входа
|
||||
if (!Installer::installed()) {
|
||||
return Response::redirect(View::route('install'));
|
||||
}
|
||||
|
||||
$user = Auth::user();
|
||||
|
||||
if ($user === null) {
|
||||
if ($request->wantsJson()) {
|
||||
return Response::error('Нужно войти', 401);
|
||||
}
|
||||
|
||||
// Куда вернуть после входа: человек шёл по ссылке, а не на главную
|
||||
View::stash('intended', $request->fullPath());
|
||||
|
||||
return Response::redirect(View::route('login'));
|
||||
}
|
||||
|
||||
$viewer = Auth::viewer();
|
||||
|
||||
$request->setAttribute('user', $user)
|
||||
->setAttribute('viewer', $viewer)
|
||||
->setAttribute('scope', $viewer->scope());
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Проверка права: can:users.manage. Несколько прав через черту — «хватит любого»:
|
||||
* can:notes.view|notes.manage.
|
||||
*
|
||||
* Ставится прослойкой у группы маршрутов, а не проверкой в контроллере: так
|
||||
* забыть её можно только вместе со всей группой.
|
||||
*/
|
||||
final class Can
|
||||
{
|
||||
public function __invoke(Request $request, callable $next, string $permission = ''): Response
|
||||
{
|
||||
$viewer = Auth::viewer();
|
||||
|
||||
$permissions = array_values(array_filter(explode('|', $permission)));
|
||||
|
||||
if ($permissions === [] || $viewer->canAny($permissions)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if ($request->wantsJson()) {
|
||||
return Response::error('Недостаточно прав', 403);
|
||||
}
|
||||
|
||||
return Response::html(View::render('errors/403', [
|
||||
'message' => 'Этот раздел вам не доступен.',
|
||||
], 'Нет доступа'), 403);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Install\Installer;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Только для не вошедших: форма входа и регистрация. Вошедшего уводим на
|
||||
* главную — показывать ему форму входа незачем.
|
||||
*/
|
||||
final class Guest
|
||||
{
|
||||
public function __invoke(Request $request, callable $next): Response
|
||||
{
|
||||
if (!Installer::installed()) {
|
||||
return Response::redirect(View::route('install'));
|
||||
}
|
||||
|
||||
if (Auth::check()) {
|
||||
return Response::redirect(View::route('home'));
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Install\Installer;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Веб-установщик открыт, только пока приложение не установлено.
|
||||
*
|
||||
* Иначе мастером воспользовался бы любой прохожий: он пишет .env и заводит
|
||||
* администратора.
|
||||
*/
|
||||
final class Install
|
||||
{
|
||||
public function __invoke(Request $request, callable $next): Response
|
||||
{
|
||||
if (Installer::installed()) {
|
||||
return Response::redirect(View::route('home'));
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Models\ApiToken;
|
||||
use Rsgrinko\Proton\RateLimit\RateLimiter;
|
||||
|
||||
/**
|
||||
* Ограничение частоты: throttle:60,60 — не больше 60 запросов за 60 секунд.
|
||||
*
|
||||
* Считаем по ключу API, если он есть, иначе по адресу: иначе один клиент за
|
||||
* общим NAT перекрыл бы кислород всем соседям.
|
||||
*/
|
||||
final class Throttle
|
||||
{
|
||||
public function __invoke(Request $request, callable $next, string $options = '60,60'): Response
|
||||
{
|
||||
[$max, $seconds] = array_pad(explode(',', $options), 2, '60');
|
||||
|
||||
$max = max(1, (int) $max);
|
||||
$seconds = max(1, (int) $seconds);
|
||||
|
||||
$limiter = new RateLimiter();
|
||||
$key = 'throttle:' . $this->subject($request) . ':' . $seconds;
|
||||
|
||||
if (!$limiter->attempt($key, $max, $seconds)) {
|
||||
$retry = $limiter->retryAfter($key);
|
||||
|
||||
return Response::error('Слишком много запросов, попробуйте позже', 429, ['retry_after' => $retry])
|
||||
->withHeader('Retry-After', (string) max(1, $retry));
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
private function subject(Request $request): string
|
||||
{
|
||||
$token = $request->attribute('token');
|
||||
|
||||
if ($token instanceof ApiToken) {
|
||||
return 'token:' . $token->id();
|
||||
}
|
||||
|
||||
return 'ip:' . $request->ip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http\Middleware;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Csrf;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Сверяет токен формы при любом изменяющем запросе.
|
||||
*
|
||||
* Вешается на группу веб-маршрутов целиком: забыть её на одном контроллере
|
||||
* куда проще, чем на всей группе. API это не касается — там ключ в заголовке,
|
||||
* а не кука, и подделать запрос с чужого сайта нельзя.
|
||||
*/
|
||||
final class VerifyCsrf
|
||||
{
|
||||
public function __invoke(Request $request, callable $next): Response
|
||||
{
|
||||
if (!$request->isWriting()) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$token = (string) $request->input(Csrf::FIELD, $request->header(Csrf::HEADER));
|
||||
|
||||
if (Csrf::check($token)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if ($request->wantsJson()) {
|
||||
return Response::error('Форма устарела, обновите страницу', 403);
|
||||
}
|
||||
|
||||
View::flash('Форма устарела. Обновите страницу и попробуйте ещё раз', 'error');
|
||||
|
||||
return Response::html(View::render('errors/403', [
|
||||
'message' => 'Не сходится токен формы. Обычно это значит, что страница была открыта слишком долго.',
|
||||
], 'Форма устарела'), 403);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http;
|
||||
|
||||
use Rsgrinko\Proton\Files\UploadedFile;
|
||||
use Rsgrinko\Proton\Support\ClientIp;
|
||||
|
||||
/**
|
||||
* Входящий HTTP-запрос в удобном виде.
|
||||
*
|
||||
* Собирается из суперглобальных один раз в точке входа; всё дальше по коду
|
||||
* работает с этим объектом — в том числе тесты, которые собирают запрос руками.
|
||||
*/
|
||||
final class Request
|
||||
{
|
||||
public string $method = 'GET';
|
||||
|
||||
public string $path = '/';
|
||||
|
||||
/** @var array<string, mixed> */
|
||||
public array $query = [];
|
||||
|
||||
/** @var array<string, string> Заголовки, имена в нижнем регистре */
|
||||
public array $headers = [];
|
||||
|
||||
public string $rawBody = '';
|
||||
|
||||
/** @var array<string, mixed> Разобранное тело: JSON или обычная форма */
|
||||
public array $body = [];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public array $cookies = [];
|
||||
|
||||
/** @var array<string, UploadedFile> Присланные файлы */
|
||||
public array $files = [];
|
||||
|
||||
/** @var array<string, mixed> Что положили прослойки: пользователь, область видимости */
|
||||
public array $attributes = [];
|
||||
|
||||
/**
|
||||
* Запрос из суперглобальных переменных.
|
||||
*/
|
||||
public static function fromGlobals(): self
|
||||
{
|
||||
$request = new self();
|
||||
|
||||
$request->method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
|
||||
$request->path = self::normalizePath((string) ($_SERVER['REQUEST_URI'] ?? '/'));
|
||||
$request->query = $_GET;
|
||||
$request->headers = self::readHeaders();
|
||||
$request->cookies = array_map('strval', $_COOKIE);
|
||||
$request->rawBody = (string) file_get_contents('php://input');
|
||||
$request->body = self::parseBody($request);
|
||||
$request->files = UploadedFile::fromGlobals($_FILES);
|
||||
|
||||
// Метод формы: браузер умеет только GET и POST, а маршруты бывают
|
||||
// и PUT, и DELETE — форма кладёт настоящий метод скрытым полем
|
||||
$override = strtoupper((string) ($request->body['_method'] ?? ''));
|
||||
|
||||
if ($request->method === 'POST' && in_array($override, ['PUT', 'PATCH', 'DELETE'], true)) {
|
||||
$request->method = $override;
|
||||
}
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Запрос для тестов и внутренних вызовов.
|
||||
*
|
||||
* @param array<string, mixed> $body
|
||||
* @param array<string, mixed> $query
|
||||
* @param array<string, string> $headers
|
||||
*/
|
||||
public static function create(string $method, string $path, array $body = [], array $query = [], array $headers = []): self
|
||||
{
|
||||
$request = new self();
|
||||
|
||||
$request->method = strtoupper($method);
|
||||
$request->path = self::normalizePath($path);
|
||||
$request->query = $query;
|
||||
$request->body = $body;
|
||||
$request->headers = array_change_key_case($headers, CASE_LOWER);
|
||||
$request->rawBody = $body === [] ? '' : (string) json_encode($body, JSON_UNESCAPED_UNICODE);
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
public function header(string $name): string
|
||||
{
|
||||
return $this->headers[strtolower($name)] ?? '';
|
||||
}
|
||||
|
||||
public function cookie(string $name, string $default = ''): string
|
||||
{
|
||||
return $this->cookies[$name] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Значение из query-строки.
|
||||
*/
|
||||
public function query(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return $this->query[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Значение из тела запроса.
|
||||
*/
|
||||
public function input(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return $this->body[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Тело плюс query-строка — то, что обычно и нужно форме.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
return array_merge($this->query, $this->body);
|
||||
}
|
||||
|
||||
/**
|
||||
* Только перечисленные поля.
|
||||
*
|
||||
* @param array<int, string> $keys
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function only(array $keys): array
|
||||
{
|
||||
$all = $this->all();
|
||||
$result = [];
|
||||
|
||||
foreach ($keys as $key) {
|
||||
if (array_key_exists($key, $all)) {
|
||||
$result[$key] = $all[$key];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function has(string $key): bool
|
||||
{
|
||||
return array_key_exists($key, $this->all());
|
||||
}
|
||||
|
||||
/**
|
||||
* Галочка формы: браузер шлёт «on» или не шлёт ничего.
|
||||
*/
|
||||
public function boolean(string $key): bool
|
||||
{
|
||||
return in_array((string) $this->input($key, $this->query($key, '')), ['1', 'on', 'true', 'yes'], true);
|
||||
}
|
||||
|
||||
public function integer(string $key, int $default = 0): int
|
||||
{
|
||||
$value = $this->input($key, $this->query($key, null));
|
||||
|
||||
return $value === null || $value === '' ? $default : (int) $value;
|
||||
}
|
||||
|
||||
public function text(string $key, string $default = ''): string
|
||||
{
|
||||
$value = $this->input($key, $this->query($key, null));
|
||||
|
||||
return $value === null ? $default : trim((string) $value);
|
||||
}
|
||||
|
||||
public function file(string $key): ?UploadedFile
|
||||
{
|
||||
return $this->files[$key] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Данные, положенные прослойкой.
|
||||
*/
|
||||
public function attribute(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return $this->attributes[$key] ?? $default;
|
||||
}
|
||||
|
||||
public function setAttribute(string $key, mixed $value): self
|
||||
{
|
||||
$this->attributes[$key] = $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function isMethod(string $method): bool
|
||||
{
|
||||
return $this->method === strtoupper($method);
|
||||
}
|
||||
|
||||
/**
|
||||
* Меняет ли запрос состояние — по этому признаку работает проверка токена форм.
|
||||
*/
|
||||
public function isWriting(): bool
|
||||
{
|
||||
return in_array($this->method, ['POST', 'PUT', 'PATCH', 'DELETE'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ждёт ли клиент JSON: запрос от fetch или к API.
|
||||
*/
|
||||
public function wantsJson(): bool
|
||||
{
|
||||
return str_contains($this->header('accept'), 'application/json')
|
||||
|| str_contains($this->header('content-type'), 'application/json')
|
||||
|| strtolower($this->header('x-requested-with')) === 'xmlhttprequest';
|
||||
}
|
||||
|
||||
/**
|
||||
* API-ключ из заголовка Authorization: Bearer <ключ>, понимаем и X-Api-Key.
|
||||
*/
|
||||
public function bearerToken(): string
|
||||
{
|
||||
$auth = $this->header('authorization');
|
||||
|
||||
if (stripos($auth, 'bearer ') === 0) {
|
||||
return trim(substr($auth, 7));
|
||||
}
|
||||
|
||||
return trim($this->header('x-api-key'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Почему разобранное тело пустое. Сломанный JSON стоит отличать от честно
|
||||
* пустого запроса: иначе клиент с опечаткой в кавычке ищет ошибку не там.
|
||||
*/
|
||||
public function bodyError(): ?string
|
||||
{
|
||||
if ($this->body !== [] || trim($this->rawBody) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!str_contains($this->header('content-type'), 'application/json')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$decoded = json_decode($this->rawBody, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
return 'Не удалось разобрать JSON: ' . json_last_error_msg();
|
||||
}
|
||||
|
||||
return is_array($decoded) ? null : 'Тело запроса должно быть объектом JSON';
|
||||
}
|
||||
|
||||
/**
|
||||
* Адрес клиента: за прокси берётся из X-Forwarded-For, но только если запрос
|
||||
* пришёл от доверенного прокси — иначе заголовок подделает кто угодно.
|
||||
*/
|
||||
public function ip(): string
|
||||
{
|
||||
$ip = ClientIp::resolve(
|
||||
(string) ($_SERVER['REMOTE_ADDR'] ?? ''),
|
||||
$this->header('x-forwarded-for')
|
||||
);
|
||||
|
||||
return $ip === '' ? 'unknown' : $ip;
|
||||
}
|
||||
|
||||
public function userAgent(): string
|
||||
{
|
||||
return trim($this->header('user-agent'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Полный адрес с query-строкой — для ссылки «вернуться назад».
|
||||
*/
|
||||
public function fullPath(): string
|
||||
{
|
||||
return $this->query === [] ? $this->path : $this->path . '?' . http_build_query($this->query);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private static function readHeaders(): array
|
||||
{
|
||||
$headers = [];
|
||||
|
||||
foreach ($_SERVER as $key => $value) {
|
||||
if (str_starts_with((string) $key, 'HTTP_')) {
|
||||
$headers[strtolower(str_replace('_', '-', substr((string) $key, 5)))] = (string) $value;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($_SERVER['CONTENT_TYPE'])) {
|
||||
$headers['content-type'] = (string) $_SERVER['CONTENT_TYPE'];
|
||||
}
|
||||
|
||||
if (isset($_SERVER['CONTENT_LENGTH'])) {
|
||||
$headers['content-length'] = (string) $_SERVER['CONTENT_LENGTH'];
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function parseBody(self $request): array
|
||||
{
|
||||
$type = $request->header('content-type');
|
||||
|
||||
if (str_contains($type, 'application/json')) {
|
||||
$decoded = json_decode($request->rawBody, true);
|
||||
|
||||
return is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
|
||||
if (in_array($request->method, ['POST', 'PUT', 'PATCH', 'DELETE'], true) && $_POST !== []) {
|
||||
return $_POST;
|
||||
}
|
||||
|
||||
if ($request->rawBody !== '' && str_contains($type, 'application/x-www-form-urlencoded')) {
|
||||
parse_str($request->rawBody, $parsed);
|
||||
|
||||
return $parsed;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Путь без хвостового слэша — так же его нормализует маршрут.
|
||||
*/
|
||||
private static function normalizePath(string $uri): string
|
||||
{
|
||||
$path = rtrim((string) (parse_url($uri, PHP_URL_PATH) ?: '/'), '/');
|
||||
|
||||
return $path === '' ? '/' : $path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http;
|
||||
|
||||
/**
|
||||
* Ответ приложения: тело, код, заголовки и куки.
|
||||
*
|
||||
* Куки лежат отдельным списком, а не в карте заголовков: их в одном ответе
|
||||
* бывает несколько (сессия, «запомнить меня», токен форм), и в карте вторая
|
||||
* затёрла бы первую.
|
||||
*/
|
||||
final class Response
|
||||
{
|
||||
private int $status;
|
||||
|
||||
private string $body;
|
||||
|
||||
/** @var array<string, string> */
|
||||
private array $headers;
|
||||
|
||||
/** @var array<int, string> Готовые значения Set-Cookie */
|
||||
private array $cookies = [];
|
||||
|
||||
/**
|
||||
* @param array<string, string> $headers
|
||||
*/
|
||||
public function __construct(string $body = '', int $status = 200, array $headers = [])
|
||||
{
|
||||
$this->body = $body;
|
||||
$this->status = $status;
|
||||
$this->headers = $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function json(array $data, int $status = 200): self
|
||||
{
|
||||
return new self(
|
||||
(string) json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT),
|
||||
$status,
|
||||
['Content-Type' => 'application/json; charset=utf-8']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ошибка в едином формате: {"error": {...}}.
|
||||
*
|
||||
* @param array<string, mixed> $details
|
||||
*/
|
||||
public static function error(string $message, int $status = 400, array $details = []): self
|
||||
{
|
||||
$error = ['message' => $message, 'status' => $status];
|
||||
|
||||
if ($details !== []) {
|
||||
$error['details'] = $details;
|
||||
}
|
||||
|
||||
return self::json(['error' => $error], $status);
|
||||
}
|
||||
|
||||
public static function html(string $html, int $status = 200): self
|
||||
{
|
||||
return new self($html, $status, ['Content-Type' => 'text/html; charset=utf-8']);
|
||||
}
|
||||
|
||||
public static function text(string $text, int $status = 200): self
|
||||
{
|
||||
return new self($text, $status, ['Content-Type' => 'text/plain; charset=utf-8']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Перенаправление — после любого действия, меняющего данные: перезагрузка
|
||||
* страницы не должна отправлять форму второй раз.
|
||||
*/
|
||||
public static function redirect(string $location, int $status = 302): self
|
||||
{
|
||||
return new self('', $status, ['Location' => $location]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Файл на скачивание.
|
||||
*/
|
||||
public static function download(string $content, string $fileName, string $type = 'application/octet-stream'): self
|
||||
{
|
||||
return new self($content, 200, [
|
||||
'Content-Type' => $type,
|
||||
'Content-Disposition' => 'attachment; filename="' . str_replace('"', '', $fileName) . '"',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Отдача файла с диска — картинки и вложения из хранилища.
|
||||
*/
|
||||
public static function file(string $path, string $type = 'application/octet-stream', bool $download = false): self
|
||||
{
|
||||
$response = new self((string) file_get_contents($path), 200, ['Content-Type' => $type]);
|
||||
|
||||
if ($download) {
|
||||
$response->withHeader('Content-Disposition', 'attachment; filename="' . basename($path) . '"');
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function withHeader(string $name, string $value): self
|
||||
{
|
||||
$this->headers[$name] = $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function withStatus(int $status): self
|
||||
{
|
||||
$this->status = $status;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Готовая строка Set-Cookie.
|
||||
*/
|
||||
public function withCookie(string $cookie): self
|
||||
{
|
||||
$this->cookies[] = $cookie;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function cookies(): array
|
||||
{
|
||||
return $this->cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function headers(): array
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
public function header(string $name): string
|
||||
{
|
||||
foreach ($this->headers as $key => $value) {
|
||||
if (strcasecmp($key, $name) === 0) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
public function status(): int
|
||||
{
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
public function body(): string
|
||||
{
|
||||
return $this->body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Отдаёт ответ клиенту.
|
||||
*/
|
||||
public function send(): void
|
||||
{
|
||||
http_response_code($this->status);
|
||||
|
||||
foreach ($this->headers as $name => $value) {
|
||||
header($name . ': ' . $value);
|
||||
}
|
||||
|
||||
// Куки добавляем, а не заменяем: PHP уже положил в Set-Cookie куку сессии,
|
||||
// и header() со значением по умолчанию выбросил бы её — сессия не держалась бы
|
||||
foreach ($this->cookies as $cookie) {
|
||||
header('Set-Cookie: ' . $cookie, false);
|
||||
}
|
||||
|
||||
echo $this->body;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http;
|
||||
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
|
||||
/**
|
||||
* Один маршрут: методы, шаблон пути, обработчик и прослойки.
|
||||
*
|
||||
* Шаблон пишется как '/admin/users/{id}'. Параметру можно задать ограничение
|
||||
* через двоеточие — '{id:\d+}'; без него берётся любой кусок пути до слэша.
|
||||
* Числовым параметрам ограничение ставить стоит: иначе '/users/new' попадёт
|
||||
* в маршрут '/users/{id}'.
|
||||
*/
|
||||
final class Route
|
||||
{
|
||||
/** @var array<int, string> */
|
||||
public array $methods;
|
||||
|
||||
public string $pattern;
|
||||
|
||||
/** @var callable|array{0: class-string, 1: string} */
|
||||
public mixed $handler;
|
||||
|
||||
/** @var array<int, string> Имена прослоек в порядке применения */
|
||||
public array $middleware;
|
||||
|
||||
public ?string $name = null;
|
||||
|
||||
/** Собранная регулярка — считаем один раз */
|
||||
private ?string $regex = null;
|
||||
|
||||
/**
|
||||
* @param array<int, string> $methods
|
||||
* @param callable|array{0: class-string, 1: string} $handler
|
||||
* @param array<int, string> $middleware
|
||||
*/
|
||||
public function __construct(array $methods, string $pattern, mixed $handler, array $middleware = [])
|
||||
{
|
||||
$this->methods = array_map('strtoupper', $methods);
|
||||
$this->pattern = self::normalize($pattern);
|
||||
$this->handler = $handler;
|
||||
$this->middleware = $middleware;
|
||||
}
|
||||
|
||||
/**
|
||||
* Имя маршрута — по нему потом собирается адрес. Адреса нигде не пишутся
|
||||
* строкой: поменялся путь — правится одна строка в файле маршрутов.
|
||||
*/
|
||||
public function name(string $name): self
|
||||
{
|
||||
$this->name = $name;
|
||||
|
||||
Router::remember($this);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Своя прослойка на один маршрут.
|
||||
*/
|
||||
public function middleware(string ...$names): self
|
||||
{
|
||||
foreach ($names as $name) {
|
||||
$this->middleware[] = $name;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сопоставляет путь с шаблоном: параметры или null, если не подошло.
|
||||
*
|
||||
* @return array<string, string>|null
|
||||
*/
|
||||
public function match(string $path): ?array
|
||||
{
|
||||
if (preg_match($this->regex(), self::normalize($path), $matches) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$params = [];
|
||||
|
||||
foreach ($matches as $key => $value) {
|
||||
if (is_string($key)) {
|
||||
$params[$key] = rawurldecode((string) $value);
|
||||
}
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
public function allows(string $method): bool
|
||||
{
|
||||
return in_array(strtoupper($method), $this->methods, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Собирает адрес: подставляет параметры, остальное уходит в query-строку.
|
||||
*
|
||||
* @param array<string, mixed> $params
|
||||
*/
|
||||
public function url(array $params = []): string
|
||||
{
|
||||
$path = (string) preg_replace_callback(
|
||||
'#\{([a-zA-Z_][a-zA-Z0-9_]*)(?::[^{}]+)?\}#',
|
||||
static function (array $m) use (&$params): string {
|
||||
$name = $m[1];
|
||||
|
||||
if (!array_key_exists($name, $params)) {
|
||||
throw new ProtonException('Для адреса не хватает параметра «' . $name . '»');
|
||||
}
|
||||
|
||||
$value = (string) $params[$name];
|
||||
|
||||
unset($params[$name]);
|
||||
|
||||
return rawurlencode($value);
|
||||
},
|
||||
$this->pattern
|
||||
);
|
||||
|
||||
$params = array_filter($params, static fn (mixed $value): bool => $value !== '' && $value !== null);
|
||||
|
||||
return $params === [] ? $path : $path . '?' . http_build_query($params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Путь без хвостового слэша — так же его нормализует запрос.
|
||||
*/
|
||||
public static function normalize(string $path): string
|
||||
{
|
||||
$path = rtrim($path, '/');
|
||||
|
||||
return $path === '' ? '/' : $path;
|
||||
}
|
||||
|
||||
private function regex(): string
|
||||
{
|
||||
if ($this->regex === null) {
|
||||
$regex = (string) preg_replace_callback(
|
||||
'#\{([a-zA-Z_][a-zA-Z0-9_]*)(?::([^{}]+))?\}#',
|
||||
static fn (array $m): string => '(?P<' . $m[1] . '>' . ($m[2] ?? '[^/]+') . ')',
|
||||
$this->pattern
|
||||
);
|
||||
|
||||
$this->regex = '#^' . $regex . '$#u';
|
||||
}
|
||||
|
||||
return $this->regex;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Http;
|
||||
|
||||
use ReflectionFunctionAbstract;
|
||||
use ReflectionMethod;
|
||||
use ReflectionNamedType;
|
||||
use Rsgrinko\Proton\Support\Container;
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
|
||||
/**
|
||||
* Роутер. Маршруты описываются в файлах routes/:
|
||||
*
|
||||
* $router->group(['prefix' => '/admin', 'middleware' => ['auth', 'can:users.manage']], function (Router $router) {
|
||||
* $router->get('/users', [UsersController::class, 'index'])->name('admin.users');
|
||||
* $router->get('/users/{id:\d+}', [UsersController::class, 'show'])->name('admin.users.show');
|
||||
* });
|
||||
*
|
||||
* Обработчик — замыкание или пара [класс, метод]: класс создаётся, только если
|
||||
* маршрут совпал, и получает зависимости из контейнера. Аргументы метода
|
||||
* подставляются по именам: Request — сам запрос, {id} — из адреса (с приведением
|
||||
* к типу аргумента), остальное — из атрибутов, которые кладут прослойки.
|
||||
*/
|
||||
final class Router
|
||||
{
|
||||
/** @var array<int, Route> */
|
||||
private array $routes = [];
|
||||
|
||||
/** @var array<string, callable> Прослойки по именам */
|
||||
private array $middleware = [];
|
||||
|
||||
/** @var array{prefix: string, middleware: array<int, string>} Текущая группа */
|
||||
private array $group = ['prefix' => '', 'middleware' => []];
|
||||
|
||||
/** @var array<string, Route> Именованные маршруты — общие для всех роутеров */
|
||||
private static array $named = [];
|
||||
|
||||
/**
|
||||
* Подключает файл маршрутов. Файл возвращает функцию, принимающую роутер.
|
||||
*/
|
||||
public function load(string $file): self
|
||||
{
|
||||
if (!is_file($file)) {
|
||||
throw new ProtonException('Файл маршрутов не найден: ' . $file);
|
||||
}
|
||||
|
||||
$definition = require $file;
|
||||
|
||||
if (!is_callable($definition)) {
|
||||
throw new ProtonException('Файл маршрутов должен возвращать функцию: ' . $file);
|
||||
}
|
||||
|
||||
$definition($this);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Регистрирует прослойку под именем, которым её потом зовут маршруты.
|
||||
*/
|
||||
public function middleware(string $name, callable $handler): self
|
||||
{
|
||||
$this->middleware[$name] = $handler;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Общий префикс и прослойки для группы. Группы вкладываются друг в друга.
|
||||
*
|
||||
* @param array{prefix?: string, middleware?: string|array<int, string>} $options
|
||||
*/
|
||||
public function group(array $options, callable $routes): self
|
||||
{
|
||||
$previous = $this->group;
|
||||
|
||||
$this->group = [
|
||||
'prefix' => $previous['prefix'] . rtrim((string) ($options['prefix'] ?? ''), '/'),
|
||||
'middleware' => array_merge($previous['middleware'], (array) ($options['middleware'] ?? [])),
|
||||
];
|
||||
|
||||
$routes($this);
|
||||
|
||||
$this->group = $previous;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable|array{0: class-string, 1: string} $handler
|
||||
*/
|
||||
public function get(string $pattern, mixed $handler): Route
|
||||
{
|
||||
return $this->add(['GET'], $pattern, $handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable|array{0: class-string, 1: string} $handler
|
||||
*/
|
||||
public function post(string $pattern, mixed $handler): Route
|
||||
{
|
||||
return $this->add(['POST'], $pattern, $handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable|array{0: class-string, 1: string} $handler
|
||||
*/
|
||||
public function put(string $pattern, mixed $handler): Route
|
||||
{
|
||||
return $this->add(['PUT'], $pattern, $handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable|array{0: class-string, 1: string} $handler
|
||||
*/
|
||||
public function patch(string $pattern, mixed $handler): Route
|
||||
{
|
||||
return $this->add(['PATCH'], $pattern, $handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable|array{0: class-string, 1: string} $handler
|
||||
*/
|
||||
public function delete(string $pattern, mixed $handler): Route
|
||||
{
|
||||
return $this->add(['DELETE'], $pattern, $handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Один адрес на несколько методов — например, форма: GET показать, POST принять.
|
||||
*
|
||||
* @param array<int, string> $methods
|
||||
* @param callable|array{0: class-string, 1: string} $handler
|
||||
*/
|
||||
public function match(array $methods, string $pattern, mixed $handler): Route
|
||||
{
|
||||
return $this->add($methods, $pattern, $handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $methods
|
||||
* @param callable|array{0: class-string, 1: string} $handler
|
||||
*/
|
||||
public function add(array $methods, string $pattern, mixed $handler): Route
|
||||
{
|
||||
$route = new Route($methods, $this->group['prefix'] . $pattern, $handler, $this->group['middleware']);
|
||||
|
||||
$this->routes[] = $route;
|
||||
|
||||
return $route;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ищет подходящий маршрут и отдаёт ответ.
|
||||
* Путь не нашёлся — 404, нашёлся, но не с этим методом — 405.
|
||||
*/
|
||||
public function dispatch(Request $request): Response
|
||||
{
|
||||
$pathMatched = false;
|
||||
|
||||
foreach ($this->routes as $route) {
|
||||
$params = $route->match($request->path);
|
||||
|
||||
if ($params === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$pathMatched = true;
|
||||
|
||||
if (!$route->allows($request->method)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return $this->run($route, $request, $params);
|
||||
}
|
||||
|
||||
if ($pathMatched) {
|
||||
return Response::error('Метод ' . $request->method . ' для этого адреса не поддерживается', 405);
|
||||
}
|
||||
|
||||
return Response::error('Адрес не найден: ' . $request->path, 404);
|
||||
}
|
||||
|
||||
/**
|
||||
* Все зарегистрированные маршруты — нужно команде route:list и проверкам.
|
||||
*
|
||||
* @return array<int, Route>
|
||||
*/
|
||||
public function routes(): array
|
||||
{
|
||||
return $this->routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Адрес именованного маршрута.
|
||||
*
|
||||
* @param array<string, mixed> $params
|
||||
*/
|
||||
public static function url(string $name, array $params = []): string
|
||||
{
|
||||
if (!isset(self::$named[$name])) {
|
||||
throw new ProtonException('Неизвестный маршрут: ' . $name);
|
||||
}
|
||||
|
||||
return self::$named[$name]->url($params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Есть ли такой маршрут — вьюхе иногда нужно спросить, не падая.
|
||||
*/
|
||||
public static function has(string $name): bool
|
||||
{
|
||||
return isset(self::$named[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Запоминает именованный маршрут — зовётся из Route::name().
|
||||
*/
|
||||
public static function remember(Route $route): void
|
||||
{
|
||||
if ($route->name !== null) {
|
||||
self::$named[$route->name] = $route;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Прогоняет запрос через прослойки маршрута и вызывает обработчик.
|
||||
*
|
||||
* @param array<string, string> $params
|
||||
*/
|
||||
private function run(Route $route, Request $request, array $params): Response
|
||||
{
|
||||
$next = fn (Request $request): Response => $this->call($route->handler, $request, $params);
|
||||
|
||||
// Идём с конца, чтобы первая прослойка в списке оказалась внешней
|
||||
foreach (array_reverse($route->middleware) as $name) {
|
||||
// Прослойке можно передать аргумент через двоеточие: can:users.manage
|
||||
[$name, $argument] = array_pad(explode(':', $name, 2), 2, '');
|
||||
|
||||
if (!isset($this->middleware[$name])) {
|
||||
throw new ProtonException('Прослойка «' . $name . '» не зарегистрирована');
|
||||
}
|
||||
|
||||
$handler = $this->middleware[$name];
|
||||
$inner = $next;
|
||||
$next = static fn (Request $request): Response => $argument === ''
|
||||
? $handler($request, $inner)
|
||||
: $handler($request, $inner, $argument);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Вызывает обработчик маршрута, подставляя ему аргументы.
|
||||
*
|
||||
* @param callable|array{0: class-string, 1: string} $handler
|
||||
* @param array<string, string> $params
|
||||
*/
|
||||
private function call(mixed $handler, Request $request, array $params): Response
|
||||
{
|
||||
if (is_array($handler) && is_string($handler[0])) {
|
||||
$controller = Container::instance()->make($handler[0]);
|
||||
$method = new ReflectionMethod($controller, $handler[1]);
|
||||
|
||||
/** @var Response $response */
|
||||
$response = $method->invokeArgs($controller, $this->arguments($method, $request, $params));
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
if (!is_callable($handler)) {
|
||||
throw new ProtonException('Обработчик маршрута должен быть функцией или парой [класс, метод]');
|
||||
}
|
||||
|
||||
/** @var Response $response */
|
||||
$response = $handler($request, $params);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Аргументы метода: запрос, параметры адреса и атрибуты запроса.
|
||||
*
|
||||
* @param array<string, string> $params
|
||||
*
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
private function arguments(ReflectionFunctionAbstract $method, Request $request, array $params): array
|
||||
{
|
||||
$arguments = [];
|
||||
|
||||
foreach ($method->getParameters() as $parameter) {
|
||||
$name = $parameter->getName();
|
||||
$type = $parameter->getType();
|
||||
|
||||
if ($type instanceof ReflectionNamedType && $type->getName() === Request::class) {
|
||||
$arguments[] = $request;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (array_key_exists($name, $params)) {
|
||||
$arguments[] = $this->cast($params[$name], $type instanceof ReflectionNamedType ? $type->getName() : 'string');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (array_key_exists($name, $request->attributes)) {
|
||||
$arguments[] = $request->attributes[$name];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($parameter->isDefaultValueAvailable()) {
|
||||
$arguments[] = $parameter->getDefaultValue();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($parameter->allowsNull()) {
|
||||
$arguments[] = null;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new ProtonException('Для обработчика маршрута нечего подставить в параметр «' . $name . '»');
|
||||
}
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
private function cast(string $value, string $type): mixed
|
||||
{
|
||||
return match ($type) {
|
||||
'int' => (int) $value,
|
||||
'float' => (float) $value,
|
||||
'bool' => in_array(strtolower($value), ['1', 'true', 'yes', 'on'], true),
|
||||
default => $value,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user