Files
rsgrinko 12e910249b Этап 3 рефакторинга: HTTP-ядро и закрытие загрузки файлов
Запрос превращается в ответ в одном месте — Kernel::handle(Request): Response.

- Delta\Http\Request: запрос как объект, capture() из суперглобалей,
  типизированные аксессоры вместо обращений к $_GET/$_POST/$_FILES
- Delta\Http\Response: статус, заголовки, тело, единственный send()
- Delta\Http\Kernel: ловит любое исключение из экшена
- Delta\Routing\Router: экземплярный, dispatch(Request): Response.
  Старый Core\Models\Router удалён. Обработчики старого стиля
  продолжают работать: их вывод перехватывается буферизацией, поэтому
  маршруты переводятся на новый стиль по одному
- Delta\Error\ErrorHandler: центральный обработчик ошибок с записью
  в журнал вместо зависимости от display_errors

Безопасность:
- Delta\Http\UploadedFile + File::saveUploadedFile() закрывают
  неограниченную загрузку файлов: расширение выводится из реального
  MIME-типа содержимого, а не из имени файла от клиента, проверяются
  тип и размер. Переведены все три точки загрузки. Прежняя защита
  uploads/.htaccess не работала: сервер nginx, .htaccess не читается
- Файлы журналов пишутся с расширением .php и заглушкой в первой
  строке: каталог логов внутри корня сайта, иначе стектрейсы, IP
  и логины читались бы по URL

Тесты: Request, Response, Router, UploadedFile — всего 47 в проекте.

Перенос docroot в public/ не выполнен: требует правки конфига nginx
на сервере. Инструкция в docs/ARCHITECTURE_PLAN.md.
2026-08-14 00:59:52 +03:00

71 lines
3.5 KiB
PHP
Raw Permalink 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) 2022 Roman Grinko <rsgrinko@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Таблица маршрутизации.
*
* Файл получает готовый объект $router из core/bootstrap.php и возвращает его.
* Обработчики пока заданы строками '\Core\App::method' — это старый стиль, при котором
* экшен печатает в вывод. Маршрутизатор оборачивает такой вывод в объект ответа,
* поэтому маршруты можно переводить на новый стиль (возврат Response) по одному.
*/
use Core\Helpers\Registry;
use Delta\Http\Response;
use Delta\Routing\Router;
/** @var Router $router */
// Прикладной код узнаёт текущий маршрут через Registry — ядро о Registry не знает
$router->onMatch(static function (callable|string $handler): void {
if (is_string($handler)) {
Registry::set('currentPage', $handler);
}
});
$router->route('/404', static fn(): Response => Response::notFound());
$router->route('/', '\Core\App::index');
$router->route('/info', '\Core\App::info');
$router->route('/login', '\Core\App::login');
$router->route('/login/authorize', '\Core\App::loginAuthorize');
$router->route('/login/failed', '\Core\App::loginFailed');
$router->route('/logout', '\Core\App::logout');
$router->route('/dialogs', '\Core\App::dialogs');
$router->route('/dialog/(\d+)', '\Core\App::dialog');
$router->route('/dialog/(\d+)/messages', '\Core\App::dialogMessages');
$router->route('/users', '\Core\App::users');
$router->route('/users/(\d+)', '\Core\App::userProfile');
$router->route('/users/(\d+)/sendMessage', '\Core\App::sendMessage');
$router->route('/users/(\d+)/dialog', '\Core\App::goToDialog');
$router->route('/profile', '\Core\App::profile');
$router->route('/profile/personal', '\Core\App::profileUpdatePersonal');
$router->route('/profile/password', '\Core\App::profileUpdatePassword');
$router->route('/profile/avatar', '\Core\App::profileUpdateAvatar');
$router->route('/profile/resend-verification', '\Core\App::profileResendVerification');
return $router;