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
7 changes: 3 additions & 4 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ name: PHP package checks

on:
push:
branches: [main, master]
pull_request:
branches: [main, master]
workflow_dispatch:
Expand Down Expand Up @@ -34,11 +33,11 @@ jobs:
- name: Validate Composer manifest and lock
run: composer validate --no-check-publish --no-interaction

- name: Install locked dependencies
run: composer install --prefer-dist --no-interaction --no-progress --no-scripts
- name: Resolve and install allowed dependencies
run: composer update --prefer-dist --no-interaction --no-progress --no-scripts

- name: Check PHP syntax
run: find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l
run: composer lint --no-interaction

- name: Run declared tests
shell: bash
Expand Down
22 changes: 12 additions & 10 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added
- Add middleware bootstrap regression tests and Composer test/lint scripts.

### Changed
- Run regression tests and syntax checks in GitHub Actions against the currently allowed dependency graph.

### Planned
- Middleware caching
- Conditional middleware

## [2.0.3] - 2026-11-20

### Changed
Expand Down Expand Up @@ -32,13 +44,3 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Fixed middleware execution in edge cases
- Improved error handling in middleware

---

## [Unreleased]

### Planned
- Middleware caching
- Conditional middleware
- Middleware testing helpers

15 changes: 9 additions & 6 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ HTTP request middleware support for Triangle applications. This package provides
- `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`.
Triangle Engine 9 has a stable `9.0.0` release, published on November 20, 2026. Middleware's `^8.1 || ^9.0` constraint allows Engine 8.1 up to 9.0 and Engine 9.x. Check the versions actually selected by Composer with `composer show triangle/middleware triangle/engine`.

## Installation

