Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<p align="center"><a href="https://www.localzet.com" target="_blank">
<img src="https://static.zorin.space/media/logos/LocalzetGroup.png" width="400" alt="Localzet Group">
</a></p>

# Triangle Router

[![Packagist version](https://img.shields.io/packagist/v/triangle/router)](https://packagist.org/packages/triangle/router)
[![PHP requirement](https://img.shields.io/packagist/dependency-v/triangle/router/php)](https://packagist.org/packages/triangle/router)
[![License](https://img.shields.io/github/license/Triangle-org/Router)](https://github.com/Triangle-org/Router)

Triangle Router matches HTTP methods and URI paths against route patterns and returns the matched handler with named parameters. It is a routing component; the application remains responsible for invoking handlers and producing HTTP responses.

[Русская документация](README.md)

## Requirements and compatibility

- PHP 8.1 or later (`^8.1` in Composer).
- `triangle/engine` `^8.1 || ^9.0` in the current source branch.

Engine 9 does not yet have a stable release tag. The source constraint is not proof that a stable published Composer release is available or verified against Engine 9. Check the resolved packages with `composer show triangle/router triangle/engine`.

## Installation

```sh
composer require triangle/router
```

Composer loads the package functions from `src/functions.php`, so the Composer autoloader must be included before calling `simpleRouteDispatcher()` or `cachedRouteDispatcher()`.

## Quick start

```php
<?php

require __DIR__ . '/vendor/autoload.php';

$dispatcher = simpleRouteDispatcher(static function (Triangle\Router $router): void {
$router->addRoute('GET', '/users/{id:\\d+}', static fn (array $params): array => $params);
});

$result = $dispatcher->dispatch('GET', '/users/42');

switch ($result[0]) {
case Triangle\Router\Dispatcher::FOUND:
[$status, $handler, $parameters] = $result;
// Invoke the handler and translate its result to an HTTP response.
break;

case Triangle\Router\Dispatcher::METHOD_NOT_ALLOWED:
$allowedMethods = $result[1];
// Return 405 and include the methods in the Allow response header.
break;

case Triangle\Router\Dispatcher::NOT_FOUND:
// Return 404.
break;
}
```

`FOUND` results contain the handler and an associative array of route parameters. `METHOD_NOT_ALLOWED` results contain the allowed HTTP methods in the second tuple item. The router does not create the HTTP response or set its headers.

## Defining routes

`simpleRouteDispatcher()` accepts a callback that receives a `Triangle\Router` instance. Register one or several methods:

```php
$router->addRoute('GET', '/health', static fn (): string => 'ok');
$router->addRoute(['GET', 'POST'], '/users', static fn (): array => []);
$router->addRoute('GET', '/users/{id:\\d+}[/{tab}]', static fn (array $params): array => $params);
```

A `{name}` placeholder matches a non-empty path segment by default. Add a regular expression after the colon to constrain it, such as `{id:\\d+}`. Bracketed sections are optional route parts. Custom expressions should not capture groups that alter parameter matching.

Route groups can prefix multiple routes. The package also provides the `get`, `post`, `put`, `patch`, `delete`, `head`, `options`, and `any` helper methods through `Triangle\Router`; see the class API for their exact signatures.

## Route cache

For applications that want to persist the generated dispatch data, use `cachedRouteDispatcher()` and supply a cache file:

```php
$dispatcher = cachedRouteDispatcher($defineRoutes, [
'cacheFile' => __DIR__ . '/var/routes.php',
]);
```

The helper loads an existing PHP cache file unless `cacheDisabled` is enabled; otherwise it builds the route data and writes it to the configured path. Ensure the deployment process can write that path when generating the cache, and regenerate it whenever route definitions change. Do not use a writable cache directory as a trust boundary: the generated file is executable PHP.

## HTTP method behavior

The dispatcher reports `FOUND`, `NOT_FOUND`, or `METHOD_NOT_ALLOWED`. Applications should turn these into appropriate responses and include an `Allow` header for a 405 response using the methods returned by the dispatcher.

A GET route can also match HEAD when no explicit HEAD route exists. PHP SAPI normally suppresses the response body for HEAD. Applications running outside PHP SAPI must suppress it themselves; the router does not control response transmission.

## Triangle Engine integration

The package includes `Triangle\Router\Bootstrap`, which implements the Engine bootstrap interface. When started with a `localzet\Server` instance it collects route configuration from the configured application paths and plugin configuration directories. For framework applications, follow the Engine bootstrap and route-configuration conventions of the Engine version actually installed. The standalone dispatcher examples above do not require the Engine request lifecycle.

## Tests

Run the repository's declared test suite from its root:

```sh
composer test --no-interaction
```

This runs PHPUnit using `tests/phpunit.xml`. The current unit suite contains four tests in `tests/Unit/RouteTest.php`; it is not an exhaustive integration or production compatibility suite.

## License

AGPL-3.0-or-later. See [LICENSE](LICENSE).
31 changes: 25 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
composer require triangle/router
```

Требуется PHP 8.0 или выше.
Требуется PHP 8.1 или выше (ограничение `^8.1` в Composer).

Usage
-----
Expand All @@ -47,7 +47,7 @@ Usage

require '/path/to/vendor/autoload.php';

$dispatcher = simpleRouteDispatcher(function(Triangle\Router\RouteCollector $r) {
$dispatcher = simpleRouteDispatcher(function(Triangle\Router $r) {
$r->addRoute('GET', '/users', 'get_all_users_handler');
// {id} должен быть числом (\d+)
$r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler');
Expand Down Expand Up @@ -85,7 +85,7 @@ switch ($routeInfo[0]) {
### Определение маршрутов

Маршруты определяются путем вызова функции `simpleRouteDispatcher()`, которая принимает
вызываемый объект, принимающий экземпляр `Triangle\Router\RouteCollector`. Маршруты добавляются путем вызова
вызываемый объект, принимающий экземпляр `Triangle\Router`. Маршруты добавляются путем вызова
`addRoute()` на экземпляре коллектора:

```php
Expand Down Expand Up @@ -172,7 +172,7 @@ $r->any('/any-route', 'any_handler');
Например, определение ваших маршрутов как:

```php
$r->addGroup('/admin', function (RouteCollector $r) {
$r->addGroup('/admin', function (\Triangle\Router $r) {
$r->addRoute('GET', '/do-something', 'handler');
$r->addRoute('GET', '/do-another-thing', 'handler');
$r->addRoute('GET', '/do-something-else', 'handler');
Expand All @@ -198,7 +198,7 @@ $r->addRoute('GET', '/admin/do-something-else', 'handler');
```php
<?php

$dispatcher = cachedRouteDispatcher(function(Triangle\Router\RouteCollector $r) {
$dispatcher = cachedRouteDispatcher(function(Triangle\Router $r) {
$r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0');
$r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1');
$r->addRoute('GET', '/user/{name}', 'handler2');
Expand Down Expand Up @@ -296,7 +296,7 @@ interface Dispatcher {
```php
<?php

$dispatcher = simpleRouteDispatcher(function(Triangle\Router\RouteCollector $r) {
$dispatcher = simpleRouteDispatcher(function(Triangle\Router $r) {
/* ... */
}, [
'routeParser' => 'Triangle\\Router\\RouteParser\\Std',
Expand Down Expand Up @@ -325,6 +325,25 @@ $dispatcher = simpleRouteDispatcher(function(Triangle\Router\RouteCollector $r)
Наконец, обратите внимание, что приложения МОГУТ всегда указывать свой собственный маршрут метода HEAD для данного ресурса,
чтобы полностью обойти это поведение.


## Версия и совместимость

Текущий исходный код требует PHP 8.1+ и объявляет совместимость с `triangle/engine` `^8.1 || ^9.0`. Ветка Engine 9 пока не имеет стабильного релизного тега: наличие ограничения в исходной ветке не означает, что опубликованный пакет Composer уже выпущен и проверен с Engine 9. Проверяйте фактически установленную версию через `composer show triangle/router triangle/engine`.

Пакет подключает глобальные функции `simpleRouteDispatcher()`, `cachedRouteDispatcher()` и `route()` через Composer autoload. Маршрутизатор возвращает кортеж статуса, обработчика и параметров; формирование HTTP-ответа и заголовка `Allow` для 405 остаётся задачей приложения. При использовании GET-маршрута для HEAD приложение вне PHP SAPI должно само подавить тело ответа.

## Проверки

Запуск тестов из корня репозитория:

```sh
composer test --no-interaction
```

Команда запускает PHPUnit с конфигурацией `tests/phpunit.xml`. Набор `tests/Unit/RouteTest.php` содержит четыре теста; фактическое число assertions зависит от результата PHPUnit. Это небольшой unit-набор, а не подтверждение полного поведения в production или совместимости со всеми версиями Engine.

Документация: [English](README.en.md).

### Авторы

Эта библиотека основана на маршрутизаторах, реализованных [Levi Morrison][levi] и [Nikita Popov][nikic].
Expand Down
2 changes: 1 addition & 1 deletion Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
},
"require": {
"php": "^8.1",
"triangle/engine": "^8.1"
"triangle/engine": "^8.1 || ^9.0"
},
"require-dev": {
"phpunit/phpunit": "^10.5"
Expand Down
2 changes: 1 addition & 1 deletion src/BadRouteException.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Config/route.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/DataGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/DataGenerator/CharCountBased.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/DataGenerator/GroupCountBased.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/DataGenerator/GroupPosBased.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/DataGenerator/MarkBased.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/DataGenerator/RegexBasedAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Dispatcher/CharCountBased.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Dispatcher/GroupCountBased.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Dispatcher/GroupPosBased.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Dispatcher/MarkBased.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Dispatcher/RegexBasedAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/RouteObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/RouteParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/RouteParser/Std.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/RouteStatic.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Router
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
Loading