3 Commits
1.2.1 ... 2.0

Author SHA1 Message Date
User
3b1d74f0a3 20250302#4 2025-03-02 21:27:56 +03:00
User
31833a8dde 20250302#2 2025-03-02 21:19:08 +03:00
User
297217ee1d 20250302#1 2025-03-02 19:13:32 +03:00
3 changed files with 51 additions and 14 deletions

View File

@@ -10,12 +10,12 @@ Stable version
composer require rmphp/router composer require rmphp/router
``` ```
```bash ```bash
composer require rmphp/router:"^1.0" composer require rmphp/router:"^2.0"
``` ```
Dev version contains the latest changes Dev version contains the latest changes
```bash ```bash
composer require rmphp/router:"1.x-dev" composer require rmphp/router:"2.x-dev"
``` ```

View File

@@ -9,12 +9,12 @@
], ],
"require": { "require": {
"php": "^8.1", "php": "^8.1",
"rmphp/foundation": "^2.0" "rmphp/foundation": "^3.0"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"Rmphp\\Router\\": "src/" "Rmphp\\Router\\": "src/"
} }
} }
} }

View File

@@ -11,25 +11,21 @@ class Router implements RouterInterface {
private array $rules = []; private array $rules = [];
private string $startPoint = "/"; private string $startPoint = "/";
/** /** @inheritDoc */
* @param string $mountPoint
*/
public function setStartPoint(string $mountPoint): void { public function setStartPoint(string $mountPoint): void {
$this->startPoint = $mountPoint; $this->startPoint = $mountPoint;
} }
/** /** @inheritDoc */
* @param array $rules
*/
public function withRules(array $rules): void public function withRules(array $rules): void
{ {
$this->rules = []; $this->rules = [];
foreach ($rules as $rulesKey => $rulesNode) { foreach ($rules as $rulesKey => $rulesNode) {
// проверка формата
if (!isset($rulesNode['key'], $rulesNode['routes'])) continue; if (!isset($rulesNode['key'], $rulesNode['routes'])) continue;
// преобразуем псевдомаску в реальную маску // преобразуем псевдомаску в реальную маску
// заменяем алиасы на регвыражения // заменяем алиасы на регвыражения
$realPattern = preg_replace("'<([A-z0-9_]+?):@any>'", "(?P<$1>.*)", $rulesNode['key']); $realPattern = $rulesNode['key'];
$realPattern = preg_replace("'<([A-z0-9_]+?):@any>'", "(?P<$1>.*)", $realPattern);
$realPattern = preg_replace("'<([A-z0-9_]+?):@num>'", "(?P<$1>[0-9]+)", $realPattern); $realPattern = preg_replace("'<([A-z0-9_]+?):@num>'", "(?P<$1>[0-9]+)", $realPattern);
$realPattern = preg_replace("'<([A-z0-9_]+?):@path>'", "(?P<$1>[^/]+)", $realPattern); $realPattern = preg_replace("'<([A-z0-9_]+?):@path>'", "(?P<$1>[^/]+)", $realPattern);
// поддерживаем свободное регулярное выражение в псевдомаске // поддерживаем свободное регулярное выражение в псевдомаске
@@ -37,13 +33,27 @@ class Router implements RouterInterface {
// заменяем алиасы на регвыражения // заменяем алиасы на регвыражения
$realPattern = str_replace(["<@any>", "<@num>", "<@path>"], [".*", "[0-9]+", "[^/]+"], $realPattern); $realPattern = str_replace(["<@any>", "<@num>", "<@path>"], [".*", "[0-9]+", "[^/]+"], $realPattern);
// при наличии слеша в конце правила url должно строго ему соответствовать // при наличии слеша в конце правила url должно строго ему соответствовать
$end = (preg_match("'/$'", $realPattern)) ? "$" : ""; $end = (str_ends_with($realPattern, "/")) ? "$" : "";
// меняем запись на паттерн // меняем запись на паттерн
$this->rules[$rulesKey] = $rulesNode; $this->rules[$rulesKey] = $rulesNode;
$this->rules[$rulesKey]['key'] = "'^".$realPattern.$end."'"; $this->rules[$rulesKey]['key'] = "'^".$realPattern.$end."'";
} }
} }
/** @inheritDoc */
public function withSet(array $rules): void
{
$this->rules = [];
foreach ($rules as $rulesKey => $rulesNode) {
if(!isset($rulesNode['key'], $rulesNode['routes'])) continue;
$rulesNode['key'] = trim($rulesNode['key'], '/');
if(!preg_match("'^[A-z0-9_/]+$'", $rulesNode['key'])) continue;
$this->rules[$rulesKey] = $rulesNode;
}
}
/** @inheritDoc */
public function match(RequestInterface $request): ?array { public function match(RequestInterface $request): ?array {
foreach ($this->rules as $rule) { foreach ($this->rules as $rule) {
@@ -96,4 +106,31 @@ class Router implements RouterInterface {
} }
return null; return null;
} }
}
/** @inheritDoc */
public function matchByArgv(RequestInterface $request): ?array {
foreach ($this->rules as $rule) {
// вычисляем строку для поиска
$currentString = trim(preg_replace("'^".preg_quote($this->startPoint)."/'", "", $request->getServerParams()['argv'][1]),'/');
// в цикле проверяем совпадения текущей строки с правилами
if ($rule['key'] == $currentString) {
$routes = [];
foreach ($rule['routes'] as $route) {
$className = (!empty($route['action'])) ? $route['action'] : "";
$methodName = (!empty($route['method'])) ? $route['method'] : "";
$params = [];
foreach ($request->getServerParams()['argv'] as $key => $param){
if($key < 2) continue;
$params[$key] = (preg_match("'^[0-9]+$'", $param)) ? (int) $param : $param;
}
$routes[] = new MatchObject($className, $methodName, $params);
}
return $routes;
}
}
return null;
}
}