From 7093e3d44bfa4f87174230f83af9c7f039e2bbec Mon Sep 17 00:00:00 2001 From: bidi Date: Thu, 12 Nov 2026 01:07:35 +0200 Subject: [PATCH 1/2] code refactor, updated composer, docs, workflow, tests Signed-off-by: bidi --- .github/workflows/codecov.yml | 11 +- .github/workflows/static-analysis.yml | 13 +- .gitignore | 1 + .laminas-ci.json | 5 +- CHANGELOG.md | 76 +++ README.md | 23 +- SECURITY.md | 8 +- composer.json | 15 +- docs/book/v2/configuration.md | 7 + docs/book/v2/features.md | 106 +++ docs/book/v2/installation.md | 15 + docs/book/v2/overview.md | 19 + docs/book/v2/tutorials/create-route-group.md | 186 ++++++ docs/book/v2/tutorials/create-single-route.md | 112 ++++ docs/book/v2/upgrading.md | 53 ++ docs/book/v2/usage.md | 13 + mkdocs.yml | 13 +- phpstan.neon | 2 +- phpunit.xml | 25 +- src/ConfigProvider.php | 8 + src/Exception/InvalidArgumentException.php | 18 + src/Exception/InvalidMiddlewareException.php | 38 ++ src/Exception/MissingMiddlewareException.php | 22 + src/Factory/RouteCollectorFactory.php | 14 +- src/Factory/RouteGroupCollectorFactory.php | 15 +- src/MiddlewareContainer.php | 34 +- src/MiddlewareFactory.php | 47 +- src/RouteCollector.php | 42 ++ src/RouteCollectorInterface.php | 43 ++ src/RouteGroupCollector.php | 126 +++- src/RouteGroupCollectorInterface.php | 49 ++ test/AbstractRouterTestCase.php | 60 ++ test/ConfigProviderTest.php | 7 +- test/Factory/FactoryTest.php | 92 +++ test/Fixture/CallLog.php | 49 ++ test/Fixture/FallbackHandler.php | 22 + test/Fixture/FirstMiddleware.php | 20 + test/Fixture/InMemoryContainer.php | 39 ++ test/Fixture/MiddlewareWithArgument.php | 25 + test/Fixture/SecondMiddleware.php | 20 + test/Fixture/ServiceNotFoundException.php | 18 + test/Fixture/TestHandler.php | 19 + test/Middleware/LazyLoadingMiddlewareTest.php | 31 + test/MiddlewareContainerTest.php | 91 +++ test/MiddlewareFactoryTest.php | 106 +++ test/RouteCollectorTest.php | 265 ++++---- test/RouteGroupCollectorTest.php | 620 ++++++++---------- 47 files changed, 2034 insertions(+), 609 deletions(-) create mode 100644 docs/book/v2/configuration.md create mode 100644 docs/book/v2/features.md create mode 100644 docs/book/v2/installation.md create mode 100644 docs/book/v2/overview.md create mode 100644 docs/book/v2/tutorials/create-route-group.md create mode 100644 docs/book/v2/tutorials/create-single-route.md create mode 100644 docs/book/v2/upgrading.md create mode 100644 docs/book/v2/usage.md create mode 100644 src/Exception/InvalidArgumentException.php create mode 100644 src/Exception/InvalidMiddlewareException.php create mode 100644 src/Exception/MissingMiddlewareException.php create mode 100644 test/AbstractRouterTestCase.php create mode 100644 test/Factory/FactoryTest.php create mode 100644 test/Fixture/CallLog.php create mode 100644 test/Fixture/FallbackHandler.php create mode 100644 test/Fixture/FirstMiddleware.php create mode 100644 test/Fixture/InMemoryContainer.php create mode 100644 test/Fixture/MiddlewareWithArgument.php create mode 100644 test/Fixture/SecondMiddleware.php create mode 100644 test/Fixture/ServiceNotFoundException.php create mode 100644 test/Fixture/TestHandler.php create mode 100644 test/Middleware/LazyLoadingMiddlewareTest.php create mode 100644 test/MiddlewareContainerTest.php create mode 100644 test/MiddlewareFactoryTest.php diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index c0fbc53..327dea7 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v3 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -44,12 +44,13 @@ jobs: php${{ matrix.php }}-composer- - name: Install dependencies with composer - run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi + # laminas/laminas-stratigility does not declare PHP 8.6 yet; drop the flag once it does. + run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi ${{ matrix.php == '8.6' && '--ignore-platform-req=php+' || '' }} - name: Collect code coverage with PHPUnit run: vendor/bin/phpunit --colors=always --coverage-clover clover.xml - name: Send code coverage report to Codecov.io - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v7 with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 9976515..19ef7e6 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -4,7 +4,7 @@ on: name: Run PHPStan checks jobs: - mutation: + static-analysis: name: PHPStan ${{ matrix.php }}-${{ matrix.os }} runs-on: ${{ matrix.os }} @@ -15,20 +15,20 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 with: php-version: "${{ matrix.php }}" - coverage: pcov + coverage: none ini-values: assert.exception=1, zend.assertions=1, error_reporting=-1, log_errors_max_len=0, display_errors=On tools: composer:v2, cs2pr @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -44,7 +44,8 @@ jobs: php${{ matrix.php }}-composer- - name: Install dependencies with composer - run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi + # laminas/laminas-stratigility does not declare PHP 8.6 yet; drop the flag once it does. + run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi ${{ matrix.php == '8.6' && '--ignore-platform-req=php+' || '' }} - name: Run static analysis with PHPStan run: vendor/bin/phpstan analyse diff --git a/.gitignore b/.gitignore index be50580..9838bf1 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ composer.phar /vendor/ .phpcs-cache .phpunit.result.cache +.phpunit.cache # Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file # You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file diff --git a/.laminas-ci.json b/.laminas-ci.json index 29216fa..efdd72e 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -1,3 +1,6 @@ { - "backwardCompatibilityCheck": true + "ignore_php_platform_requirements": { + "8.6": true + }, + "backwardCompatibilityCheck": false } diff --git a/CHANGELOG.md b/CHANGELOG.md index 825c32f..38e5ae7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1 +1,77 @@ # Changelog + +All notable changes to this project are documented in this file. + +## 2.0.0 - TBD + +### Added + +- PHP 8.6 support. +- `Dot\Router\Exception\MissingMiddlewareException` (PSR-11 not-found), `InvalidMiddlewareException` (PSR-11 container exception) and `InvalidArgumentException`. +- Version 2 documentation and an upgrade guide. + +### Changed + +- Group middleware now also runs for callable route handlers (closures and callable arrays). +- `$excludeMiddleware` now removes group middleware only, never the route's own middleware or handler, and matches middleware objects by class. +- `MiddlewareContainer::get()` throws PSR-11 exceptions instead of `Exception` or `ArgumentCountError`. +- `MiddlewareFactory::pipeline()` and `prepare([])` throw `InvalidArgumentException` for an empty list. +- A group route whose prefix and path are both empty throws `InvalidArgumentException`. +- Minimum `mezzio/mezzio-fastroute` is `^3.15`; `mezzio/mezzio-router` and `psr/http-server-handler` are now declared requirements; minimum `psr/container` is `^1.1.2`. +- PHPDoc types narrowed for static analysis: `non-empty-string` paths and names, `list` methods. +- PHPStan level 8, PHPUnit 12. + +### Removed + +- PHP 8.2 support. + +### Fixed + +- A `RouteGroupCollector` created by the container, or with `new`, no longer fails with an uninitialized `$middleware` property. +- Building a pipeline from an empty list no longer raises a PHP warning. + +## 1.1.0 - 2025-10-30 + +### Added + +- PHP 8.4 and 8.5 support (#11). + +### Removed + +- PHP 8.1 support (#11). + +## 1.0.5 - 2025-03-22 + +### Changed + +- Clearer instructions for creating single routes and route groups (#9). + +## 1.0.4 - 2025-03-20 + +### Changed + +- Group middleware is merged with the route handlers (#7). + +## 1.0.3 - 2025-03-20 + +### Changed + +- The middleware argument of `RouteCollector::group()` is optional (#5). + +## 1.0.2 - 2025-03-20 + +### Changed + +- Allow `laminas/laminas-stratigility` 3.x and 4.x (#3). + +## 1.0.1 - 2025-03-20 + +### Changed + +- Documentation tweaks. + +## 1.0.0 - 2025-03-20 + +### Added + +- Initial release. diff --git a/README.md b/README.md index 3520228..09fe4ef 100644 --- a/README.md +++ b/README.md @@ -11,22 +11,31 @@ Documentation is available at: https://docs.dotkernel.org/dot-router/. ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-router) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-router/1.1.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-router/2.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-router)](https://github.com/dotkernel/dot-router/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-router)](https://github.com/dotkernel/dot-router/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-router)](https://github.com/dotkernel/dot-router/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-router)](https://github.com/dotkernel/dot-router/blob/1.0/LICENSE) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-router)](https://github.com/dotkernel/dot-router/blob/2.0/LICENSE) -[![Build Static](https://github.com/dotkernel/dot-router/actions/workflows/continuous-integration.yml/badge.svg?branch=1.0)](https://github.com/dotkernel/dot-router/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-router/actions/workflows/continuous-integration.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-router/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-router/graph/badge.svg?token=ubNnFctuDR)](https://codecov.io/gh/dotkernel/dot-router) -[![PHPStan](https://github.com/dotkernel/dot-router/actions/workflows/static-analysis.yml/badge.svg?branch=1.0)](https://github.com/dotkernel/dot-router/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-router/actions/workflows/static-analysis.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-router/actions/workflows/static-analysis.yml) + +## Versions + +| Version | Supported PHP versions | Documentation | +| --- | --- | --- | +| 2.x | 8.3, 8.4, 8.5, 8.6 | https://docs.dotkernel.org/dot-router/v2/overview/ | +| 1.x | 8.2, 8.3, 8.4, 8.5 | https://docs.dotkernel.org/dot-router/v1/overview/ | + +Upgrading from 1.x? Read the [upgrade guide](https://docs.dotkernel.org/dot-router/v2/upgrading/). ## Requirements -- **PHP**: 8.2, 8.3, 8.4 or 8.5 +- **PHP**: 8.3, 8.4, 8.5 or 8.6 - **laminas/laminas-stratigility**: ^3.0 || ^4.0 -- **mezzio/mezzio-fastroute**: ^3.12 +- **mezzio/mezzio-fastroute**: ^3.15 ## Setup @@ -36,7 +45,7 @@ Run the following command in your application's root directory: composer require dotkernel/dot-router ``` -Open your application's `config/config.php` and the following line: +Open your application's `config/config.php` and add the following line: ```php Dot\Router\ConfigProvider::class, diff --git a/SECURITY.md b/SECURITY.md index 8d22317..845a7c7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,9 +2,10 @@ ## Supported Versions -| Version | Supported | PHP Version | -|---------|--------------------|---------------------------------------------------------------------------------------------------------| -| 1.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-cli/1.1.0) | +| Version | Supported | PHP Version | +|---------|------------------------------------|------------------------------------------------------------------------------------------------------------| +| 2.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-router/2.0.0) | +| 1.x | :white_check_mark: (security only) | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-router/1.1.0) | ## Reporting Potential Security Issues @@ -25,4 +26,3 @@ If we verify a reported security vulnerability, our policy is: - We will patch the current release branch, as well as the immediate prior minor release branch. - After patching the release branches, we will immediately issue new security fix releases for each patched release branch. - diff --git a/composer.json b/composer.json index c32ebb5..529d871 100644 --- a/composer.json +++ b/composer.json @@ -24,19 +24,20 @@ } }, "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", "laminas/laminas-stratigility": "^3.0 || ^4.0", - "mezzio/mezzio-fastroute": "^3.12", - "psr/container": "^1.0 || ^2.0", + "mezzio/mezzio-fastroute": "^3.15", + "mezzio/mezzio-router": "^3.18 || ^4.0.1", + "psr/container": "^1.1.2 || ^2.0", "psr/http-message": "^1.0 || ^2.0", - "psr/http-server-middleware": "^1.0" - + "psr/http-server-handler": "^1.0.2", + "psr/http-server-middleware": "^1.0.2" }, "require-dev": { - "laminas/laminas-coding-standard": "^3.0", + "laminas/laminas-coding-standard": "^3.1", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.5" + "phpunit/phpunit": "^12.5" }, "autoload": { "psr-4": { diff --git a/docs/book/v2/configuration.md b/docs/book/v2/configuration.md new file mode 100644 index 0000000..08c9cc8 --- /dev/null +++ b/docs/book/v2/configuration.md @@ -0,0 +1,7 @@ +# Configuration + +After installation, register `dot-router` in your project by adding the below line to your configuration aggregator (usually: `config/config.php`): + +```php +Dot\Router\ConfigProvider::class, +``` diff --git a/docs/book/v2/features.md b/docs/book/v2/features.md new file mode 100644 index 0000000..76cdd12 --- /dev/null +++ b/docs/book/v2/features.md @@ -0,0 +1,106 @@ +# Features + +## Route groups + +During development, developers often need to create sets of visually similar routes. +The traditional way is creating each route, one by one, like in the below example: + +```php +$app->post('/product/create', CreateProductHandler::class, 'product:create'); +$app->delete('/product/delete/{id}', DeleteProductHandler::class, 'product:delete'); +$app->patch('/product/update/{id}', UpdateProductHandler::class, 'product:update'); +$app->get('/product/view/{id}', GetProductHandler::class, 'product:view'); +``` + +Besides the features provided by `mezzio/mezzio-fastroute`, `dot-router` offers route groups, which are collections of routes that (partially) share the same path. + +To use this feature, first get an instance of the `Dot\Router\RouteCollector` using the below code: + +```php +/** @var \Dot\Router\RouteCollectorInterface $routeCollector */ +$routeCollector = $container->get(\Dot\Router\RouteCollectorInterface::class); +``` + +Then rewrite the above routes using the below code: + +```php +$routeCollector->group('/product') + ->post('/create', CreateProductHandler::class, 'product:create') + ->delete('/delete/{id}', DeleteProductHandler::class, 'product:delete') + ->patch('/update/{id}', UpdateProductHandler::class, 'product:update') + ->get('/view/{id}', GetProductHandler::class, 'product:view'); +``` + +Note that **/product** becomes the group prefix and the routes only specify the part that is specific to them. +When `dot-router` registers the routes, it prepends the prefix to each route path. +The prefix and the path are joined as they are, so do not end the prefix with `/` (`/product/` plus `/create` gives `/product//create`). + +### Advantages + +- DRY: no need for repeating common route parts +- encapsulation: similar routes are grouped in a single block of code (vs. each route a separate statement) +- easy path refactoring: modify all routes at once by changing only the prefix +- easy copying/moving: copying/moving an entire group makes sure that you don't accidentally omit a route + +## Group middleware + +Besides sharing the same path, routes often share middleware too. +A good example is `CheckOwnerMiddleware` in the below example: + +```php +$app->delete('/product/delete/{id}', [CheckOwnerMiddleware::class, DeleteProductHandler::class], 'product:delete'); +$app->patch('/product/update/{id}', [CheckOwnerMiddleware::class, UpdateProductHandler::class], 'product:update'); +$app->get('/product/view/{id}', [CheckOwnerMiddleware::class, GetProductHandler::class], 'product:view'); +``` + +Pass the shared middleware as the second argument of `group()`, and `dot-router` runs it before the handler of every route in the group: + +```php +$routeCollector->group('/product', CheckOwnerMiddleware::class) + ->delete('/delete/{id}', DeleteProductHandler::class, 'product:delete') + ->patch('/update/{id}', UpdateProductHandler::class, 'product:update') + ->get('/view/{id}', GetProductHandler::class, 'product:view'); +``` + +Group middleware runs first, in the order given, followed by the route's own middleware and handler. +This applies to every kind of route handler: class names, objects, closures and other callables. + +## Exclude middleware + +Sometimes one route in a group must not run a group middleware. +In the below example, creating a product has no owner to check yet: + +```php +$app->post('/product/create', CreateProductHandler::class, 'product:create'); +$app->delete('/product/delete/{id}', [CheckOwnerMiddleware::class, DeleteProductHandler::class], 'product:delete'); +$app->patch('/product/update/{id}', [CheckOwnerMiddleware::class, UpdateProductHandler::class], 'product:update'); +$app->get('/product/view/{id}', [CheckOwnerMiddleware::class, GetProductHandler::class], 'product:view'); +``` + +For such cases, each group route accepts `$excludeMiddleware` as its last argument: + +```php +$routeCollector->group('/product', CheckOwnerMiddleware::class) + ->post('/create', CreateProductHandler::class, 'product:create', CheckOwnerMiddleware::class) + ->delete('/delete/{id}', DeleteProductHandler::class, 'product:delete') + ->patch('/update/{id}', UpdateProductHandler::class, 'product:update') + ->get('/view/{id}', GetProductHandler::class, 'product:view'); +``` + +The `product:create` route is now the equivalent of: + +```php +$app->post('/product/create', CreateProductHandler::class, 'product:create'); +``` + +How exclusion works: + +- `$excludeMiddleware` is a class name or a list of class names. +- It removes **group** middleware only. The route's own middleware and handler always run. +- A group middleware given as a class name is excluded when that exact name is listed. +- A group middleware given as an object is excluded when it is an instance of a listed class or interface. + +### Advantages + +- extends the DRYness of route groups by allowing to specify common middlewares only once per group +- shorter and easier-to-read route definitions diff --git a/docs/book/v2/installation.md b/docs/book/v2/installation.md new file mode 100644 index 0000000..02dd47c --- /dev/null +++ b/docs/book/v2/installation.md @@ -0,0 +1,15 @@ +# Installation + +Install `dotkernel/dot-router` by executing the following Composer command: + +```shell +composer require dotkernel/dot-router +``` + +## Requirements + +- **PHP**: 8.3, 8.4, 8.5 or 8.6 +- **laminas/laminas-stratigility**: ^3.0 || ^4.0 +- **mezzio/mezzio-fastroute**: ^3.15 + +Upgrading from version 1? Read the [upgrade guide](upgrading.md). diff --git a/docs/book/v2/overview.md b/docs/book/v2/overview.md new file mode 100644 index 0000000..9cb19dc --- /dev/null +++ b/docs/book/v2/overview.md @@ -0,0 +1,19 @@ +# Overview + +Dotkernel component to build complex routes, based on [mezzio/mezzio-fastroute](https://github.com/mezzio/mezzio-fastroute). + +> dot-router is a wrapper on top of [mezzio/mezzio-fastroute](https://github.com/mezzio/mezzio-fastroute) + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-router) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-router/2.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-router)](https://github.com/dotkernel/dot-router/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-router)](https://github.com/dotkernel/dot-router/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-router)](https://github.com/dotkernel/dot-router/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-router)](https://github.com/dotkernel/dot-router/blob/2.0/LICENSE) + +[![Build Static](https://github.com/dotkernel/dot-router/actions/workflows/continuous-integration.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-router/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-router/graph/badge.svg?token=ubNnFctuDR)](https://codecov.io/gh/dotkernel/dot-router) +[![PHPStan](https://github.com/dotkernel/dot-router/actions/workflows/static-analysis.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-router/actions/workflows/static-analysis.yml) diff --git a/docs/book/v2/tutorials/create-route-group.md b/docs/book/v2/tutorials/create-route-group.md new file mode 100644 index 0000000..4380ef1 --- /dev/null +++ b/docs/book/v2/tutorials/create-route-group.md @@ -0,0 +1,186 @@ +# Creating route groups + +> Following this tutorial assumes that you already completed the [installation](../installation.md) and [configuration](../configuration.md) steps. + +## Access the RouteCollector + +Get an instance of the `Dot\Router\RouteCollector` using the below code: + +```php +/** @var \Dot\Router\RouteCollectorInterface $routeCollector */ +$routeCollector = $container->get(\Dot\Router\RouteCollectorInterface::class); +``` + +### Create a route group + +Create a route group by setting the route group prefix and optionally a(n array of) common middleware(s): + +```php +$routeCollector->group('/resource', SomeMiddleware::class); +``` + +`group` method arguments: + +- **prefix**: required, a string that will be prepended to each route from the group; do not end it with `/` +- **middleware**: optional, (array of) request middleware(s) to execute before the handler of every route in the group, including closures and other callables + +Each call to `group()` returns a new group. +Create groups this way rather than fetching `Dot\Router\RouteGroupCollectorInterface` from the container: the container returns the same shared instance every time, so its prefix and middleware would leak between modules. + +### Which middleware is excluded + +`$excludeMiddleware` removes group middleware only; the route's own middleware and handler always run. +A group middleware given as a class name is excluded when that exact name is listed. +A group middleware given as an object is excluded when it is an instance of a listed class or interface. + +### Append a route that matches specific request methods + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->route('/manage', ResourceHandler::class, 'route-name', ['GET', 'POST']); +``` + +If this route does not need to be piped through specific middleware(s), you can use the fifth argument, `$excludeMiddleware`, to exclude those group middlewares at route level (makes sense when there are multiple routes in a group): + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->route('/manage', ResourceHandler::class, 'route-name', ['GET', 'POST'], excludeMiddleware: SomeMiddleware::class); +``` + +`route()` method arguments: + +- **path**: required, of type string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: (optional) if omitted, it will be set using the pattern **route path**^METHOD1:METHOD2 +- **methods**: (optional) if omitted, the route will respond to all request methods (equivalent of `any()`) +- **excludeMiddleware**: (optional) class name, or list of class names, of group middleware to skip for this route + +### Append a route that matches any request method + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->any('/manage', ResourceHandler::class, 'route-name'); +``` + +If this route does not need to be piped through specific middleware(s), you can use the fourth argument, `$excludeMiddleware`, to exclude those group middlewares at route level (makes sense when there are multiple routes in a group): + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->any('/manage', ResourceHandler::class, 'route-name', excludeMiddleware: SomeMiddleware::class); +``` + +`any()` method arguments: + +- **path**: required, of type string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set to the value of the **route path** +- **excludeMiddleware**: optional, class name, or list of class names, of group middleware to skip for this route + +### Append a route that matches **DELETE** requests + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->delete('/{id}', ResourceHandler::class, 'route-name'); +``` + +If this route does not need to be piped through specific middleware(s), you can use the fourth argument, `$excludeMiddleware`, to exclude those group middlewares at route level (makes sense when there are multiple routes in a group): + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->delete('/{id}', ResourceHandler::class, 'route-name', excludeMiddleware: SomeMiddleware::class); +``` + +`delete()` method arguments: + +- **path**: required, of type string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set using the pattern **route path**^DELETE +- **excludeMiddleware**: optional, class name, or list of class names, of group middleware to skip for this route + +### Append a route that matches **GET** requests + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->get('/{id}', ResourceHandler::class, 'route-name'); +``` + +If this route does not need to be piped through specific middleware(s), you can use the fourth argument, `$excludeMiddleware`, to exclude those group middlewares at route level (makes sense when there are multiple routes in a group): + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->get('/{id}', ResourceHandler::class, 'route-name', excludeMiddleware: SomeMiddleware::class); +``` + +`get()` method arguments: + +- **path**: required, of type string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set using the pattern **route path**^GET +- **excludeMiddleware**: optional, class name, or list of class names, of group middleware to skip for this route + +### Append a route that matches **PATCH** requests + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->patch('/{id}', ResourceHandler::class, 'route-name'); +``` + +If this route does not need to be piped through specific middleware(s), you can use the fourth argument, `$excludeMiddleware`, to exclude those group middlewares at route level (makes sense when there are multiple routes in a group): + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->patch('/{id}', ResourceHandler::class, 'route-name', excludeMiddleware: SomeMiddleware::class); +``` + +`patch()` method arguments: + +- **path**: required, of type string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set using the pattern **route path**^PATCH +- **excludeMiddleware**: optional, class name, or list of class names, of group middleware to skip for this route + +### Append a route that matches **POST** requests + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->post('', ResourceHandler::class, 'route-name'); +``` + +If this route does not need to be piped through specific middleware(s), you can use the fourth argument, `$excludeMiddleware`, to exclude those group middlewares at route level (makes sense when there are multiple routes in a group): + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->post('', ResourceHandler::class, 'route-name', excludeMiddleware: SomeMiddleware::class); +``` + +`post()` method arguments: + +- **path**: required, of type string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set using the pattern **route path**^POST +- **excludeMiddleware**: optional, class name, or list of class names, of group middleware to skip for this route + +### Append a route that matches **PUT** requests + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->put('/{id}', ResourceHandler::class, 'route-name'); +``` + +If this route does not need to be piped through specific middleware(s), you can use the fourth argument, `$excludeMiddleware`, to exclude those group middlewares at route level (makes sense when there are multiple routes in a group): + +```php +$routeCollector->group('/resource', [SomeMiddleware::class, OtherMiddleware::class]) + ->put('/{id}', ResourceHandler::class, 'route-name', excludeMiddleware: SomeMiddleware::class); +``` + +`put()` method arguments: + +- **path**: required, of type string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set using the pattern **route path**^PUT +- **excludeMiddleware**: optional, class name, or list of class names, of group middleware to skip for this route + +## List the registered routes + +`getRoutes()` on a group returns every route registered in the application's route collector, not only the routes of that group. diff --git a/docs/book/v2/tutorials/create-single-route.md b/docs/book/v2/tutorials/create-single-route.md new file mode 100644 index 0000000..0c78311 --- /dev/null +++ b/docs/book/v2/tutorials/create-single-route.md @@ -0,0 +1,112 @@ +# Creating a single route + +> Following this tutorial assumes that you already completed the [installation](../installation.md) and [configuration](../configuration.md) steps. + +## Access the RouteCollector + +Get an instance of the `Dot\Router\RouteCollector` using the below code: + +```php +/** @var \Dot\Router\RouteCollectorInterface $routeCollector */ +$routeCollector = $container->get(\Dot\Router\RouteCollectorInterface::class); +``` + +### Create a route that matches specific request methods + +```php +$routeCollector->route('/resource/manage', SomeHandler::class, 'route-name', ['GET', 'POST']); +``` + +`route()` method arguments: + +- **path**: required, a non-empty string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: (optional) if omitted, it will be set using the pattern **route path**^METHOD1:METHOD2 +- **methods**: (optional) if omitted, the route will respond to all request methods + +### Create a route that matches any request method + +```php +$routeCollector->any('/resource/manage', SomeHandler::class, 'route-name'); +``` + +`any()` method arguments: + +- **path**: required, a non-empty string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set to the value of the **route path** + +### Create a route that matches **DELETE** requests + +```php +$routeCollector->delete('/resource/{id}', SomeHandler::class, 'route-name'); +``` + +`delete()` method arguments: + +- **path**: required, a non-empty string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set using the pattern **route path**^DELETE + +### Create a route that matches **GET** requests + +```php +$routeCollector->get('/resource/{id}', SomeHandler::class, 'route-name'); +``` + +`get()` method arguments: + +- **path**: required, a non-empty string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set using the pattern **route path**^GET + +### Create a route that matches **PATCH** requests + +```php +$routeCollector->patch('/resource/{id}', SomeHandler::class, 'route-name'); +``` + +`patch()` method arguments: + +- **path**: required, a non-empty string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set using the pattern **route path**^PATCH + +### Create a route that matches **POST** requests + +```php +$routeCollector->post('/resource', SomeHandler::class, 'route-name'); +``` + +`post()` method arguments: + +- **path**: required, a non-empty string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set using the pattern **route path**^POST + +### Create a route that matches **PUT** requests + +```php +$routeCollector->put('/resource/{id}', SomeHandler::class, 'route-name'); +``` + +`put()` method arguments: + +- **path**: required, a non-empty string +- **middleware**: required, (array of) request handler(s)/middleware(s) +- **name**: optional, if omitted, it will be set using the pattern **route path**^PUT + +## Chain routes to the RouteCollector + +To facilitate creating routes, each `$routeCollector` method returns the existing `RouteCollector` instance, so you can chain routes like this: + +```php +$routeCollector + ->route('/product', SomeHandler::class, 'app::product', ['GET', 'POST']) + ->any('/category', SomeHandler::class, 'app::category') + ->delete('/order/{id}', SomeHandler::class, 'app::delete-order') + ->get('/order/{id}', SomeHandler::class, 'app::view-order') + ->patch('/order/{id}', SomeHandler::class, 'app::update-order') + ->post('/order', SomeHandler::class, 'app::create-order') + ->put('/order/{id}', SomeHandler::class, 'app::replace-order'); +``` diff --git a/docs/book/v2/upgrading.md b/docs/book/v2/upgrading.md new file mode 100644 index 0000000..9882002 --- /dev/null +++ b/docs/book/v2/upgrading.md @@ -0,0 +1,53 @@ +# Upgrading from version 1 to version 2 + +Version 2 drops PHP 8.2, fixes how group middleware is applied, and makes the middleware container follow PSR-11. +Most applications only need to update PHP and run `composer update`; read the table below if your routes use groups with closures or `$excludeMiddleware`. + +## Update the package + +```shell +composer require dotkernel/dot-router:^2.0 +``` + +## Changes that can break your code + +| Change | Symptom | Fix | +| --- | --- | --- | +| PHP 8.2 support removed | Composer refuses to install version 2 | Use PHP 8.3 or newer, or stay on version 1 | +| `mezzio/mezzio-fastroute` minimum is `^3.15` | Composer reports a conflict with an older FastRoute version | Update `mezzio/mezzio-fastroute` | +| Callable route handlers in a group now run the group middleware | A closure route inside a group now runs, for example, the group's authentication middleware | This is usually what you want. To keep the old behaviour, list the group middleware in that route's `$excludeMiddleware` | +| `$excludeMiddleware` removes group middleware only | Listing the route's own handler or middleware class no longer removes it from the route | Remove the class from the route's middleware list instead | +| `$excludeMiddleware` matches middleware objects by class | A group middleware passed as an object is now excluded by its class name; excluding `MiddlewareInterface::class` removes every group middleware object, but never the route handler | Check routes that exclude interface names | +| `MiddlewareContainer::get()` throws `MissingMiddlewareException` or `InvalidMiddlewareException` | Code that compares the exception class with `Exception::class` no longer matches | Catch `Psr\Container\ContainerExceptionInterface`; both new classes extend `RuntimeException`, so `catch (Exception $e)` still works | +| An unregistered middleware class with required constructor arguments throws `InvalidMiddlewareException` | The error was an `ArgumentCountError` | Register the middleware in the container | +| `MiddlewareFactory::pipeline()` and `prepare([])` reject an empty list | `Dot\Router\Exception\InvalidArgumentException` when routes are registered; version 1 raised a PHP warning and registered a route that did nothing | Pass at least one middleware or handler | +| A group route with an empty prefix and an empty path is rejected | `Dot\Router\Exception\InvalidArgumentException` | Set a prefix or a path | +| Stricter PHPDoc types (`non-empty-string` paths and names, `list` methods) | Static analysis of your code reports new errors on route calls | Pass non-empty literals, or narrow your variables before the call | + +## Group middleware with closures + +Before, the closure route skipped `AuthMiddleware`: + +```php +$routeCollector->group('/admin', AuthMiddleware::class) + ->get('/status', fn ($request, $handler) => new JsonResponse(['ok' => true]), 'admin:status'); +``` + +After, `AuthMiddleware` runs first for `/admin/status`, as it does for every other route in the group. +To keep the route public, exclude the middleware: + +```php +$routeCollector->group('/admin', AuthMiddleware::class) + ->get('/status', fn ($request, $handler) => new JsonResponse(['ok' => true]), 'admin:status', AuthMiddleware::class); +``` + +## Excluding middleware objects + +Before, a group middleware passed as an object could not be excluded by its class name: + +```php +$routeCollector->group('/product', new CheckOwnerMiddleware($repository)) + ->post('/create', CreateProductHandler::class, 'product:create', CheckOwnerMiddleware::class); +// version 1: CheckOwnerMiddleware still ran +// version 2: CheckOwnerMiddleware is skipped for product:create +``` diff --git a/docs/book/v2/usage.md b/docs/book/v2/usage.md new file mode 100644 index 0000000..25825c1 --- /dev/null +++ b/docs/book/v2/usage.md @@ -0,0 +1,13 @@ +# Usage + +Register routes in your application using your preferred method: + +- in `config/routes.php` +- per-module, using a `RoutesDelegator` + +Both methods will provide access to the application's container via the `$container` variable. + +There are two types of routes that you can create: + +- [create a single route](./tutorials/create-single-route.md) +- [create a route group](./tutorials/create-route-group.md) diff --git a/mkdocs.yml b/mkdocs.yml index 7566dd1..8813243 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,11 +2,22 @@ docs_dir: docs/book site_dir: docs/html extra: project: Packages - current_version: v1 + current_version: v2 versions: + - v2 - v1 nav: - Home: index.md + - v2: + - Overview: v2/overview.md + - Installation: v2/installation.md + - Configuration: v2/configuration.md + - Features: v2/features.md + - Usage: v2/usage.md + - Tutorials: + - "Creating a single route": v2/tutorials/create-single-route.md + - "Creating route groups": v2/tutorials/create-route-group.md + - "Upgrading from v1": v2/upgrading.md - v1: - Overview: v1/overview.md - Installation: v1/installation.md diff --git a/phpstan.neon b/phpstan.neon index 349be25..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,7 +1,7 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test diff --git a/phpunit.xml b/phpunit.xml index 4a1bf00..7228fe4 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,17 +1,26 @@ + xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" + bootstrap="vendor/autoload.php" + cacheDirectory=".phpunit.cache" + colors="true" + failOnDeprecation="true" + failOnNotice="true" + failOnWarning="true" + failOnRisky="true" + failOnPhpunitDeprecation="true" + displayDetailsOnTestsThatTriggerDeprecations="true" + displayDetailsOnTestsThatTriggerNotices="true" + displayDetailsOnTestsThatTriggerWarnings="true" + displayDetailsOnPhpunitDeprecations="true"> - - ./test + + test - - + - ./src + src diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 83e0fd8..1e5983c 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -11,6 +11,11 @@ class ConfigProvider { + /** + * @return array{ + * dependencies: array{aliases: array, factories: array} + * } + */ public function __invoke(): array { return [ @@ -18,6 +23,9 @@ public function __invoke(): array ]; } + /** + * @return array{aliases: array, factories: array} + */ public function getDependencyConfig(): array { return [ diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..45e4321 --- /dev/null +++ b/src/Exception/InvalidArgumentException.php @@ -0,0 +1,18 @@ +has(\Mezzio\Router\RouteCollectorInterface::class)) { - throw new RuntimeException('Could not find "Mezzio\Router\RouteCollectorInterface" in container'); + if (! $container->has(MezzioRouteCollectorInterface::class)) { + throw new RuntimeException( + sprintf('Could not find "%s" in container', MezzioRouteCollectorInterface::class) + ); } - $routeCollector = $container->get(\Mezzio\Router\RouteCollectorInterface::class); + $routeCollector = $container->get(MezzioRouteCollectorInterface::class); $middlewareFactory = $container->get(MiddlewareFactory::class); return new RouteCollector($routeCollector, $middlewareFactory); diff --git a/src/Factory/RouteGroupCollectorFactory.php b/src/Factory/RouteGroupCollectorFactory.php index 4522722..546d9d8 100644 --- a/src/Factory/RouteGroupCollectorFactory.php +++ b/src/Factory/RouteGroupCollectorFactory.php @@ -7,27 +7,30 @@ use Dot\Router\MiddlewareFactory; use Dot\Router\RouteGroupCollector; use Dot\Router\RouteGroupCollectorInterface; -use Exception; -use Mezzio\Router\RouteCollectorInterface; +use Mezzio\Router\RouteCollectorInterface as MezzioRouteCollectorInterface; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; use RuntimeException; +use function sprintf; + class RouteGroupCollectorFactory { /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Exception + * @throws RuntimeException */ public function __invoke(ContainerInterface $container): RouteGroupCollectorInterface { - if (! $container->has(RouteCollectorInterface::class)) { - throw new RuntimeException('Could not find "Mezzio\Router\RouteCollectorInterface" in container'); + if (! $container->has(MezzioRouteCollectorInterface::class)) { + throw new RuntimeException( + sprintf('Could not find "%s" in container', MezzioRouteCollectorInterface::class) + ); } - $routeCollector = $container->get(RouteCollectorInterface::class); + $routeCollector = $container->get(MezzioRouteCollectorInterface::class); $middlewareFactory = $container->get(MiddlewareFactory::class); return new RouteGroupCollector($routeCollector, $middlewareFactory); diff --git a/src/MiddlewareContainer.php b/src/MiddlewareContainer.php index 8ec35b6..8c780ee 100644 --- a/src/MiddlewareContainer.php +++ b/src/MiddlewareContainer.php @@ -4,7 +4,9 @@ namespace Dot\Router; -use Exception; +use ArgumentCountError; +use Dot\Router\Exception\InvalidMiddlewareException; +use Dot\Router\Exception\MissingMiddlewareException; use Laminas\Stratigility\Middleware\RequestHandlerMiddleware; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; @@ -13,9 +15,6 @@ use Psr\Http\Server\RequestHandlerInterface; use function class_exists; -use function gettype; -use function is_object; -use function sprintf; class MiddlewareContainer implements ContainerInterface { @@ -34,32 +33,33 @@ public function has(string $id): bool } /** + * @throws MissingMiddlewareException + * @throws InvalidMiddlewareException * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function get(string $id): MiddlewareInterface { if (! $this->has($id)) { - throw new Exception(sprintf( - 'Cannot fetch middleware service "%s"; service not registered,' - . ' or does not resolve to an autoloadable class name', - $id - )); + throw MissingMiddlewareException::forService($id); + } + + if ($this->container->has($id)) { + $middleware = $this->container->get($id); + } else { + try { + $middleware = new $id(); + } catch (ArgumentCountError $exception) { + throw InvalidMiddlewareException::notInstantiable($id, $exception); + } } - $middleware = $this->container->has($id) ? $this->container->get($id) : new $id(); if ($middleware instanceof RequestHandlerInterface && ! $middleware instanceof MiddlewareInterface) { $middleware = new RequestHandlerMiddleware($middleware); } if (! $middleware instanceof MiddlewareInterface) { - throw new Exception(sprintf( - 'Service "%s" did not to resolve to a %s instance; resolved to "%s"', - $id, - MiddlewareInterface::class, - is_object($middleware) ? $middleware::class : gettype($middleware) - )); + throw InvalidMiddlewareException::forService($id, $middleware); } return $middleware; diff --git a/src/MiddlewareFactory.php b/src/MiddlewareFactory.php index 3d8baee..667defb 100644 --- a/src/MiddlewareFactory.php +++ b/src/MiddlewareFactory.php @@ -4,6 +4,7 @@ namespace Dot\Router; +use Dot\Router\Exception\InvalidArgumentException; use Dot\Router\Middleware\LazyLoadingMiddleware; use Laminas\Stratigility\Middleware\CallableMiddlewareDecorator; use Laminas\Stratigility\Middleware\RequestHandlerMiddleware; @@ -11,11 +12,14 @@ use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; -use function array_shift; use function count; use function is_array; use function is_callable; +/** + * @phpstan-import-type MiddlewareItem from RouteCollectorInterface + * @phpstan-import-type MiddlewareSpec from RouteCollectorInterface + */ class MiddlewareFactory { public function __construct( @@ -23,6 +27,10 @@ public function __construct( ) { } + /** + * @param MiddlewareSpec $middleware + * @throws InvalidArgumentException When given an empty list. + */ public function prepare( string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware ): MiddlewareInterface { @@ -39,12 +47,25 @@ public function prepare( } if (is_array($middleware)) { - return $this->pipeline(...$middleware); + return $this->pipeline($middleware); } return $this->lazy($middleware); } + /** + * True for an array of middleware; false for a callable array such as [$object, 'method']. + * + * @internal + * + * @param MiddlewareSpec|null $middleware + * @phpstan-assert-if-true list $middleware + */ + public static function isMiddlewareList(mixed $middleware): bool + { + return is_array($middleware) && ! is_callable($middleware); + } + public function callable(callable $middleware): CallableMiddlewareDecorator { return new CallableMiddlewareDecorator($middleware); @@ -61,17 +82,25 @@ public function lazy(string $middleware): LazyLoadingMiddleware } /** - * @param string|array|callable|MiddlewareInterface|RequestHandlerInterface ...$middleware + * Accepts either several middleware arguments, or a single list of middleware. + * + * @param MiddlewareSpec ...$middleware + * @throws InvalidArgumentException When given an empty list. */ - public function pipeline(...$middleware): MiddlewarePipe - { - if (is_array($middleware[0]) && count($middleware) === 1) { - $middleware = array_shift($middleware); + public function pipeline( + string|array|callable|MiddlewareInterface|RequestHandlerInterface ...$middleware + ): MiddlewarePipe { + if (count($middleware) === 1 && isset($middleware[0]) && self::isMiddlewareList($middleware[0])) { + $middleware = $middleware[0]; + } + + if ($middleware === []) { + throw InvalidArgumentException::emptyPipeline(); } $pipeline = new MiddlewarePipe(); - foreach ($middleware as $m) { - $pipeline->pipe($this->prepare($m)); + foreach ($middleware as $item) { + $pipeline->pipe($this->prepare($item)); } return $pipeline; diff --git a/src/RouteCollector.php b/src/RouteCollector.php index 4130385..83ef446 100644 --- a/src/RouteCollector.php +++ b/src/RouteCollector.php @@ -9,6 +9,9 @@ use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; +/** + * @phpstan-import-type MiddlewareSpec from RouteCollectorInterface + */ class RouteCollector implements RouteCollectorInterface { public function __construct( @@ -17,6 +20,9 @@ public function __construct( ) { } + /** + * @param MiddlewareSpec|null $middleware + */ public function group( string $prefix, null|string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware = null, @@ -26,6 +32,12 @@ public function group( ->setMiddleware($middleware); } + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param list|null $methods + */ public function route( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -37,6 +49,11 @@ public function route( return $this; } + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function any( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -47,6 +64,11 @@ public function any( return $this; } + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function delete( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -61,6 +83,11 @@ public function delete( return $this; } + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function get( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -75,6 +102,11 @@ public function get( return $this; } + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function patch( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -89,6 +121,11 @@ public function patch( return $this; } + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function post( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -103,6 +140,11 @@ public function post( return $this; } + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function put( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, diff --git a/src/RouteCollectorInterface.php b/src/RouteCollectorInterface.php index e863f11..cdaee92 100644 --- a/src/RouteCollectorInterface.php +++ b/src/RouteCollectorInterface.php @@ -8,13 +8,26 @@ use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; +/** + * @phpstan-type MiddlewareItem string|callable|MiddlewareInterface|RequestHandlerInterface + * @phpstan-type MiddlewareSpec MiddlewareItem|list + */ interface RouteCollectorInterface { + /** + * @param MiddlewareSpec|null $middleware + */ public function group( string $prefix, null|string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware = null, ): RouteGroupCollectorInterface; + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param list|null $methods + */ public function route( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -22,36 +35,66 @@ public function route( ?array $methods = null, ): RouteCollectorInterface; + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function any( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, ?string $name = null, ): RouteCollectorInterface; + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function delete( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, ?string $name = null, ): RouteCollectorInterface; + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function get( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, ?string $name = null, ): RouteCollectorInterface; + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function patch( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, ?string $name = null, ): RouteCollectorInterface; + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function post( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, ?string $name = null, ): RouteCollectorInterface; + /** + * @param non-empty-string $path + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + */ public function put( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, diff --git a/src/RouteGroupCollector.php b/src/RouteGroupCollector.php index db1f3c3..cf6dd7c 100644 --- a/src/RouteGroupCollector.php +++ b/src/RouteGroupCollector.php @@ -4,28 +4,32 @@ namespace Dot\Router; +use Dot\Router\Exception\InvalidArgumentException; use Mezzio\Router\Route; use Mezzio\Router\RouteCollectorInterface as MezzioRouteCollectorInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use function array_filter; -use function array_merge; +use function array_values; use function in_array; -use function is_array; -use function is_callable; +use function is_object; use function is_string; -use function sprintf; +/** + * @phpstan-import-type MiddlewareSpec from RouteCollectorInterface + */ class RouteGroupCollector implements RouteGroupCollectorInterface { protected string $prefix = ''; + /** @var MiddlewareSpec|null */ protected mixed $middleware; public function __construct( private readonly MezzioRouteCollectorInterface $routeCollector, private readonly MiddlewareFactory $middlewareFactory, ) { + $this->middleware = null; } public function getPrefix(): string @@ -40,11 +44,17 @@ public function setPrefix(string $prefix): self return $this; } + /** + * @return MiddlewareSpec|null + */ public function getMiddleware(): mixed { return $this->middleware; } + /** + * @param MiddlewareSpec|null $middleware + */ public function setMiddleware( null|string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware ): self { @@ -53,6 +63,12 @@ public function setMiddleware( return $this; } + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param list|null $methods + * @param class-string|list $excludeMiddleware + */ public function route( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -70,6 +86,11 @@ public function route( return $this; } + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function any( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -85,6 +106,11 @@ public function any( return $this; } + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function delete( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -100,6 +126,11 @@ public function delete( return $this; } + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function get( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -115,6 +146,11 @@ public function get( return $this; } + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function patch( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -130,6 +166,11 @@ public function patch( return $this; } + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function post( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -145,6 +186,11 @@ public function post( return $this; } + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function put( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -168,55 +214,67 @@ public function getRoutes(): array return $this->routeCollector->getRoutes(); } + /** + * @return non-empty-string + * @throws InvalidArgumentException When both the prefix and the path are empty. + */ private function preparePath(string $path): string { - return sprintf('%s%s', $this->prefix, $path); + $path = $this->prefix . $path; + if ($path === '') { + throw InvalidArgumentException::emptyPath(); + } + + return $path; } /** + * Group middleware runs first, minus any listed in $excludeMiddleware, then the route's own middleware. + * + * @param MiddlewareSpec $middleware * @param class-string|list $excludeMiddleware */ private function prepareMiddleware( string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, array|string $excludeMiddleware = [], ): MiddlewareInterface { - if (is_string($excludeMiddleware)) { - $excludeMiddleware = [$excludeMiddleware]; - } + $exclude = is_string($excludeMiddleware) ? [$excludeMiddleware] : $excludeMiddleware; + + $groupMiddleware = match (true) { + $this->middleware === null => [], + MiddlewareFactory::isMiddlewareList($this->middleware) => $this->middleware, + default => [$this->middleware], + }; + $groupMiddleware = array_filter( + $groupMiddleware, + fn (mixed $item): bool => ! $this->isExcluded($item, $exclude) + ); - $prependMiddleware = []; - if ($this->middleware !== null) { - $prependMiddleware = $this->middleware; - if (! is_array($prependMiddleware)) { - $prependMiddleware = [$prependMiddleware]; - } - } + $routeMiddleware = MiddlewareFactory::isMiddlewareList($middleware) ? $middleware : [$middleware]; - if (is_callable($middleware)) { - return $this->middlewareFactory->prepare($middleware); - } + return $this->middlewareFactory->prepare([ + ...array_values($groupMiddleware), + ...$routeMiddleware, + ]); + } - if (! is_array($middleware)) { - $middleware = [$middleware]; + /** + * @param list $exclude + */ + private function isExcluded(mixed $item, array $exclude): bool + { + if (is_string($item)) { + return in_array($item, $exclude, true); } - $middleware = array_merge($prependMiddleware, $middleware); - $middleware = array_filter( - $middleware, - function (callable|string|MiddlewareInterface|RequestHandlerInterface $item) use ($excludeMiddleware) { - if (is_callable($item)) { + if (is_object($item)) { + foreach ($exclude as $class) { + if ($item instanceof $class) { return true; } - if ($item instanceof RequestHandlerInterface) { - $item = RequestHandlerInterface::class; - } - if ($item instanceof MiddlewareInterface) { - $item = MiddlewareInterface::class; - } - return ! in_array($item, $excludeMiddleware, true); } - ); + } - return $this->middlewareFactory->prepare($middleware); + return false; } } diff --git a/src/RouteGroupCollectorInterface.php b/src/RouteGroupCollectorInterface.php index e075e72..45c1895 100644 --- a/src/RouteGroupCollectorInterface.php +++ b/src/RouteGroupCollectorInterface.php @@ -8,18 +8,35 @@ use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; +/** + * @phpstan-import-type MiddlewareSpec from RouteCollectorInterface + */ interface RouteGroupCollectorInterface { public function getPrefix(): string; public function setPrefix(string $prefix): self; + /** + * @return MiddlewareSpec|null + */ public function getMiddleware(): mixed; + /** + * @param MiddlewareSpec|null $middleware + */ public function setMiddleware( null|string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware ): self; + /** + * Group middleware listed in $excludeMiddleware is not run for this route. + * + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param list|null $methods + * @param class-string|list $excludeMiddleware + */ public function route( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -28,6 +45,11 @@ public function route( array|string $excludeMiddleware = [], ): RouteGroupCollectorInterface; + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function any( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -35,6 +57,11 @@ public function any( array|string $excludeMiddleware = [], ): RouteGroupCollectorInterface; + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function delete( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -42,6 +69,11 @@ public function delete( array|string $excludeMiddleware = [], ): RouteGroupCollectorInterface; + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function get( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -49,6 +81,11 @@ public function get( array|string $excludeMiddleware = [], ): RouteGroupCollectorInterface; + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function patch( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -56,6 +93,11 @@ public function patch( array|string $excludeMiddleware = [], ): RouteGroupCollectorInterface; + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function post( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -63,6 +105,11 @@ public function post( array|string $excludeMiddleware = [], ): RouteGroupCollectorInterface; + /** + * @param MiddlewareSpec $middleware + * @param non-empty-string|null $name + * @param class-string|list $excludeMiddleware + */ public function put( string $path, string|array|callable|MiddlewareInterface|RequestHandlerInterface $middleware, @@ -71,6 +118,8 @@ public function put( ): RouteGroupCollectorInterface; /** + * Returns every route in the underlying Mezzio route collector, not only this group's routes. + * * @return list */ public function getRoutes(): array; diff --git a/test/AbstractRouterTestCase.php b/test/AbstractRouterTestCase.php new file mode 100644 index 0000000..fc60f99 --- /dev/null +++ b/test/AbstractRouterTestCase.php @@ -0,0 +1,60 @@ +container = new InMemoryContainer(); + $this->middlewareFactory = new MiddlewareFactory(new MiddlewareContainer($this->container)); + $this->mezzioCollector = new MezzioRouteCollector($this->createStub(RouterInterface::class)); + $this->request = $this->createStub(ServerRequestInterface::class); + CallLog::reset($this->createStub(ResponseInterface::class)); + } + + /** + * @return list + */ + protected function runRoute(Route $route): array + { + $route->getMiddleware()->process($this->request, new FallbackHandler()); + + return CallLog::calls(); + } + + protected function routeNamed(string $name): Route + { + foreach ($this->mezzioCollector->getRoutes() as $route) { + if ($route->getName() === $name) { + return $route; + } + } + + $this->fail(sprintf('Route "%s" was not registered', $name)); + } +} diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index 55c4081..617e80a 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -17,11 +17,12 @@ use Dot\Router\RouteGroupCollectorInterface; use PHPUnit\Framework\TestCase; -class ConfigProviderTest extends TestCase +final class ConfigProviderTest extends TestCase { - protected array $config; + /** @var array{dependencies: array{aliases: array, factories: array}} */ + private array $config; - protected function setup(): void + protected function setUp(): void { $this->config = (new ConfigProvider())(); } diff --git a/test/Factory/FactoryTest.php b/test/Factory/FactoryTest.php new file mode 100644 index 0000000..84fd05b --- /dev/null +++ b/test/Factory/FactoryTest.php @@ -0,0 +1,92 @@ +container = new InMemoryContainer(); + $middlewareContainer = (new MiddlewareContainerFactory())($this->container); + $this->container->set(MiddlewareContainer::class, $middlewareContainer); + $this->container->set(MiddlewareFactory::class, (new MiddlewareFactoryFactory())($this->container)); + } + + public function testMiddlewareContainerFactory(): void + { + $this->assertInstanceOf(MiddlewareContainer::class, $this->container->get(MiddlewareContainer::class)); + } + + public function testMiddlewareFactoryFactory(): void + { + $this->assertInstanceOf(MiddlewareFactory::class, $this->container->get(MiddlewareFactory::class)); + } + + public function testRouteCollectorFactory(): void + { + $this->registerMezzioCollector(); + + $this->assertInstanceOf(RouteCollector::class, (new RouteCollectorFactory())($this->container)); + } + + public function testRouteGroupCollectorFactory(): void + { + $this->registerMezzioCollector(); + + $group = (new RouteGroupCollectorFactory())($this->container); + + $this->assertInstanceOf(RouteGroupCollector::class, $group); + $this->assertNull($group->getMiddleware()); + } + + /** + * @param class-string $factory + */ + #[DataProvider('collectorFactoryProvider')] + public function testCollectorFactoryRequiresMezzioRouteCollector(string $factory): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(MezzioRouteCollectorInterface::class); + + (new $factory())($this->container); + } + + /** + * @return array}> + */ + public static function collectorFactoryProvider(): array + { + return [ + 'RouteCollectorFactory' => ['factory' => RouteCollectorFactory::class], + 'RouteGroupCollectorFactory' => ['factory' => RouteGroupCollectorFactory::class], + ]; + } + + private function registerMezzioCollector(): void + { + $this->container->set( + MezzioRouteCollectorInterface::class, + new MezzioRouteCollector($this->createStub(RouterInterface::class)) + ); + } +} diff --git a/test/Fixture/CallLog.php b/test/Fixture/CallLog.php new file mode 100644 index 0000000..b489857 --- /dev/null +++ b/test/Fixture/CallLog.php @@ -0,0 +1,49 @@ + */ + private static array $calls = []; + + private static ?ResponseInterface $response = null; + + public static function reset(ResponseInterface $response): void + { + self::$calls = []; + self::$response = $response; + } + + public static function record(string $name): void + { + self::$calls[] = $name; + } + + /** + * @return list + */ + public static function calls(): array + { + return self::$calls; + } + + public static function response(): ResponseInterface + { + if (self::$response === null) { + throw new RuntimeException('Call CallLog::reset() in setUp() first'); + } + + return self::$response; + } +} diff --git a/test/Fixture/FallbackHandler.php b/test/Fixture/FallbackHandler.php new file mode 100644 index 0000000..64dda2b --- /dev/null +++ b/test/Fixture/FallbackHandler.php @@ -0,0 +1,22 @@ +handle($request); + } +} diff --git a/test/Fixture/InMemoryContainer.php b/test/Fixture/InMemoryContainer.php new file mode 100644 index 0000000..99f3d47 --- /dev/null +++ b/test/Fixture/InMemoryContainer.php @@ -0,0 +1,39 @@ + $services + */ + public function __construct( + private array $services = [], + ) { + } + + public function set(string $id, mixed $service): void + { + $this->services[$id] = $service; + } + + public function get(string $id): mixed + { + if (! array_key_exists($id, $this->services)) { + throw ServiceNotFoundException::forService($id); + } + + return $this->services[$id]; + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services); + } +} diff --git a/test/Fixture/MiddlewareWithArgument.php b/test/Fixture/MiddlewareWithArgument.php new file mode 100644 index 0000000..ed0f61f --- /dev/null +++ b/test/Fixture/MiddlewareWithArgument.php @@ -0,0 +1,25 @@ +name); + + return $handler->handle($request); + } +} diff --git a/test/Fixture/SecondMiddleware.php b/test/Fixture/SecondMiddleware.php new file mode 100644 index 0000000..aa6b38f --- /dev/null +++ b/test/Fixture/SecondMiddleware.php @@ -0,0 +1,20 @@ +handle($request); + } +} diff --git a/test/Fixture/ServiceNotFoundException.php b/test/Fixture/ServiceNotFoundException.php new file mode 100644 index 0000000..926fcd4 --- /dev/null +++ b/test/Fixture/ServiceNotFoundException.php @@ -0,0 +1,18 @@ +container), 'lazy'); + $this->container->set('lazy', new MiddlewareWithArgument('resolved')); + + $this->assertSame(['resolved', FallbackHandler::class], $this->runRoute(new Route('/x', $middleware))); + } + + public function testExposesMiddlewareName(): void + { + $middleware = new LazyLoadingMiddleware(new MiddlewareContainer($this->container), FirstMiddleware::class); + + $this->assertSame(FirstMiddleware::class, $middleware->middlewareName); + } +} diff --git a/test/MiddlewareContainerTest.php b/test/MiddlewareContainerTest.php new file mode 100644 index 0000000..337094d --- /dev/null +++ b/test/MiddlewareContainerTest.php @@ -0,0 +1,91 @@ +services = new InMemoryContainer(); + $this->container = new MiddlewareContainer($this->services); + } + + public function testHasRegisteredService(): void + { + $this->services->set('my-middleware', new FirstMiddleware()); + + $this->assertTrue($this->container->has('my-middleware')); + } + + public function testHasAutoloadableClass(): void + { + $this->assertTrue($this->container->has(FirstMiddleware::class)); + } + + public function testDoesNotHaveUnknownId(): void + { + $this->assertFalse($this->container->has('Missing\\Middleware')); + } + + public function testGetReturnsRegisteredService(): void + { + $middleware = new MiddlewareWithArgument('registered'); + $this->services->set(MiddlewareWithArgument::class, $middleware); + + $this->assertSame($middleware, $this->container->get(MiddlewareWithArgument::class)); + } + + public function testGetInstantiatesUnregisteredClass(): void + { + $this->assertInstanceOf(FirstMiddleware::class, $this->container->get(FirstMiddleware::class)); + } + + public function testGetWrapsHandler(): void + { + $this->assertInstanceOf(RequestHandlerMiddleware::class, $this->container->get(TestHandler::class)); + } + + public function testGetThrowsNotFoundForUnknownService(): void + { + $this->expectException(NotFoundExceptionInterface::class); + $this->expectException(MissingMiddlewareException::class); + + $this->container->get('Missing\\Middleware'); + } + + public function testGetThrowsContainerExceptionForNonMiddleware(): void + { + $this->expectException(ContainerExceptionInterface::class); + $this->expectException(InvalidMiddlewareException::class); + $this->expectExceptionMessage('resolved to "stdClass"'); + + $this->container->get(stdClass::class); + } + + public function testGetThrowsContainerExceptionForClassWithRequiredArguments(): void + { + $this->expectException(ContainerExceptionInterface::class); + $this->expectException(InvalidMiddlewareException::class); + $this->expectExceptionMessage('register it in the container'); + + $this->container->get(MiddlewareWithArgument::class); + } +} diff --git a/test/MiddlewareFactoryTest.php b/test/MiddlewareFactoryTest.php new file mode 100644 index 0000000..11638ae --- /dev/null +++ b/test/MiddlewareFactoryTest.php @@ -0,0 +1,106 @@ +assertSame($middleware, $this->middlewareFactory->prepare($middleware)); + } + + public function testPrepareWrapsHandler(): void + { + $this->assertInstanceOf( + RequestHandlerMiddleware::class, + $this->middlewareFactory->prepare(new TestHandler()) + ); + } + + public function testPrepareDecoratesClosure(): void + { + $closure = static fn (ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + => $handler->handle($request); + + $this->assertInstanceOf(CallableMiddlewareDecorator::class, $this->middlewareFactory->prepare($closure)); + } + + public function testPrepareDecoratesCallableArray(): void + { + $this->assertInstanceOf( + CallableMiddlewareDecorator::class, + $this->middlewareFactory->prepare([new TestHandler(), 'handle']) + ); + } + + public function testPrepareMakesStringLazy(): void + { + $middleware = $this->middlewareFactory->prepare(FirstMiddleware::class); + + $this->assertInstanceOf(LazyLoadingMiddleware::class, $middleware); + $this->assertSame(FirstMiddleware::class, $middleware->middlewareName); + $this->assertSame([], CallLog::calls(), 'Lazy middleware must not run when prepared'); + } + + public function testPrepareBuildsPipelineFromList(): void + { + $middleware = $this->middlewareFactory->prepare([FirstMiddleware::class, TestHandler::class]); + + $this->assertInstanceOf(MiddlewarePipe::class, $middleware); + $this->assertSame([FirstMiddleware::class, TestHandler::class], $this->runMiddleware($middleware)); + } + + public function testPipelineAcceptsSeveralArguments(): void + { + $pipeline = $this->middlewareFactory->pipeline(FirstMiddleware::class, TestHandler::class); + + $this->assertSame([FirstMiddleware::class, TestHandler::class], $this->runMiddleware($pipeline)); + } + + public function testPipelineAcceptsASingleList(): void + { + $pipeline = $this->middlewareFactory->pipeline([FirstMiddleware::class, TestHandler::class]); + + $this->assertSame([FirstMiddleware::class, TestHandler::class], $this->runMiddleware($pipeline)); + } + + public function testPipelineRejectsEmptyList(): void + { + $this->expectException(InvalidArgumentException::class); + + $this->middlewareFactory->prepare([]); + } + + public function testPipelineRejectsNoArguments(): void + { + $this->expectException(InvalidArgumentException::class); + + $this->middlewareFactory->pipeline(); + } + + /** + * @return list + */ + private function runMiddleware(MiddlewareInterface $middleware): array + { + return $this->runRoute(new Route('/x', $middleware)); + } +} diff --git a/test/RouteCollectorTest.php b/test/RouteCollectorTest.php index c4f9b30..9b7fb64 100644 --- a/test/RouteCollectorTest.php +++ b/test/RouteCollectorTest.php @@ -4,224 +4,195 @@ namespace DotTest\Router; -use Dot\Router\MiddlewareFactory; use Dot\Router\RouteCollector; use Dot\Router\RouteGroupCollector; -use Mezzio\Router\RouterInterface; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\TestCase; -use Psr\Http\Server\MiddlewareInterface; -use Psr\Http\Server\RequestHandlerInterface; +use DotTest\Router\Fixture\FirstMiddleware; +use DotTest\Router\Fixture\SecondMiddleware; +use DotTest\Router\Fixture\TestHandler; +use PHPUnit\Framework\Attributes\DataProvider; -class RouteCollectorTest extends TestCase +use function strtoupper; + +final class RouteCollectorTest extends AbstractRouterTestCase { - protected RouteCollector $routeCollector; - protected RequestHandlerInterface $handler; + private RouteCollector $routeCollector; - /** - * @throws Exception - */ - protected function setup(): void + protected function setUp(): void { - $this->routeCollector = new RouteCollector( - new \Mezzio\Router\RouteCollector($this->createMock(RouterInterface::class)), - $this->createMock(MiddlewareFactory::class) - ); + parent::setUp(); + + $this->routeCollector = new RouteCollector($this->mezzioCollector, $this->middlewareFactory); } public function testWillCreateGroup(): void { - $group = $this->routeCollector->group('/group', MiddlewareInterface::class); + $group = $this->routeCollector->group('/group', FirstMiddleware::class); + $this->assertInstanceOf(RouteGroupCollector::class, $group); $this->assertSame('/group', $group->getPrefix()); - $this->assertSame(MiddlewareInterface::class, $group->getMiddleware()); + $this->assertSame(FirstMiddleware::class, $group->getMiddleware()); + } + + public function testGroupMiddlewareIsOptional(): void + { + $group = $this->routeCollector->group('/group'); + + $this->assertNull($group->getMiddleware()); + + $group->get('/x', TestHandler::class, 'x'); + $this->assertSame([TestHandler::class], $this->runRoute($this->routeNamed('x'))); + } + + public function testEachGroupIsANewInstance(): void + { + $first = $this->routeCollector->group('/first'); + $second = $this->routeCollector->group('/second'); + + $this->assertNotSame($first, $second); + $this->assertSame('/first', $first->getPrefix()); + } + + public function testRouteRunsMiddlewareInOrder(): void + { + $this->routeCollector->get( + '/x', + [FirstMiddleware::class, new SecondMiddleware(), TestHandler::class], + 'x' + ); + + $this->assertSame( + [FirstMiddleware::class, SecondMiddleware::class, TestHandler::class], + $this->runRoute($this->routeNamed('x')) + ); } /** - * @dataProvider routeProvider + * @param non-empty-string $routePath + * @param non-empty-string|null $routeName + * @param list|null $allowedMethods */ + #[DataProvider('routeProvider')] public function testWillCreateRoute( string $routePath, - ?string $routeName = null, - ?string $generatedPath = null, - ?string $generatedName = null, - ?array $allowedMethods = null, + ?string $routeName, + string $generatedPath, + string $generatedName, + ?array $allowedMethods, ): void { $this->assertCount(0, $this->routeCollector->getRoutes()); - $route = $this->routeCollector->route( - $routePath, - RequestHandlerInterface::class, - $routeName, - $allowedMethods - ); - $this->assertInstanceOf(RouteCollector::class, $route); - + $result = $this->routeCollector->route($routePath, TestHandler::class, $routeName, $allowedMethods); + $this->assertSame($this->routeCollector, $result); $this->assertCount(1, $this->routeCollector->getRoutes()); $route = $this->routeCollector->getRoutes()[0]; $this->assertSame($generatedPath, $route->getPath()); - $this->assertContainsOnlyInstancesOf(MiddlewareInterface::class, [$route->getMiddleware()]); $this->assertSame($generatedName, $route->getName()); $this->assertSame($allowedMethods, $route->getAllowedMethods()); + $this->assertSame([TestHandler::class], $this->runRoute($route)); } /** - * @dataProvider methodProvider + * @param 'any'|'delete'|'get'|'patch'|'post'|'put' $requestMethod + * @param non-empty-string $routePath + * @param non-empty-string|null $routeName + * @param list|null $allowedMethods */ + #[DataProvider('methodProvider')] public function testWillCreateRoutesByMethod( string $requestMethod, string $routePath, - ?string $routeName = null, - ?string $generatedPath = null, - ?string $generatedName = null, - ?array $allowedMethods = null, + ?string $routeName, + string $generatedPath, + string $generatedName, + ?array $allowedMethods, ): void { $this->assertCount(0, $this->routeCollector->getRoutes()); - $route = $this->routeCollector->$requestMethod( - $routePath, - RequestHandlerInterface::class, - $routeName, - ); - $this->assertInstanceOf(RouteCollector::class, $route); - + $result = $this->routeCollector->$requestMethod($routePath, TestHandler::class, $routeName); + $this->assertSame($this->routeCollector, $result); $this->assertCount(1, $this->routeCollector->getRoutes()); $route = $this->routeCollector->getRoutes()[0]; $this->assertSame($generatedPath, $route->getPath()); - $this->assertContainsOnlyInstancesOf(MiddlewareInterface::class, [$route->getMiddleware()]); $this->assertSame($generatedName, $route->getName()); $this->assertSame($allowedMethods, $route->getAllowedMethods()); + $this->assertSame([TestHandler::class], $this->runRoute($route)); } + /** + * @return array|null, + * }> + */ public static function methodProvider(): array { - return [ - [ - 'requestMethod' => 'any', - 'routePath' => '/any', + $cases = []; + foreach (['any', 'delete', 'get', 'patch', 'post', 'put'] as $method) { + $path = '/' . $method; + $methods = $method === 'any' ? null : [strtoupper($method)]; + $default = $methods === null ? $path : $path . '^' . strtoupper($method); + + $cases[$method . ' without name'] = [ + 'requestMethod' => $method, + 'routePath' => $path, 'routeName' => null, - 'generatedPath' => '/any', - 'generatedName' => '/any', - 'allowedMethods' => null, - ], - [ - 'requestMethod' => 'any', - 'routePath' => '/any', - 'routeName' => 'app::any', - 'generatedPath' => '/any', - 'generatedName' => 'app::any', - 'allowedMethods' => null, - ], - [ - 'requestMethod' => 'delete', - 'routePath' => '/delete', - 'routeName' => null, - 'generatedPath' => '/delete', - 'generatedName' => '/delete^DELETE', - 'allowedMethods' => ['DELETE'], - ], - [ - 'requestMethod' => 'delete', - 'routePath' => '/delete', - 'routeName' => 'app::delete', - 'generatedPath' => '/delete', - 'generatedName' => 'app::delete', - 'allowedMethods' => ['DELETE'], - ], - [ - 'requestMethod' => 'get', - 'routePath' => '/get', - 'routeName' => null, - 'generatedPath' => '/get', - 'generatedName' => '/get^GET', - 'allowedMethods' => ['GET'], - ], - [ - 'requestMethod' => 'get', - 'routePath' => '/get', - 'routeName' => 'app::get', - 'generatedPath' => '/get', - 'generatedName' => 'app::get', - 'allowedMethods' => ['GET'], - ], - [ - 'requestMethod' => 'patch', - 'routePath' => '/patch', - 'routeName' => null, - 'generatedPath' => '/patch', - 'generatedName' => '/patch^PATCH', - 'allowedMethods' => ['PATCH'], - ], - [ - 'requestMethod' => 'patch', - 'routePath' => '/patch', - 'routeName' => 'app::patch', - 'generatedPath' => '/patch', - 'generatedName' => 'app::patch', - 'allowedMethods' => ['PATCH'], - ], - [ - 'requestMethod' => 'post', - 'routePath' => '/post', - 'routeName' => null, - 'generatedPath' => '/post', - 'generatedName' => '/post^POST', - 'allowedMethods' => ['POST'], - ], - [ - 'requestMethod' => 'post', - 'routePath' => '/post', - 'routeName' => 'app::post', - 'generatedPath' => '/post', - 'generatedName' => 'app::post', - 'allowedMethods' => ['POST'], - ], - [ - 'requestMethod' => 'put', - 'routePath' => '/put', - 'routeName' => null, - 'generatedPath' => '/put', - 'generatedName' => '/put^PUT', - 'allowedMethods' => ['PUT'], - ], - [ - 'requestMethod' => 'put', - 'routePath' => '/put', - 'routeName' => 'app::put', - 'generatedPath' => '/put', - 'generatedName' => 'app::put', - 'allowedMethods' => ['PUT'], - ], - ]; + 'generatedPath' => $path, + 'generatedName' => $default, + 'allowedMethods' => $methods, + ]; + $cases[$method . ' with name'] = [ + 'requestMethod' => $method, + 'routePath' => $path, + 'routeName' => 'app::' . $method, + 'generatedPath' => $path, + 'generatedName' => 'app::' . $method, + 'allowedMethods' => $methods, + ]; + } + + return $cases; } + /** + * @return array|null, + * }> + */ public static function routeProvider(): array { return [ - [ + 'any method, no name' => [ 'routePath' => '/route', 'routeName' => null, 'generatedPath' => '/route', 'generatedName' => '/route', 'allowedMethods' => null, ], - [ + 'two methods, no name' => [ 'routePath' => '/route', 'routeName' => null, 'generatedPath' => '/route', 'generatedName' => '/route^DELETE:GET', 'allowedMethods' => ['DELETE', 'GET'], ], - [ + 'any method, with name' => [ 'routePath' => '/route', 'routeName' => 'app::name', 'generatedPath' => '/route', 'generatedName' => 'app::name', 'allowedMethods' => null, ], - [ + 'two methods, with name' => [ 'routePath' => '/route', 'routeName' => 'app::name', 'generatedPath' => '/route', diff --git a/test/RouteGroupCollectorTest.php b/test/RouteGroupCollectorTest.php index 10181ad..282863a 100644 --- a/test/RouteGroupCollectorTest.php +++ b/test/RouteGroupCollectorTest.php @@ -4,411 +4,335 @@ namespace DotTest\Router; -use Dot\Router\MiddlewareFactory; +use Dot\Router\Exception\InvalidArgumentException; use Dot\Router\RouteGroupCollector; -use Mezzio\Router\RouteCollector; -use Mezzio\Router\RouterInterface; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\TestCase; +use DotTest\Router\Fixture\CallLog; +use DotTest\Router\Fixture\FallbackHandler; +use DotTest\Router\Fixture\FirstMiddleware; +use DotTest\Router\Fixture\MiddlewareWithArgument; +use DotTest\Router\Fixture\SecondMiddleware; +use DotTest\Router\Fixture\TestHandler; +use PHPUnit\Framework\Attributes\DataProvider; +use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; -class RouteGroupCollectorTest extends TestCase +use function strtoupper; + +final class RouteGroupCollectorTest extends AbstractRouterTestCase { - protected RouteGroupCollector $routeGroupCollector; - protected RequestHandlerInterface $handler; + private RouteGroupCollector $routeGroupCollector; - /** - * @throws Exception - */ - protected function setup(): void + protected function setUp(): void { - $this->routeGroupCollector = new RouteGroupCollector( - new RouteCollector($this->createMock(RouterInterface::class)), - $this->createMock(MiddlewareFactory::class) - ); + parent::setUp(); + + $this->routeGroupCollector = new RouteGroupCollector($this->mezzioCollector, $this->middlewareFactory); } public function testWillCreateGroup(): void { - $group = $this->routeGroupCollector->setPrefix('/group')->setMiddleware(MiddlewareInterface::class); + $group = $this->routeGroupCollector->setPrefix('/group')->setMiddleware(FirstMiddleware::class); + $this->assertSame('/group', $group->getPrefix()); - $this->assertSame(MiddlewareInterface::class, $group->getMiddleware()); + $this->assertSame(FirstMiddleware::class, $group->getMiddleware()); + } + + public function testMiddlewareIsNullByDefault(): void + { + $this->assertNull($this->routeGroupCollector->getMiddleware()); + } + + public function testGroupWithoutSetMiddlewareCanAddRoutes(): void + { + $this->routeGroupCollector->setPrefix('/group')->get('/x', TestHandler::class, 'x'); + + $this->assertSame([TestHandler::class], $this->runRoute($this->routeNamed('x'))); + } + + public function testGroupMiddlewareRunsBeforeRouteMiddleware(): void + { + $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware([FirstMiddleware::class, new SecondMiddleware()]) + ->get('/x', TestHandler::class, 'x'); + + $this->assertSame( + [FirstMiddleware::class, SecondMiddleware::class, TestHandler::class], + $this->runRoute($this->routeNamed('x')) + ); + } + + public function testCallableRouteRunsGroupMiddleware(): void + { + $closure = static function ( + ServerRequestInterface $request, + RequestHandlerInterface $handler, + ): ResponseInterface { + CallLog::record('closure'); + + return CallLog::response(); + }; + + $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware(FirstMiddleware::class) + ->get('/x', $closure, 'x'); + + $this->assertSame([FirstMiddleware::class, 'closure'], $this->runRoute($this->routeNamed('x'))); + } + + public function testCallableArrayRouteRunsGroupMiddleware(): void + { + $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware(FirstMiddleware::class) + ->get('/x', [new TestHandler(), 'handle'], 'x'); + + $this->assertSame([FirstMiddleware::class, TestHandler::class], $this->runRoute($this->routeNamed('x'))); + } + + public function testExcludeRemovesGroupMiddlewareByClassName(): void + { + $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware([FirstMiddleware::class, SecondMiddleware::class]) + ->get('/x', TestHandler::class, 'x', FirstMiddleware::class); + + $this->assertSame([SecondMiddleware::class, TestHandler::class], $this->runRoute($this->routeNamed('x'))); + } + + public function testExcludeAcceptsAList(): void + { + $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware([FirstMiddleware::class, SecondMiddleware::class]) + ->get('/x', TestHandler::class, 'x', [FirstMiddleware::class, SecondMiddleware::class]); + + $this->assertSame([TestHandler::class], $this->runRoute($this->routeNamed('x'))); + } + + public function testExcludeRemovesGroupMiddlewareInstanceByClass(): void + { + $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware([new MiddlewareWithArgument('instance'), FirstMiddleware::class]) + ->get('/x', TestHandler::class, 'x', MiddlewareWithArgument::class); + + $this->assertSame([FirstMiddleware::class, TestHandler::class], $this->runRoute($this->routeNamed('x'))); + } + + public function testExcludeByInterfaceRemovesOnlyGroupMiddlewareObjects(): void + { + $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware([new MiddlewareWithArgument('instance'), FirstMiddleware::class]) + ->get('/x', new TestHandler(), 'x', MiddlewareInterface::class); + + $this->assertSame([FirstMiddleware::class, TestHandler::class], $this->runRoute($this->routeNamed('x'))); + } + + public function testExcludeNeverRemovesRouteHandler(): void + { + $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware(FirstMiddleware::class) + ->get('/x', new TestHandler(), 'x', RequestHandlerInterface::class) + ->get('/y', TestHandler::class, 'y', TestHandler::class); + + $this->assertSame([FirstMiddleware::class, TestHandler::class], $this->runRoute($this->routeNamed('x'))); + $this->assertNotContains(FallbackHandler::class, CallLog::calls()); + } + + public function testExcludeDoesNotRemoveTheSameMiddlewareFromTheRoute(): void + { + $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware(FirstMiddleware::class) + ->get('/x', [FirstMiddleware::class, TestHandler::class], 'x', FirstMiddleware::class); + + $this->assertSame([FirstMiddleware::class, TestHandler::class], $this->runRoute($this->routeNamed('x'))); + } + + public function testEmptyPrefixAndPathIsRejected(): void + { + $this->expectException(InvalidArgumentException::class); + + $this->routeGroupCollector->get('', TestHandler::class); + } + + public function testEmptyRoutePathUsesThePrefix(): void + { + $this->routeGroupCollector->setPrefix('/group')->post('', TestHandler::class, 'x'); + + $this->assertSame('/group', $this->routeNamed('x')->getPath()); + } + + public function testGetRoutesReturnsEveryRouteInTheCollector(): void + { + $this->mezzioCollector->get('/home', $this->middlewareFactory->prepare(TestHandler::class), 'home'); + $this->routeGroupCollector->setPrefix('/group')->get('/x', TestHandler::class, 'x'); + + $this->assertCount(2, $this->routeGroupCollector->getRoutes()); } /** - * @dataProvider routeProvider + * @param non-empty-string|null $routeName + * @param list|null $allowedMethods + * @param class-string|list $excludeMiddleware */ + #[DataProvider('routeProvider')] public function testWillCreateRoute( - string $groupPrefix, - string $routePath, - ?string $routeName = null, - ?string $generatedPath = null, - ?string $generatedName = null, - ?array $allowedMethods = null, - array|null|string $excludeMiddleware = [], + ?string $routeName, + string $generatedName, + ?array $allowedMethods, + array|string $excludeMiddleware, ): void { $this->assertCount(0, $this->routeGroupCollector->getRoutes()); - $route = $this->routeGroupCollector - ->setPrefix($groupPrefix) - ->setMiddleware(MiddlewareInterface::class) - ->route( - $routePath, - RequestHandlerInterface::class, - $routeName, - $allowedMethods, - $excludeMiddleware - ); - $this->assertInstanceOf(RouteGroupCollector::class, $route); - + $result = $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware(FirstMiddleware::class) + ->route('/route', TestHandler::class, $routeName, $allowedMethods, $excludeMiddleware); + $this->assertSame($this->routeGroupCollector, $result); $this->assertCount(1, $this->routeGroupCollector->getRoutes()); $route = $this->routeGroupCollector->getRoutes()[0]; - $this->assertSame($generatedPath, $route->getPath()); - $this->assertContainsOnlyInstancesOf(MiddlewareInterface::class, [$route->getMiddleware()]); + $this->assertSame('/group/route', $route->getPath()); $this->assertSame($generatedName, $route->getName()); $this->assertSame($allowedMethods, $route->getAllowedMethods()); + $this->assertSame($this->expectedCalls($excludeMiddleware), $this->runRoute($route)); } /** - * @dataProvider methodProvider + * @param 'any'|'delete'|'get'|'patch'|'post'|'put' $requestMethod + * @param non-empty-string|null $routeName + * @param list|null $allowedMethods + * @param class-string|list $excludeMiddleware */ + #[DataProvider('methodProvider')] public function testWillCreateRoutesByMethod( - string $groupPrefix, string $requestMethod, - string $routePath, - ?string $routeName = null, - ?string $generatedPath = null, - ?string $generatedName = null, - ?array $allowedMethods = null, - array|null|string $excludeMiddleware = [], + ?string $routeName, + string $generatedPath, + string $generatedName, + ?array $allowedMethods, + array|string $excludeMiddleware, ): void { $this->assertCount(0, $this->routeGroupCollector->getRoutes()); - $route = $this->routeGroupCollector - ->setPrefix($groupPrefix) - ->setMiddleware(MiddlewareInterface::class) - ->$requestMethod( - $routePath, - RequestHandlerInterface::class, - $routeName, - $excludeMiddleware - ); - $this->assertInstanceOf(RouteGroupCollector::class, $route); - + $result = $this->routeGroupCollector + ->setPrefix('/group') + ->setMiddleware(FirstMiddleware::class) + ->$requestMethod('/' . $requestMethod, TestHandler::class, $routeName, $excludeMiddleware); + $this->assertSame($this->routeGroupCollector, $result); $this->assertCount(1, $this->routeGroupCollector->getRoutes()); $route = $this->routeGroupCollector->getRoutes()[0]; $this->assertSame($generatedPath, $route->getPath()); - $this->assertContainsOnlyInstancesOf(MiddlewareInterface::class, [$route->getMiddleware()]); $this->assertSame($generatedName, $route->getName()); $this->assertSame($allowedMethods, $route->getAllowedMethods()); + $this->assertSame($this->expectedCalls($excludeMiddleware), $this->runRoute($route)); } + /** + * @return array|null, + * excludeMiddleware: class-string|list, + * }> + */ public static function methodProvider(): array { - return [ - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'any', - 'routePath' => '/any', - 'routeName' => null, - 'generatedPath' => '/group/any', - 'generatedName' => '/group/any', - 'allowedMethods' => null, - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'any', - 'routePath' => '/any', - 'routeName' => null, - 'generatedPath' => '/group/any', - 'generatedName' => '/group/any', - 'allowedMethods' => null, - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'any', - 'routePath' => '/any', - 'routeName' => 'app::group-any', - 'generatedPath' => '/group/any', - 'generatedName' => 'app::group-any', - 'allowedMethods' => null, - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'any', - 'routePath' => '/any', - 'routeName' => 'app::group-any', - 'generatedPath' => '/group/any', - 'generatedName' => 'app::group-any', - 'allowedMethods' => null, - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'delete', - 'routePath' => '/delete', - 'routeName' => null, - 'generatedPath' => '/group/delete', - 'generatedName' => '/group/delete^DELETE', - 'allowedMethods' => ['DELETE'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'delete', - 'routePath' => '/delete', - 'routeName' => null, - 'generatedPath' => '/group/delete', - 'generatedName' => '/group/delete^DELETE', - 'allowedMethods' => ['DELETE'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'delete', - 'routePath' => '/delete', - 'routeName' => 'app::group-delete', - 'generatedPath' => '/group/delete', - 'generatedName' => 'app::group-delete', - 'allowedMethods' => ['DELETE'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'delete', - 'routePath' => '/delete', - 'routeName' => 'app::group-delete', - 'generatedPath' => '/group/delete', - 'generatedName' => 'app::group-delete', - 'allowedMethods' => ['DELETE'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'get', - 'routePath' => '/get', - 'routeName' => null, - 'generatedPath' => '/group/get', - 'generatedName' => '/group/get^GET', - 'allowedMethods' => ['GET'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'get', - 'routePath' => '/get', - 'routeName' => null, - 'generatedPath' => '/group/get', - 'generatedName' => '/group/get^GET', - 'allowedMethods' => ['GET'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'get', - 'routePath' => '/get', - 'routeName' => 'app::group-get', - 'generatedPath' => '/group/get', - 'generatedName' => 'app::group-get', - 'allowedMethods' => ['GET'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'get', - 'routePath' => '/get', - 'routeName' => 'app::group-get', - 'generatedPath' => '/group/get', - 'generatedName' => 'app::group-get', - 'allowedMethods' => ['GET'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'patch', - 'routePath' => '/patch', - 'routeName' => null, - 'generatedPath' => '/group/patch', - 'generatedName' => '/group/patch^PATCH', - 'allowedMethods' => ['PATCH'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'patch', - 'routePath' => '/patch', - 'routeName' => null, - 'generatedPath' => '/group/patch', - 'generatedName' => '/group/patch^PATCH', - 'allowedMethods' => ['PATCH'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'patch', - 'routePath' => '/patch', - 'routeName' => 'app::group-patch', - 'generatedPath' => '/group/patch', - 'generatedName' => 'app::group-patch', - 'allowedMethods' => ['PATCH'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'patch', - 'routePath' => '/patch', - 'routeName' => 'app::group-patch', - 'generatedPath' => '/group/patch', - 'generatedName' => 'app::group-patch', - 'allowedMethods' => ['PATCH'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'post', - 'routePath' => '/post', - 'routeName' => null, - 'generatedPath' => '/group/post', - 'generatedName' => '/group/post^POST', - 'allowedMethods' => ['POST'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'post', - 'routePath' => '/post', - 'routeName' => null, - 'generatedPath' => '/group/post', - 'generatedName' => '/group/post^POST', - 'allowedMethods' => ['POST'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'post', - 'routePath' => '/post', - 'routeName' => 'app::group-post', - 'generatedPath' => '/group/post', - 'generatedName' => 'app::group-post', - 'allowedMethods' => ['POST'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'post', - 'routePath' => '/post', - 'routeName' => 'app::group-post', - 'generatedPath' => '/group/post', - 'generatedName' => 'app::group-post', - 'allowedMethods' => ['POST'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'put', - 'routePath' => '/put', - 'routeName' => null, - 'generatedPath' => '/group/put', - 'generatedName' => '/group/put^PUT', - 'allowedMethods' => ['PUT'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'put', - 'routePath' => '/put', - 'routeName' => null, - 'generatedPath' => '/group/put', - 'generatedName' => '/group/put^PUT', - 'allowedMethods' => ['PUT'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'put', - 'routePath' => '/put', - 'routeName' => 'app::group-put', - 'generatedPath' => '/group/put', - 'generatedName' => 'app::group-put', - 'allowedMethods' => ['PUT'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'requestMethod' => 'put', - 'routePath' => '/put', - 'routeName' => 'app::group-put', - 'generatedPath' => '/group/put', - 'generatedName' => 'app::group-put', - 'allowedMethods' => ['PUT'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - ]; + $cases = []; + foreach (['any', 'delete', 'get', 'patch', 'post', 'put'] as $method) { + $path = '/group/' . $method; + $methods = $method === 'any' ? null : [strtoupper($method)]; + $default = $methods === null ? $path : $path . '^' . strtoupper($method); + + foreach (self::excludeCases() as $excludeLabel => $exclude) { + $cases[$method . ', no name, ' . $excludeLabel] = [ + 'requestMethod' => $method, + 'routeName' => null, + 'generatedPath' => $path, + 'generatedName' => $default, + 'allowedMethods' => $methods, + 'excludeMiddleware' => $exclude, + ]; + $cases[$method . ', with name, ' . $excludeLabel] = [ + 'requestMethod' => $method, + 'routeName' => 'app::group-' . $method, + 'generatedPath' => $path, + 'generatedName' => 'app::group-' . $method, + 'allowedMethods' => $methods, + 'excludeMiddleware' => $exclude, + ]; + } + } + + return $cases; } + /** + * @return array|null, + * excludeMiddleware: class-string|list, + * }> + */ public static function routeProvider(): array { - return [ - [ - 'groupPrefix' => '/group', - 'routePath' => '/route', + $cases = []; + foreach (self::excludeCases() as $excludeLabel => $exclude) { + $cases['any method, no name, ' . $excludeLabel] = [ 'routeName' => null, - 'generatedPath' => '/group/route', 'generatedName' => '/group/route', 'allowedMethods' => null, - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'routePath' => '/route', - 'routeName' => null, - 'generatedPath' => '/group/route', - 'generatedName' => '/group/route^DELETE:GET', - 'allowedMethods' => ['DELETE', 'GET'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'routePath' => '/route', + 'excludeMiddleware' => $exclude, + ]; + $cases['two methods, no name, ' . $excludeLabel] = [ 'routeName' => null, - 'generatedPath' => '/group/route', 'generatedName' => '/group/route^DELETE:GET', 'allowedMethods' => ['DELETE', 'GET'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], - [ - 'groupPrefix' => '/group', - 'routePath' => '/route', - 'routeName' => 'app::group-route', - 'generatedPath' => '/group/route', - 'generatedName' => 'app::group-route', - 'allowedMethods' => null, - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'routePath' => '/route', - 'routeName' => 'app::group-route', - 'generatedPath' => '/group/route', - 'generatedName' => 'app::group-route', - 'allowedMethods' => ['DELETE', 'GET'], - 'excludeMiddleware' => [], - ], - [ - 'groupPrefix' => '/group', - 'routePath' => '/route', + 'excludeMiddleware' => $exclude, + ]; + $cases['two methods, with name, ' . $excludeLabel] = [ 'routeName' => 'app::group-route', - 'generatedPath' => '/group/route', 'generatedName' => 'app::group-route', 'allowedMethods' => ['DELETE', 'GET'], - 'excludeMiddleware' => [MiddlewareInterface::class], - ], + 'excludeMiddleware' => $exclude, + ]; + } + + return $cases; + } + + /** + * @return array> + */ + private static function excludeCases(): array + { + return [ + 'no exclusion' => [], + 'exclude by string' => FirstMiddleware::class, + 'exclude by list' => [FirstMiddleware::class], + 'exclude unrelated name' => [SecondMiddleware::class], ]; } + + /** + * @param class-string|list $excludeMiddleware + * @return list + */ + private function expectedCalls(array|string $excludeMiddleware): array + { + $excluded = $excludeMiddleware === FirstMiddleware::class || $excludeMiddleware === [FirstMiddleware::class]; + + return $excluded ? [TestHandler::class] : [FirstMiddleware::class, TestHandler::class]; + } } From c5bb03e39d58beff66033fc0effc7f3276c0a308 Mon Sep 17 00:00:00 2001 From: bidi Date: Thu, 12 Nov 2026 16:04:43 +0200 Subject: [PATCH 2/2] update based on review Signed-off-by: bidi --- .laminas-ci.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.laminas-ci.json b/.laminas-ci.json index efdd72e..e827682 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -2,5 +2,5 @@ "ignore_php_platform_requirements": { "8.6": true }, - "backwardCompatibilityCheck": false + "backwardCompatibilityCheck": true }