Skip to content

Commit d139569

Browse files
2.1.0
- PHP 8 version - Добавлен Helper-класс с методами: `dumpRoutingRulesWeb()` и `dumpRoutingRulesCLI()`, генерирующий таблицы роутов для веба и CLI - мелкие фиксы
1 parent 706b34d commit d139569

File tree

4 files changed

+301
-100
lines changed

4 files changed

+301
-100
lines changed

src/AppRouter.php

Lines changed: 27 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Arris\AppRouter\FastRoute\ConfigureRoutes;
66
use Arris\AppRouter\FastRoute\Dispatcher;
7+
use Arris\AppRouter\Helper;
78
use Arris\AppRouter\Stack;
89
use Arris\Exceptions\AppRouterHandlerError;
910
use Arris\Exceptions\AppRouterMethodNotAllowedException;
@@ -90,13 +91,6 @@ class AppRouter implements AppRouterInterface
9091
*/
9192
private static string $current_prefix = '';
9293

93-
/**
94-
* Default replace pattern
95-
*
96-
* @var string
97-
*/
98-
// private static string $routeReplacePattern = '%%$1%%';
99-
10094
/**
10195
* Current Routing Info
10296
*
@@ -151,6 +145,13 @@ class AppRouter implements AppRouterInterface
151145
*/
152146
private static array $routeRule = [];
153147

148+
/**
149+
* STUB для внутренних опций
150+
*
151+
* @var array
152+
*/
153+
private static array $options = [];
154+
154155
/**
155156
* Разрешать ли пустые группы (без роутов, но с опциями или миддлварами)
156157
*
@@ -193,8 +194,10 @@ class AppRouter implements AppRouterInterface
193194
*/
194195
private static bool $option_use_aliases = false;
195196

196-
/* ============================================================================================================================================*/
197197

198+
/**
199+
* @inheritDoc
200+
*/
198201
public function __construct(
199202
LoggerInterface $logger = null,
200203
string $namespace = '',
@@ -205,6 +208,9 @@ public function __construct(
205208
self::init($logger, namespace: $namespace, prefix: $prefix, allowEmptyGroups: $allowEmptyGroups, allowEmptyHandlers: $allowEmptyHandlers);
206209
}
207210

211+
/**
212+
* @inheritDoc
213+
*/
208214
public static function init(
209215
LoggerInterface $logger = null,
210216
string $namespace = '',
@@ -280,12 +286,7 @@ public static function setDefaultNamespace(string $namespace = ''):void
280286
self::$current_namespace = $namespace;
281287
}
282288

283-
/**
284-
* Указывает нэймспейс для миддлваров-посредников
285-
*
286-
* @param string $namespace
287-
* @return void
288-
*/
289+
289290
public static function setMiddlewaresNamespace(string $namespace = ''):void
290291
{
291292
// return true;
@@ -344,6 +345,7 @@ public static function post($route, $handler, $name = null)
344345
];
345346
}
346347

348+
347349
public static function put($route, $handler, $name = null)
348350
{
349351
if (is_null($route) || is_null($handler)) {
@@ -637,7 +639,6 @@ public static function dispatch()
637639
}
638640

639641
$r->addRoute($rule['httpMethod'], $route, $handler, $rule);
640-
// $r->addRoute($rule['httpMethod'], $rule['route'], $handler, $rule);
641642
}
642643
});
643644

