-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
executable file
·813 lines (702 loc) · 29.8 KB
/
Copy pathRouter.php
File metadata and controls
executable file
·813 lines (702 loc) · 29.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
<?php
namespace Pet\Router;
use Pet\Request\Request;
/**
* Router — основной маршрутизатор приложения.
*
* Позволяет регистрировать маршруты с поддержкой:
* - HTTP-методов (GET, POST, PUT, DELETE, OPTIONS)
* - Wildcard-маршрутов (/*)
* - Flexible-параметров ({id}, {slug})
* - Middleware (через наследование от Middleware)
* - AJAX-событий
* - Именованных маршрутов и групп
*
* @method static Router get(string $path, callable|string|array ...$callback)
* @method static Router post(string $path, callable|string|array ...$callback)
* @method static Router put(string $path, callable|string|array ...$callback)
* @method static Router delete(string $path, callable|string|array ...$callback)
* @method static Router options(string $path, callable|string|array ...$callback)
*/
class Router extends Middleware
{
/** @var string Директория публичных файлов (переопределяется в конфиге) */
public const PUBLIC_DIR = PUBLIC_DIR;
/** @var array<int, array> Все зарегистрированные маршруты */
private static array $routes = [];
/** @var callable|string|array|null Fallback-обработчик для 404 */
private static mixed $fallback = null;
/** @var int ID последнего добавленного маршрута */
private static int $lastRouteId = 0;
/** @var array<string, callable|string|array> Зарегистрированные AJAX-события */
private static array $events = [];
/** @var array<string> HTTP-методы, для которых разрешён AJAX */
private const AJAX_METHODS = ['POST'];
/** @var string Регулярка для flexible-параметров */
private const FLEXIBLE_PARAM_REGEX = '|{([a-z]{1,})}|';
/** @var string Регулярка для значения flexible-параметра */
private const FLEXIBLE_VALUE_REGEX = '([a-zA-Z0-9?_-]+)';
/**
* ---------------------------------------------------------------------------
* Регистрация маршрутов
* ---------------------------------------------------------------------------
*/
/**
* Регистрирует GET-маршрут.
*
* @param string $path URI-шаблон
* @param callable|string|array ...$callback Обработчик(и)
* @return static
*/
public static function get(string $path, callable|string|array ...$callback): static
{
return self::addRoute('GET', $path, $callback);
}
/**
* Регистрирует POST-маршрут.
*
* @param string $path URI-шаблон
* @param callable|string|array ...$callback Обработчик(и)
* @return static
*/
public static function post(string $path, callable|string|array ...$callback): static
{
return self::addRoute('POST', $path, $callback);
}
/**
* Регистрирует PUT-маршрут.
*
* @param string $path URI-шаблон
* @param callable|string|array ...$callback Обработчик(и)
* @return static
*/
public static function put(string $path, callable|string|array ...$callback): static
{
return self::addRoute('PUT', $path, $callback);
}
/**
* Регистрирует DELETE-маршрут.
*
* @param string $path URI-шаблон
* @param callable|string|array ...$callback Обработчик(и)
* @return static
*/
public static function delete(string $path, callable|string|array ...$callback): static
{
return self::addRoute('DELETE', $path, $callback);
}
/**
* Регистрирует OPTIONS-маршрут.
*
* @param string $path URI-шаблон
* @param callable|string|array ...$callback Обработчик(и)
* @return static
*/
public static function options(string $path, callable|string|array ...$callback): static
{
return self::addRoute('OPTIONS', $path, $callback);
}
/**
* Регистрирует HEAD-маршрут.
*
* @param string $path URI-шаблон
* @param callable|string|array ...$callback Обработчик(и)
* @return static
*/
public static function head(string $path, callable|string|array ...$callback): static
{
return self::addRoute('HEAD', $path, $callback);
}
/**
* Добавляет маршрут во внутренний реестр.
*
* @param string $method HTTP-метод
* @param string $path URI-шаблон
* @param array $callback Массив обработчиков
* @return static
*/
private static function addRoute(string $method, string $path, array $callback): static
{
$method = strtoupper($method);
// Проверка на конфликт с существующими маршрутами
self::detectConflict($method, $path);
self::$routes[] = [
'path' => $path,
'method' => $method,
'callback' => $callback,
];
self::$lastRouteId = array_key_last(self::$routes);
return new static();
}
/**
* Проверяет, не конфликтует ли новый маршрут с уже зарегистрированными.
*
* Конфликт возникает, когда два маршрута с одним HTTP-методом
* могут совпасть с одним и тем же URL. Это приводит к неопределённости:
* какой из них должен обработать запрос?
*
* Типы конфликтов:
* 1. Точный vs точный — /user/list и /user/list (дубликат)
* 2. Точный vs flexible — /user/42 и /user/{id} (точный никогда не сработает,
* если flexible зарегистрирован раньше)
* 3. Flexible vs flexible — /user/{id} и /user/{slug} (оба подходят под /user/abc)
* 4. Wildcard vs flexible — /user/* и /user/{id} (wildcard перехватывает)
* 5. Wildcard vs wildcard — /user/* и /user/* (дубликат)
*
* @param string $method HTTP-метод
* @param string $path Шаблон нового маршрута
* @return void
* @throws \RuntimeException Если обнаружен конфликт
*/
private static function detectConflict(string $method, string $path): void
{
$isNewWildcard = self::isWildcardRoute($path);
$newHasFlexible = !$isNewWildcard && preg_match(self::FLEXIBLE_PARAM_REGEX, $path);
foreach (self::$routes as $index => $existing) {
if ($existing['method'] !== $method) {
continue;
}
$existingPath = $existing['path'];
$isExistingWildcard = self::isWildcardRoute($existingPath);
$existingHasFlexible = !$isExistingWildcard && preg_match(self::FLEXIBLE_PARAM_REGEX, $existingPath);
// Случай 1: точный vs точный (дубликат)
if (!$isNewWildcard && !$newHasFlexible && !$isExistingWildcard && !$existingHasFlexible) {
if ($path === $existingPath) {
throw new \RuntimeException(
"Route conflict: exact duplicate [{$method}] {$path} (route #{$index})"
);
}
continue;
}
// Случай 5: wildcard vs wildcard (дубликат)
if ($isNewWildcard && $isExistingWildcard) {
if ($path === $existingPath) {
throw new \RuntimeException(
"Route conflict: duplicate wildcard [{$method}] {$path} (route #{$index})"
);
}
continue;
}
// Для остальных случаев конвертируем оба шаблона в regex
$newRegex = self::patternToRegex($path, $isNewWildcard, $newHasFlexible);
$existingRegex = self::patternToRegex($existingPath, $isExistingWildcard, $existingHasFlexible);
// Случай 2: точный vs flexible
// Точный путь совпадает с regex flexible — flexible перехватит
if (!$isNewWildcard && !$newHasFlexible && $existingHasFlexible) {
if (preg_match($existingRegex, $path)) {
throw new \RuntimeException(
"Route conflict: exact route [{$method}] {$path} will never match — " .
"it is intercepted by flexible route [{$method}] {$existingPath} (route #{$index})"
);
}
continue;
}
// Случай 2 (обратный): flexible vs точный
if ($newHasFlexible && !$isExistingWildcard && !$existingHasFlexible) {
if (preg_match($newRegex, $existingPath)) {
throw new \RuntimeException(
"Route conflict: flexible route [{$method}] {$path} intercepts " .
"exact route [{$method}] {$existingPath} (route #{$index})"
);
}
continue;
}
// Случай 3: flexible vs flexible
if ($newHasFlexible && $existingHasFlexible) {
// Проверяем, могут ли оба regex совпасть с одним URL
// Для этого проверяем, совпадает ли структура сегментов
$newSegments = explode('/', trim($path, '/'));
$existingSegments = explode('/', trim($existingPath, '/'));
if (count($newSegments) !== count($existingSegments)) {
continue; // разное количество сегментов — не конфликтуют
}
// Сравниваем посегментно: если оба не-flexible сегмента различаются — не конфликт
$conflict = true;
foreach ($newSegments as $i => $newSeg) {
$isNewFlex = preg_match(self::FLEXIBLE_PARAM_REGEX, $newSeg);
$isExistFlex = preg_match(self::FLEXIBLE_PARAM_REGEX, $existingSegments[$i]);
if (!$isNewFlex && !$isExistFlex && $newSeg !== $existingSegments[$i]) {
$conflict = false;
break;
}
}
if ($conflict) {
throw new \RuntimeException(
"Route conflict: flexible routes [{$method}] {$path} and " .
"[{$method}] {$existingPath} (route #{$index}) can match the same URL"
);
}
continue;
}
// Случай 4: wildcard vs flexible
if ($isNewWildcard && $existingHasFlexible) {
$wcPrefix = rtrim(substr($path, 0, -1), '/'); // /user/* -> /user
if (preg_match($existingRegex, $wcPrefix . '/test')) {
throw new \RuntimeException(
"Route conflict: wildcard [{$method}] {$path} intercepts " .
"flexible route [{$method}] {$existingPath} (route #{$index})"
);
}
continue;
}
// Случай 4 (обратный): flexible vs wildcard
if ($newHasFlexible && $isExistingWildcard) {
$wcPrefix = rtrim(substr($existingPath, 0, -1), '/');
if (preg_match($newRegex, $wcPrefix . '/test')) {
throw new \RuntimeException(
"Route conflict: flexible route [{$method}] {$path} is intercepted " .
"by wildcard [{$method}] {$existingPath} (route #{$index})"
);
}
continue;
}
// Точный vs wildcard: точный /user/list и wildcard /user/*
if (!$isNewWildcard && !$newHasFlexible && $isExistingWildcard) {
$wcPrefix = rtrim(substr($existingPath, 0, -1), '/');
if (str_starts_with($path, $wcPrefix === '' ? '/' : $wcPrefix . '/')) {
throw new \RuntimeException(
"Route conflict: exact route [{$method}] {$path} will never match — " .
"it is intercepted by wildcard [{$method}] {$existingPath} (route #{$index})"
);
}
continue;
}
// Точный vs wildcard (обратный): wildcard регистрируется после точного
if ($isNewWildcard && !$isExistingWildcard && !$existingHasFlexible) {
$wcPrefix = rtrim(substr($path, 0, -1), '/');
if (str_starts_with($existingPath, $wcPrefix === '' ? '/' : $wcPrefix . '/')) {
throw new \RuntimeException(
"Route conflict: wildcard [{$method}] {$path} intercepts " .
"exact route [{$method}] {$existingPath} (route #{$index})"
);
}
continue;
}
}
}
/**
* Конвертирует шаблон маршрута в регулярное выражение для проверки конфликтов.
*
* @param string $path Шаблон маршрута
* @param bool $isWildcard Является ли wildcard-маршрутом
* @param bool $hasFlexible Содержит ли flexible-параметры
* @return string
*/
private static function patternToRegex(string $path, bool $isWildcard, bool $hasFlexible): string
{
if ($isWildcard) {
$prefix = rtrim(substr($path, 0, -1), '/');
return '#^' . preg_quote($prefix, '#') . '(/.+)?$#';
}
if ($hasFlexible) {
$regex = preg_replace(self::FLEXIBLE_PARAM_REGEX, self::FLEXIBLE_VALUE_REGEX, $path);
return '#^' . $regex . '$#';
}
return '#^' . preg_quote($path, '#') . '$#';
}
/**
* ---------------------------------------------------------------------------
* Модификаторы маршрутов (fluent)
* ---------------------------------------------------------------------------
*/
/**
* Задаёт имя маршруту.
*
* @param string $name
* @return $this
*/
public function name(string $name): static
{
self::$routes[self::$lastRouteId]['name'] = $name;
return $this;
}
/**
* Задаёт группу маршруту.
*
* @param string $group
* @return $this
*/
public function group(string $group): static
{
self::$routes[self::$lastRouteId]['group'] = $group;
return $this;
}
/**
* Регистрирует fallback-обработчик для ненайденных маршрутов (404).
*
* @param callable|string|array $callback Обработчик
* @return void
*/
public static function fallback(callable|string|array $callback): void
{
self::$fallback = $callback;
}
/**
* ---------------------------------------------------------------------------
* События (AJAX)
* ---------------------------------------------------------------------------
*/
/**
* Регистрирует AJAX-событие.
*
* @param string $key Ключ события (заголовок запроса)
* @param callable|string|array $action Обработчик
* @return void
*/
public static function event(string $key, callable|string|array $action): void
{
self::$events[$key] = $action;
}
/**
* ---------------------------------------------------------------------------
* Запуск маршрутизации
* ---------------------------------------------------------------------------
*/
/**
* Запускает обработку входящего запроса.
*
* Последовательно перебирает зарегистрированные маршруты,
* применяет middleware, вызывает обработчики и отправляет ответ.
*
* @return never
*/
public static function init(): never
{
ob_start();
$request = request();
$routeMatched = false;
foreach (self::getOrderedRoutes() as $route) {
// AJAX-события обрабатываются до проверки метода
if (self::isAjaxMethod($request) && self::handleAjaxEvent($request)) {
// handleAjaxEvent уже завершил выполнение через Response::die()
}
// Фильтрация по HTTP-методу
if ($route['method'] !== $request->getMethod()) {
continue;
}
// Если маршрут уже найден — пропускаем остальные
if ($routeMatched) {
continue;
}
// Проверка совпадения пути (wildcard, flexible, точное)
if (!self::matchRoute($request, $route)) {
continue;
}
// Выполнение middleware
if (isset($route['middleware'])) {
$middlewareResult = self::executeMiddleware($route, $request);
if ($middlewareResult === false) {
break;
}
}
// Выполнение обработчиков маршрута
$results = self::executeCallbacks($route['callback'], $request);
// Отправка ответа
self::sendResponse($results);
$routeMatched = true;
}
// 404 — маршрут не найден
if (!$routeMatched) {
Header::status(HTTP::NOT_FOUND);
if (self::$fallback !== null) {
$results = ( new Invoker())->call(self::$fallback, $request);
if (!empty($results)) {
self::sendResponse($results);
}
}
}
ob_end_flush();
exit;
}
/**
* ---------------------------------------------------------------------------
* Middleware
* ---------------------------------------------------------------------------
*/
/**
* Выполняет middleware для маршрута.
*
* @param array $route Данные маршрута
* @param Request $request Объект запроса
* @return bool|null false — прервать цепочку, null/true — продолжать
*/
private static function executeMiddleware(array $route, Request $request): bool|null
{
if (isset($route['isManyMiddle']) && $route['isManyMiddle'] === true) {
// Множественные middleware
foreach ($route['middleware'] as $middleware) {
$result = (new Invoker())->call($middleware, $request);
if ($result === false) {
return false;
}
}
return null;
}
// Одиночный middleware
return (new Invoker())->call($route['middleware'], $request);
}
/**
* ---------------------------------------------------------------------------
* Обработка AJAX
* ---------------------------------------------------------------------------
*/
/**
* Проверяет, является ли метод запроса AJAX-совместимым.
*
* @param Request $request
* @return bool
*/
private static function isAjaxMethod(Request $request): bool
{
return in_array($request->getMethod(), self::AJAX_METHODS, true);
}
/**
* Обрабатывает AJAX-событие, если найден соответствующий заголовок.
*
* @param Request $request
* @return bool true — событие обработано и выполнение завершено
*/
private static function handleAjaxEvent(Request $request): bool
{
foreach (self::$events as $key => $action) {
$headerValue = $request->getHeader($key);
if ($headerValue !== null && $headerValue !== '') {
self::hydrateRouteParameters($request);
$result = (new Invoker())->call($action, $request);
Response::json($result);
}
}
return false;
}
/**
* ---------------------------------------------------------------------------
* Сопоставление маршрута
* ---------------------------------------------------------------------------
*/
/**
* Проверяет, совпадает ли путь запроса с маршрутом.
*
* @param Request $request
* @param array $route
* @return bool
*/
private static function matchRoute(Request $request, array $route): bool
{
$path = $request->getPath();
// Точное совпадение
if ($path === $route['path']) {
return true;
}
// Wildcard-маршрут
if (self::isWildcardRoute($route['path'])) {
return self::matchWildcard($route['path'], $request);
}
// Flexible-маршрут с параметрами {id}, {slug}
// Сначала проверяем, содержит ли шаблон flexible-параметры
if (!preg_match_all(self::FLEXIBLE_PARAM_REGEX, $route['path'], $matches)) {
return false;
}
return self::matchFlexible($route['path'], $request);
}
/**
* ---------------------------------------------------------------------------
* Wildcard-маршруты (/*)
* ---------------------------------------------------------------------------
*/
/**
* Проверяет, является ли путь wildcard-маршрутом.
*
* @param string $path
* @return bool
*/
private static function isWildcardRoute(string $path): bool
{
return str_ends_with($path, '/*');
}
/**
* Сопоставляет wildcard-маршрут с путём запроса.
*
* @param string $pattern Шаблон (например, /blog/*)
* @param Request $request
* @return bool
*/
private static function matchWildcard(string $pattern, Request $request): bool
{
$prefix = substr($pattern, 0, -1); // /blog/
$path = $request->getPath();
$base = rtrim($prefix, '/'); // /blog
// Точное совпадение с базой: /blog == /blog
if ($path === $base) {
Request::setParameter('*', '');
return true;
}
// Совпадение с префиксом: /blog/post-1 начинается с /blog/
if (str_starts_with($path, $prefix)) {
Request::setParameter('*', substr($path, strlen($prefix)));
return true;
}
return false;
}
/**
* ---------------------------------------------------------------------------
* Flexible-маршруты ({param})
* ---------------------------------------------------------------------------
*/
/**
* Сопоставляет flexible-маршрут с путём запроса.
*
* @param string $pattern Шаблон (например, /post/{id})
* @param Request $request
* @return bool
*/
private static function matchFlexible(string $pattern, Request $request): bool
{
if (!preg_match_all(self::FLEXIBLE_PARAM_REGEX, $pattern, $matches)) {
return false;
}
$paramNames = $matches[1]; // ['id'], ['slug'], etc.
$regex = $pattern;
// Заменяем {param} на регулярку
foreach ($matches[0] as $placeholder) {
$regex = str_replace($placeholder, self::FLEXIBLE_VALUE_REGEX, $regex);
}
$path = $request->getPath();
if (preg_match("#^{$regex}$#", $path, $result)) {
foreach ($paramNames as $index => $name) {
Request::setParameter($name, $result[$index + 1]);
}
return true;
}
return false;
}
/**
* Заполняет Request::$parametr для AJAX/event-запросов до вызова обработчика.
*
* AJAX события (`Router::event`) выполняются до обычного route matching,
* поэтому flexible-параметры вроде `/service/edit/{id}` иначе недоступны
* через `supple('id')`.
*/
private static function hydrateRouteParameters(Request $request): void
{
foreach (self::getOrderedRoutes() as $route) {
if (self::matchRoute($request, $route)) {
return;
}
}
}
/**
* ---------------------------------------------------------------------------
* Выполнение callback
* ---------------------------------------------------------------------------
*/
/**
* Выполняет все callback маршрута и возвращает массив результатов.
*
* @param array $callbacks Массив обработчиков
* @param Request $request
* @return array
*/
private static function executeCallbacks(array $callbacks, Request $request): array
{
$results = [];
foreach ($callbacks as $callback) {
$result = (new Invoker())->call($callback, $request);
$results[] = $result;
}
// Фильтрация пустых результатов (null, false, '')
return array_values(
array_filter($results, static fn($item): bool => is_array($item) || !in_array($item, [null, false, ''], true))
);
}
/**
* ---------------------------------------------------------------------------
* Отправка ответа
* ---------------------------------------------------------------------------
*/
/**
* Отправляет JSON-ответ с результатами выполнения маршрута.
*
* @param array $results
* @return void
*/
private static function sendResponse(array $results): void
{
if ($results === []) {
return;
}
if (!Header::sent()) {
Header::json();
}
$data = count($results) === 1 ? $results[0] : $results;
echo json_encode($data, JSON_UNESCAPED_UNICODE);
}
/**
* ---------------------------------------------------------------------------
* Порядок маршрутов
* ---------------------------------------------------------------------------
*/
/**
* Возвращает маршруты в порядке приоритета:
* сначала точные, потом wildcard.
*
* @return array
*/
private static function getOrderedRoutes(): array
{
$explicit = [];
$wildcard = [];
foreach (self::$routes as $route) {
if (self::isWildcardRoute($route['path'])) {
$wildcard[] = $route;
} else {
$explicit[] = $route;
}
}
return array_merge($explicit, $wildcard);
}
/**
* ---------------------------------------------------------------------------
* Доступ к маршрутам (для Middleware)
* ---------------------------------------------------------------------------
*/
/**
* Возвращает все зарегистрированные маршруты.
* Используется в Middleware::set() для привязки middleware.
*
* @internal
* @return array
*/
public static function getRoutes(): array
{
return self::$routes;
}
/**
* Возвращает количество зарегистрированных маршрутов.
*
* @internal
* @return int
*/
public static function getRouteCount(): int
{
return count(self::$routes);
}
/**
* Устанавливает middleware для маршрута по индексу.
*
* @internal
* @param int $index Индекс маршрута
* @param mixed $callback Middleware callback
* @param bool $isMany Флаг множественных middleware
* @return void
*/
public static function setRouteMiddleware(int $index, mixed $callback, bool $isMany): void
{
if (!isset(self::$routes[$index])) {
return;
}
self::$routes[$index]['middleware'] = $callback;
if ($isMany) {
self::$routes[$index]['isManyMiddle'] = true;
}
}
}