Expand Down Expand Up @@ -70,17 +70,20 @@ Global middleware can be omitted for an individual lookup with `withGlobal: fals

## 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.
`composer test` runs the middleware bootstrap regression suite. It covers registration order and scope for global, plugin and app middleware, `withGlobal: false`, and errors for invalid configuration. `composer lint` checks PHP syntax in source and test files.

To run the same basic checks locally, use the workflow commands:
GitHub Actions runs both checks on PHP 8.1 and 8.5. This library does not track `composer.lock`, so each CI run resolves versions within the constraints in `composer.json`. The tests cover bootstrap behavior and the prepared handler list; they do not exercise a complete HTTP request through Triangle HTTP.

Run the local checks with:

```sh
composer update --prefer-dist --no-interaction --no-progress
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
composer lint
composer test
```

Run integration checks in an application using the Engine and HTTP component versions that it actually installs.
For HTTP-level behavior, use integration tests in an application with its installed Engine and HTTP component versions.

## License

Expand Down
15 changes: 9 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
- `triangle/router` версии `^2.0`.
- Текущая исходная ветка объявляет `triangle/engine` `^8.1 || ^9.0`.

Engine 9 пока не имеет стабильного тега. Ограничение в исходниках не подтверждает наличие опубликованного стабильного пакета с поддержкой Engine 9. Проверяйте разрешённые Composer версии командой `composer show triangle/middleware triangle/engine`.
Стабильный Triangle Engine 9 опубликован как версия `9.0.0` 20 ноября 2026 года. Ограничение Middleware `^8.1 || ^9.0` разрешает Engine 8.1+ до 9.0 и Engine 9.x. Фактически выбранные версии проверяйте командой `composer show triangle/middleware triangle/engine`.

## Установка

Expand Down Expand Up @@ -70,17 +70,20 @@ Bootstrap также считывает глобальную конфигура

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

В этом репозитории нет каталога тестов, dev-зависимости PHPUnit или Composer script для тестирования. Workflow GitHub Actions проверяет манифест Composer, устанавливает зависимости и выполняет `php -l` для PHP-файлов; шаг тестов сообщает, что скрипт не объявлен. Эти проверки не подтверждают поведение middleware в полном HTTP-запросе.
`composer test` запускает regression suite загрузчика middleware. Проверяются порядок и область действия global, plugin и app middleware, параметр `withGlobal: false`, а также ошибки некорректной конфигурации. `composer lint` проверяет синтаксис PHP в исходниках и тестах.

Для локальной проверки тех же базовых условий используйте команды из CI:
GitHub Actions выполняет эти проверки на PHP 8.1 и 8.5. Поскольку это библиотека, `composer.lock` не хранится в репозитории: каждый CI запуск разрешает версии по ограничениям `composer.json`. Тесты проверяют загрузчик и список обработчиков; полный цикл HTTP-запроса с Triangle HTTP здесь не запускается.

Локальный запуск:

```sh
composer update --prefer-dist --no-interaction --no-progress
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
composer lint
composer test
```

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

## Лицензия

Expand Down
4 changes: 4 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@
"triangle/router": "^2.0",
"triangle/engine": "^8.1 || ^9.0"
},
"scripts": {
"test": "php tests/bootstrap-regression.php",
"lint": "find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l"
},
"suggest": {
},
"config": {
Expand Down
105 changes: 105 additions & 0 deletions tests/bootstrap-regression.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php declare(strict_types=1);

/**
* @package Triangle Middleware Component
* @link https://github.com/Triangle-org/Middleware
* @author Ivan Zorin <creator@localzet.com>
* @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
*/

require dirname(__DIR__) . '/vendor/autoload.php';

use Triangle\Engine\Config;
use Triangle\Middleware\Bootstrap;

final class GlobalMiddlewareOne
{
public static function process(mixed $request, callable $handler): mixed {}
}

final class GlobalMiddlewareTwo
{
public static function process(mixed $request, callable $handler): mixed {}
}

final class PluginGlobalMiddleware
{
public static function process(mixed $request, callable $handler): mixed {}
}

final class PluginAppMiddlewareOne
{
public static function process(mixed $request, callable $handler): mixed {}
}

final class PluginAppMiddlewareTwo
{
public static function process(mixed $request, callable $handler): mixed {}
}

final class MiddlewareWithoutProcess {}

function assertSameValue(mixed $expected, mixed $actual, string $message): void
{
if ($expected !== $actual) {
throw new RuntimeException($message . '\nExpected: ' . var_export($expected, true) . '\nActual: ' . var_export($actual, true));
}
}

function assertRuntimeException(callable $operation, string $message): void
{
try {
$operation();
} catch (RuntimeException) {
return;
}

throw new RuntimeException($message);
}

Config::set(['app' => ['plugin_alias' => 'plugin']]);

Bootstrap::load(['@' => [GlobalMiddlewareOne::class, GlobalMiddlewareTwo::class]]);
Bootstrap::load(['' => [PluginGlobalMiddleware::class]], 'acme');
Bootstrap::load(['plugin.acme.api' => [PluginAppMiddlewareOne::class, PluginAppMiddlewareTwo::class]]);

$middleware = Bootstrap::getMiddleware('acme', 'api', static fn () => null, null);
assertSameValue(
[
[PluginAppMiddlewareTwo::class, 'process'],
[PluginAppMiddlewareOne::class, 'process'],
[PluginGlobalMiddleware::class, 'process'],
[GlobalMiddlewareTwo::class, 'process'],
[GlobalMiddlewareOne::class, 'process'],
],
$middleware,
'Middleware must be scoped and returned in reverse registration order.'
);

assertSameValue(
[[PluginAppMiddlewareTwo::class, 'process'], [PluginAppMiddlewareOne::class, 'process']],
Bootstrap::getMiddleware('acme', 'api', static fn () => null, null, false),
'withGlobal=false must keep app middleware and omit plugin/global middleware.'
);
assertSameValue(
[[PluginGlobalMiddleware::class, 'process'], [GlobalMiddlewareTwo::class, 'process'], [GlobalMiddlewareOne::class, 'process']],
Bootstrap::getMiddleware('acme', 'other', static fn () => null, null),
'Plugin global middleware must apply to other apps within the same plugin.'
);
assertSameValue(
[[GlobalMiddlewareTwo::class, 'process'], [GlobalMiddlewareOne::class, 'process']],
Bootstrap::getMiddleware('other', 'api', static fn () => null, null),
'Global middleware must apply outside the configured plugin.'
);

assertRuntimeException(
static fn () => Bootstrap::load(['api' => 'invalid']),
'A non-array middleware list must throw RuntimeException.'
);
assertRuntimeException(
static fn () => Bootstrap::load(['api' => [MiddlewareWithoutProcess::class]]),
'A class without process() must throw RuntimeException.'
);

fwrite(STDOUT, "Middleware bootstrap regressions passed.\n");