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
87 changes: 87 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Triangle Middleware

[![Packagist version](https://img.shields.io/packagist/v/triangle/middleware)](https://packagist.org/packages/triangle/middleware)
[![PHP requirement](https://img.shields.io/packagist/dependency-v/triangle/middleware/php)](https://packagist.org/packages/triangle/middleware)

HTTP request middleware support for Triangle applications. This package provides a middleware contract and a loader that collects handlers from application configuration, routes, and controller attributes. The integrating application, such as Triangle HTTP, invokes the chain and converts its result into an HTTP response.

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

## Requirements and compatibility

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

Engine 9 does not yet have a stable tag. A constraint in the source branch does not establish that a stable package release supporting Engine 9 is published. Check the resolved Composer versions with `composer show triangle/middleware triangle/engine`.

## Installation

```sh
composer require triangle/middleware
```

## Middleware contract

```php
<?php

use Triangle\Middleware\MiddlewareInterface;

final class RequestLogMiddleware implements MiddlewareInterface
{
public function process($request, callable $handler)
{
// Inspect or modify the request before passing it on.
$response = $handler($request);

// Inspect or modify the downstream response.
return $response;
}
}
```

Calling `$handler($request)` passes the request to the next handler. Middleware may return a response without invoking the handler, or return the downstream result. The request and response objects are defined by the integrating application.

`MiddlewareInterface` is not a strict PSR-15 implementation: the request parameter and return value are untyped, and the handler is a `callable` rather than a typed PSR-15 `RequestHandlerInterface`. Do not assume PSR-7/PSR-15 compatibility without an adapter and verification of your application's request and response types.

## Configuration

The component ships `src/Config/middleware.php` with an empty list for the `''` application. `Triangle\Middleware\Bootstrap` accepts a map from application names to lists of middleware classes with a `process` method:

```php
<?php

return [
'@' => [RequestLogMiddleware::class],
'api' => [ApiAccessMiddleware::class],
];
```

`@` denotes the shared middleware scope; an application name such as `api` denotes middleware for that application. Configuration entries must be arrays. The loader checks for a `process` method, but does not require the class to implement `MiddlewareInterface`. Invalid structure or a missing method raises `RuntimeException`.

The bootstrap also reads Engine global configuration, static configuration, application configuration, and plugin configuration. `getMiddleware()` includes route middleware, `Triangle\Annotation\Middleware` attributes on controller classes or methods, and a controller's public `middleware` property when present. These mechanisms require the corresponding Triangle components; this package is not a standalone HTTP server.

### Ordering and scope

`getMiddleware()` returns a prepared list for wrapping a handler. Triangle HTTP applies the list through nested calls: each middleware receives the request and a callable for the next handler. The effective sequence depends on configuration scope and declaration site; verify ordering against the Engine HTTP version in use before relying on side-effect order.

Global middleware can be omitted for an individual lookup with `withGlobal: false`. Registration is stored in process-wide static state. Loading configuration repeatedly in the same process appends entries; it does not clear prior registrations.

## Tests and verification limits

This repository has no test directory, PHPUnit development dependency, or Composer test script. Its GitHub Actions workflow validates the Composer manifest, installs dependencies, and runs `php -l` on PHP files. The test step reports that no test script is declared. These checks do not verify middleware behavior across a complete HTTP request.

To run the same basic checks locally, use the workflow commands:

```sh
composer validate --no-check-publish --no-interaction
composer install --prefer-dist --no-interaction --no-progress --no-scripts
find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l
```

Run integration checks in an application using the Engine and HTTP component versions that it actually installs.

## License

AGPL-3.0-or-later. See [LICENSE](LICENSE).
108 changes: 87 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,87 @@
<p align="center"><a href="https://www.localzet.com" target="_blank">
<img src="https://static.zorin.space/media/logos/LocalzetGroup.png" width="400">
</a></p>

<p align="center">
<a href="https://packagist.org/packages/triangle/middleware">
<img src="https://img.shields.io/packagist/dt/triangle/middleware?label=%D0%A1%D0%BA%D0%B0%D1%87%D0%B8%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F" alt="Скачивания">
</a>
<a href="https://github.com/Triangle-org/Middleware">
<img src="https://img.shields.io/github/commit-activity/t/Triangle-org/Middleware?label=%D0%9A%D0%BE%D0%BC%D0%BC%D0%B8%D1%82%D1%8B" alt="Коммиты">
</a>
<a href="https://packagist.org/packages/triangle/middleware">
<img src="https://img.shields.io/packagist/v/triangle/middleware?label=%D0%92%D0%B5%D1%80%D1%81%D0%B8%D1%8F" alt="Версия">
</a>
<a href="https://packagist.org/packages/triangle/middleware">
<img src="https://img.shields.io/packagist/dependency-v/triangle/middleware/php?label=PHP" alt="Версия PHP">
</a>
<a href="https://github.com/Triangle-org/Middleware">
<img src="https://img.shields.io/github/license/Triangle-org/Middleware?label=%D0%9B%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F" alt="Лицензия">
</a>
</p>
# Triangle Middleware

[![Packagist version](https://img.shields.io/packagist/v/triangle/middleware)](https://packagist.org/packages/triangle/middleware)
[![PHP requirement](https://img.shields.io/packagist/dependency-v/triangle/middleware/php)](https://packagist.org/packages/triangle/middleware)

Промежуточные обработчики HTTP-запросов для приложений Triangle. Пакет предоставляет контракт middleware и загрузчик, который собирает обработчики из конфигурации приложения, маршрута и атрибутов контроллера. Вызов цепочки и преобразование результата в HTTP-ответ выполняет интегрирующее приложение, например Triangle HTTP.

[English documentation](README.en.md)

## Требования и совместимость

- PHP 8.1 или новее (`^8.1` в Composer).
- `triangle/router` версии `^2.0`.
- Текущая исходная ветка объявляет `triangle/engine` `^8.1 || ^9.0`.

Engine 9 пока не имеет стабильного тега. Ограничение в исходниках не подтверждает наличие опубликованного стабильного пакета с поддержкой Engine 9. Проверяйте разрешённые Composer версии командой `composer show triangle/middleware triangle/engine`.

## Установка

```sh
composer require triangle/middleware
```

## Контракт обработчика

```php
<?php

use Triangle\Middleware\MiddlewareInterface;

final class RequestLogMiddleware implements MiddlewareInterface
{
public function process($request, callable $handler)
{
// Inspect or modify the request before passing it on.
$response = $handler($request);

// Inspect or modify the downstream response.
return $response;
}
}
```

Вызов `$handler($request)` передаёт запрос следующему обработчику. Middleware может вернуть ответ самостоятельно, не вызывая `$handler`, либо вернуть результат следующего обработчика. Тип запроса, тип результата и конкретный объект ответа определяются используемым приложением.

`MiddlewareInterface` не является строгой реализацией PSR-15: параметр запроса и возвращаемое значение не типизированы, а обработчик задан как `callable`, а не типизированный PSR-15 `RequestHandlerInterface`. Не предполагайте совместимость с PSR-7/PSR-15 без адаптера и проверки типов запросов/ответов вашего приложения.

## Конфигурация

Установщик компонента содержит пример файла `src/Config/middleware.php` с пустым списком для приложения `''`. Загрузчик `Triangle\Middleware\Bootstrap` принимает массив, где ключ — приложение, а значение — список классов middleware с методом `process`:

```php
<?php

return [
'@' => [RequestLogMiddleware::class],
'api' => [ApiAccessMiddleware::class],
];
```

`@` задаёт middleware общего уровня; имя приложения, например `api`, задаёт обработчики приложения. Записи конфигурации должны быть массивами. При загрузке проверяется наличие метода `process`; соответствие `MiddlewareInterface` не обязательно. Если метод отсутствует или структура неверна, загрузчик выбрасывает `RuntimeException`.

Bootstrap также считывает глобальную конфигурацию Engine, статическую конфигурацию, конфигурацию приложений и плагинов. `getMiddleware()` добавляет middleware маршрута, атрибута `Triangle\Annotation\Middleware` на классе/методе контроллера и публичного свойства контроллера `middleware`, если они заданы. Эти механизмы требуют соответствующих компонентов Triangle и не являются отдельным HTTP-сервером.

### Порядок и область действия

`getMiddleware()` возвращает подготовленный список для дальнейшего оборачивания обработчика. В Engine HTTP список применяется через вложенные вызовы: каждый middleware получает запрос и callable следующего обработчика. Фактическая последовательность зависит от уровня конфигурации и места объявления; проверьте порядок для используемой версии Engine HTTP, прежде чем полагаться на порядок побочных эффектов.

Глобальные обработчики могут отключаться для конкретного вызова параметром `withGlobal: false`. Регистрация кэшируется в статическом состоянии процесса; повторная загрузка конфигурации в том же процессе добавляет элементы, а не очищает ранее зарегистрированные.

## Проверки и ограничения тестирования

В этом репозитории нет каталога тестов, dev-зависимости PHPUnit или Composer script для тестирования. Workflow GitHub Actions проверяет манифест Composer, устанавливает зависимости и выполняет `php -l` для PHP-файлов; шаг тестов сообщает, что скрипт не объявлен. Эти проверки не подтверждают поведение middleware в полном HTTP-запросе.

Для локальной проверки тех же базовых условий используйте команды из CI:

```sh
composer validate --no-check-publish --no-interaction
composer install --prefer-dist --no-interaction --no-progress --no-scripts
find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l
```

Запускайте интеграционные проверки в приложении с теми версиями Engine и HTTP-компонента, которые использует проект.

## Лицензия

AGPL-3.0-or-later. См. [LICENSE](LICENSE).
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"require": {
"php": "^8.1",
"triangle/router": "^2.0",
"triangle/engine": "^8.1"
"triangle/engine": "^8.1 || ^9.0"
},
"suggest": {
},
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/Middleware
*
* @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/middleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Middleware
*
* @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/Middleware
*
* @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/MiddlewareInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Middleware
*
* @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