@@ -746,7 +747,7 @@ public static function dispatch()
746747
/**
747748
* @inheritDoc
748749
*
749-
* @return array|Dispatcher\Result\ResultInterface
750+
* @return Dispatcher\Result\ResultInterface
750751
*/
751752
public static function getRoutingInfo()
752753
{
@@ -794,7 +795,7 @@ private static function getInternalRuleKey(string $httpMethod, $handler, string
794795
}
795796

796797
if ($handler instanceof \Closure) {
797-
$internal_name = self::getClosureInternalName($handler);
798+
$internal_name = Helper::getClosureInternalName($handler);
798799
} elseif (is_array($handler)) {
799800

800801
// Хэндлер может быть массивом, но пустым. Вообще, это ошибка, поэтому генерим имя на основе md5 роута и метода.
@@ -822,7 +823,7 @@ private static function getInternalRuleKey(string $httpMethod, $handler, string
822823
* @param bool $is_static
823824
* @return void
824825
*/
825-
public static function checkClassExists($class, bool $is_static = false): void
826+
private static function checkClassExists($class, bool $is_static = false): void
826827
{
827828
// быстрее, чем рефлексия
828829
if (!class_exists($class)){
@@ -845,7 +846,7 @@ public static function checkClassExists($class, bool $is_static = false): void
845846
* @param bool $is_static
846847
* @return void
847848
*/
848-
public static function checkMethodExists($class, $method, bool $is_static = false): void
849+
private static function checkMethodExists($class, $method, bool $is_static = false): void
849850
{
850851
$prompt = $is_static ? 'static class' : 'class';
851852

@@ -878,7 +879,7 @@ public static function checkMethodExists($class, $method, bool $is_static = fals
878879
* @return bool
879880
* @throws AppRouterHandlerError
880881
*/
881-
public static function checkFunctionExists($handler): bool
882+
private static function checkFunctionExists($handler): bool
882883
{
883884
if (!function_exists($handler)){
884885
self::$logger->error("Handler function '{$handler}' not found", [ self::$uri, self::$httpMethod, $handler ]);
@@ -892,52 +893,6 @@ public static function checkFunctionExists($handler): bool
892893
return true;
893894
}
894895

895-
/**
896-
* Возвращает "внутреннее" имя замыкание, сгенерированное на основе таймштампа (до мс) и аргументов функции
897-
* Closure(LineStart-LineEnd)=аргумент1:аргумент2:аргумент3
898-
*
899-
* Или, если возникло исключение ReflectionException
900-
* Closure(<md5(1, 4096)>)=.
901-
*
902-
* @param $closure
903-
* @return string
904-
*/
905-
public static function getClosureInternalName($closure): string
906-
{
907-
$name = "Closure(";
908-
909-
try {
910-
$reflected = new \ReflectionFunction($closure);
911-
$args = implode(':',
912-
// создаем статичную функцию и сразу вызываем
913-
(static function ($r) {
914-
return
915-
array_map(
916-
// обработчик
917-
static function($v)
918-
{
919-
return is_object($v) ? $v->name : $v;
920-
},
921-
// входной массив
922-
array_merge(
923-
$r->getParameters(),
924-
array_keys(
925-
$r->getStaticVariables()
926-
)
927-
)
928-
);
929-
})
930-
($reflected) // а это её аргумент
931-
); // эта скобочка относится к implode
932-
// "value:value2:s1:s2"
933-
$name .= $reflected->getStartLine() . "-" . $reflected->getEndLine() . ")=" . $args;
934-
} catch (\ReflectionException $e) {
935-
$name .= md5(mt_rand(1, PHP_MAXPATHLEN)) . ")=.";
936-
}
937-
938-
return $name;
939-
}
940-
941896
/**
942897
* Компилирует хэндлер из строчки, замыкания или массива [класс, метод] в действующий хэндлер
943898
* с отловом ошибок несуществования роута
@@ -946,7 +901,7 @@ static function($v)
946901
* @param bool $is_middleware
947902
* @return array|\Closure|string
948903
*/
949-
public static function compileHandler($handler, bool $is_middleware = false)
904+
private static function compileHandler($handler, bool $is_middleware = false): array|\Closure|string
950905
{
951906
if (empty($handler)) {
952907
return [];
@@ -987,7 +942,7 @@ public static function compileHandler($handler, bool $is_middleware = false)
987942
if (is_string($handler) && str_contains($handler, '@')) {
988943
// 'Class@method'
989944

990-
list($class, $method) = self::explode($handler, [null, '__invoke'], '@');
945+
list($class, $method) = Helper::explode($handler, [null, '__invoke'], '@');
991946
self::checkClassExists($class);
992947
self::checkMethodExists($class, $method);
993948

@@ -1037,31 +992,13 @@ public static function compileHandler($handler, bool $is_middleware = false)
1037992
return $handler;
1038993
}
1039994

1040-
1041-
/**
1042-
* Выполняет explode строки роута с учетом дефолтной маски
1043-
* Заменяет list($a, $b) = explode(separator, string) с дефолтными значениями элементов
1044-
* Хотел назвать это replace_array_callback(), но передумал
1045-
*
1046-
* @param $income
1047-
* @param array $default
1048-
* @param string $separator
1049-
* @return array
1050-
*/
1051-
private static function explode($income, array $default = [ null, '__invoke' ], string $separator = '@'): array
1052-
{
1053-
return array_map(static function($first, $second) {
1054-
return empty($second) ? $first : $second;
1055-
}, $default, \explode($separator, $income));
1056-
}
1057-
1058995
/**
1059996
* Experimental - use only if str_contains('{')
1060997
*
1061998
* @param $route
1062999
* @return array|string|string[]|null
10631000
*/
1064-
private static function applyAliases($route)
1001+
private static function applyAliases($route): array|string|null
10651002
{
10661003
return preg_replace_callback('/\{(\w+)\}/', function($matches) {
10671004
$paramName = $matches[1];
@@ -1073,11 +1010,7 @@ private static function applyAliases($route)
10731010
}
10741011

10751012
/**
1076-
* Experimental - addAlias
1077-
*
1078-
* @param array|string $name
1079-
* @param string|null $regexp
1080-
* @return void
1013+
* @inheritDoc
10811014
*/
10821015
public static function addAlias(array|string $name, ?string $regexp = null): void
10831016
{
@@ -1091,9 +1024,7 @@ public static function addAlias(array|string $name, ?string $regexp = null): voi
10911024
}
10921025

10931026
/**
1094-
* Experimental: возвращает список алиасов
1095-
*
1096-
* @return array
1027+
* @inheritDoc
10971028
*/
10981029
public static function getAliases():array
10991030
{
@@ -1102,4 +1033,4 @@ public static function getAliases():array
11021033

11031034
}
11041035

1105-
# -eof-
1036+
# -eof- #
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?php
2+
3+
namespace Arris\AppRouter;
4+
5+
interface AppRouterHelperInterface
6+
{
7+
/**
8+
* Превращает дамп внутренней таблицы роутов в WEB-таблицу.
9+
*
10+
* echo getRoutingTable(AppRouter::getRoutingRules());
11+
*
12+
* @param array $routingRules
13+
* @param bool $withMiddlewares
14+
* @return string
15+
*/
16+
public static function dumpRoutingRulesWeb(array $routingRules, bool $withMiddlewares = true): string;
17+
18+
/**
19+
* Превращает дамп внутренней таблицы роутов в CLI-таблицу
20+
*
21+
* echo dumpRoutingRulesCLI(AppRouter::getRoutingRules());
22+
*
23+
* @param array $routingRules
24+
* @param bool $withMiddlewares
25+
* @return string
26+
*/
27+
public static function dumpRoutingRulesCLI(array $routingRules, bool $withMiddlewares = false):string;
28+
29+
/**
30+
* Выполняет explode строки роута с учетом дефолтной маски
31+
* Заменяет list($a, $b) = explode(separator, string) с дефолтными значениями элементов
32+
* Хотел назвать это replace_array_callback(), но передумал
33+
*
34+
* @param $income
35+
* @param array $default
36+
* @param string $separator
37+
* @return array
38+
*/
39+
public static function explode($income, array $default = [ null, '__invoke' ], string $separator = '@'): array;
40+
41+
/**
42+
* Возвращает "внутреннее" имя замыкание, сгенерированное на основе таймштампа (до мс) и аргументов функции
43+
* Closure(LineStart-LineEnd)=аргумент1:аргумент2:аргумент3
44+
*
45+
* Или, если возникло исключение ReflectionException
46+
* Closure(<md5(1, 4096)>)=.
47+
*
48+
* @param $closure
49+
* @return string
50+
*/
51+
public static function getClosureInternalName($closure): string;
52+
53+
}

0 commit comments

Comments
 (0)