Bicycle/System/Classes/Route.php
Egor Isaev b516ca07dc Initial commit: Bicycle PHP MVC micro-framework
Core MVC, HTTP client, Session, Cookie, Config, HTTPException — 111 PHPUnit tests.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-04 10:04:19 +03:00

113 lines
3.5 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
/**
* @package Bicycle
* @author Egor Isaev
* @description Route.php
* @copyright (c) 03/06/2026
*/
namespace System\Classes;
class Route
{
/**
* Разбирает URI и возвращает массив с ключами controller, action, params.
*
* Поддерживаемые форматы URL:
* / → Index::index
* /controller → Controller::index
* /controller/action → Controller::action
* /controller/action/p1/p2 → Controller::action + params
* /subdir/controller/action → Subdir/Controller::action (если subdir — папка в App/Controller)
*/
public static function resolve(string $uri): array
{
if ($uri === '') {
return self::make('Index', 'index', []);
}
$parts = explode('/', $uri);
$controller = self::findController($parts[0], '');
if ($controller !== null || !isset($parts[1])) {
return self::make(
$controller ?? ucfirst($parts[0]),
$parts[1] ?? 'index',
array_slice($parts, 2)
);
}
$subdirController = self::findController($parts[1], $parts[0]);
if ($subdirController !== null) {
return self::make(
$subdirController,
$parts[2] ?? 'index',
array_slice($parts, 3)
);
}
// Ни плоский контроллер, ни subdir не найдены — возвращаем flat-роутинг
return self::make(
ucfirst($parts[0]),
$parts[1] ?? 'index',
array_slice($parts, 2)
);
}
/**
* Ищет файл {name}Controller.php в App/Classes[/subdir] без учёта регистра.
* Возвращает имя контроллера (или subdir/имя) без суффикса Controller, либо null.
*/
private static function findController(string $name, string $subdir): ?string
{
$base = DOCROOT . '/App/Controller/';
$dir = $base;
if ($subdir !== '') {
foreach (is_dir($base) ? scandir($base) : [] as $entry) {
if ($entry !== '.' && $entry !== '..'
&& is_dir($base . $entry)
&& strtolower($entry) === strtolower($subdir)
) {
$dir = $base . $entry . '/';
$subdir = $entry;
break;
}
}
if ($dir === $base) {
return null;
}
}
if (!is_dir($dir)) {
return null;
}
$needle = strtolower($name . 'Controller');
foreach (scandir($dir) as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) !== 'php') {
continue;
}
$basename = pathinfo($file, PATHINFO_FILENAME);
if (strtolower($basename) === $needle) {
$clean = substr($basename, 0, -10); // убираем 'Controller'
return $subdir !== '' ? $subdir . '/' . $clean : $clean;
}
}
return null;
}
private static function make(string $controller, string $action, array $params): array
{
return [
'controller' => $controller,
'action' => $action,
'params' => $params,
];
}
}