From c2e48773b51bbf203a8c9a3eb58fc916cc6b2d00 Mon Sep 17 00:00:00 2001 From: bidi Date: Fri, 20 Nov 2026 18:39:12 +0200 Subject: [PATCH] updated codebase, composer, workflow, tests Signed-off-by: bidi --- .github/workflows/codecov.yml | 8 +- .github/workflows/static-analysis.yml | 8 +- .gitignore | 1 + .laminas-ci.json | 3 + CHANGELOG.md | 430 +++++++++++++++++- README.md | 23 +- SECURITY.md | 6 +- composer.json | 23 +- docs/book/v5/configuration.md | 69 +++ docs/book/v5/events.md | 257 +++++++++++ docs/book/v5/installation.md | 20 + docs/book/v5/overview.md | 19 + docs/book/v5/plugins.md | 142 ++++++ docs/book/v5/upgrading.md | 108 +++++ docs/book/v5/usage.md | 74 +++ mkdocs.yml | 11 +- phpstan.neon | 7 +- phpunit.xml | 18 +- src/AbstractActionController.php | 61 +-- src/AbstractController.php | 29 +- src/ConfigProvider.php | 9 + src/Event/ControllerEvent.php | 14 +- .../ControllerEventListenerInterface.php | 6 + src/Event/ControllerEventListenerTrait.php | 6 + src/Event/DispatchControllerEventsTrait.php | 32 +- src/Exception/InvalidArgumentException.php | 9 + src/Exception/InvalidPluginException.php | 33 ++ src/Exception/PluginNotFoundException.php | 17 + .../ControllerEventListenersInitializer.php | 72 +-- src/Factory/PluginManagerAwareInitializer.php | 15 +- src/Factory/PluginManagerFactory.php | 34 +- src/Plugin/PluginManager.php | 176 ++++++- src/Plugin/PluginManagerAwareInterface.php | 2 +- src/Plugin/TemplatePlugin.php | 30 +- src/Plugin/UrlHelperPlugin.php | 32 +- test/AbstractActionControllerTest.php | 158 +++++-- test/AbstractControllerTest.php | 150 +++--- test/ConfigProviderTest.php | 39 +- .../ControllerEventListenerTraitTest.php | 88 ++-- .../DispatchControllerEventsTraitTest.php | 81 ++-- ...ontrollerEventListenersInitializerTest.php | 192 +++++--- .../PluginManagerAwareInitializerTest.php | 114 ++--- test/Factory/PluginManagerFactoryTest.php | 106 ++--- test/Fixture/ContainerErrorException.php | 19 + test/Fixture/InMemoryContainer.php | 55 +++ test/Fixture/PassThroughHandler.php | 25 + test/Fixture/PlainPlugin.php | 18 + test/Fixture/ServiceNotFoundException.php | 18 + test/Fixture/StringPlugin.php | 17 + test/Fixture/StringPluginFactory.php | 15 + test/Fixture/TestController.php | 38 ++ test/Fixture/TestListener.php | 38 ++ test/Plugin/PluginManagerTest.php | 189 ++++++-- test/Plugin/TemplatePluginTest.php | 69 +-- test/Plugin/UrlHelperPluginTest.php | 73 ++- 55 files changed, 2612 insertions(+), 694 deletions(-) create mode 100644 docs/book/v5/configuration.md create mode 100644 docs/book/v5/events.md create mode 100644 docs/book/v5/installation.md create mode 100644 docs/book/v5/overview.md create mode 100644 docs/book/v5/plugins.md create mode 100644 docs/book/v5/upgrading.md create mode 100644 docs/book/v5/usage.md create mode 100644 src/Exception/InvalidArgumentException.php create mode 100644 src/Exception/InvalidPluginException.php create mode 100644 src/Exception/PluginNotFoundException.php create mode 100644 test/Fixture/ContainerErrorException.php create mode 100644 test/Fixture/InMemoryContainer.php create mode 100644 test/Fixture/PassThroughHandler.php create mode 100644 test/Fixture/PlainPlugin.php create mode 100644 test/Fixture/ServiceNotFoundException.php create mode 100644 test/Fixture/StringPlugin.php create mode 100644 test/Fixture/StringPluginFactory.php create mode 100644 test/Fixture/TestController.php create mode 100644 test/Fixture/TestListener.php diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index 89e83df..5cd87b3 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') }} @@ -49,6 +49,6 @@ jobs: 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..0e57d13 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,14 +15,14 @@ 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 @@ -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') }} diff --git a/.gitignore b/.gitignore index d3096f4..be7f715 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ clover.xml coveralls-upload.json .phpunit.result.cache +.phpunit.cache .phpcs-cache # Created by .ignore support plugin (hsz.mobi) diff --git a/.laminas-ci.json b/.laminas-ci.json index 29216fa..e827682 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -1,3 +1,6 @@ { + "ignore_php_platform_requirements": { + "8.6": true + }, "backwardCompatibilityCheck": true } diff --git a/CHANGELOG.md b/CHANGELOG.md index 26f18cd..dbeb3a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,183 +1,595 @@ +# Changelog + +## 5.0.0 - TBD + +### Changed + +* Requires PHP 8.3, 8.4, 8.5 or 8.6. +* `PluginManager` is a PSR-11 container and no longer extends `Laminas\ServiceManager\AbstractPluginManager`. +* `ControllerEvent` extends `Laminas\EventManager\Event` directly. +* `dispatchEvent()` returns `ControllerEvent|ResponseInterface`. +* `getPluginManager()` returns `PluginManager` and `plugin()` returns `PluginInterface`. +* `UrlHelperPlugin` takes a `?string` fragment identifier. +* Invalid entries in `dot_controller.event_listeners` throw a `RuntimeException` with a clear message. +* Allows `mezzio/mezzio-template` 3.x. +* PHPStan level 8, PHPUnit 12. + +### Added + +* `PluginNotFoundException`, `InvalidPluginException` and `InvalidArgumentException`. +* `PluginManager::setAlias()` and the `aliases` key of the plugin manager configuration. +* Version 5 documentation with an upgrade guide. + +### Deprecated + +* Nothing + +### Removed + +* PHP 8.2 support. +* The requirements `laminas/laminas-servicemanager` and `dotkernel/dot-event`. +* Support for plugin manager configuration keys other than `factories` and `aliases`. + +### Fixed + +* A listener that returned a response caused a `TypeError` and could not stop the dispatch. +* `TemplatePlugin` with a `null` template name caused a `TypeError`. +* A `debug` configuration value that was not a boolean caused a `TypeError`. +* An `action` request attribute that was not a string caused a `TypeError`. +* A configuration without the `dot_controller` key caused a PHP warning. + +## 4.2.0 - 2025-11-03 + +### Changed + +* Removed PHP 8.1, added PHP 8.4 and 8.5 support (#51). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 4.1.0 - 2025-02-28 + +### Changed + +* Replaced Psalm with PHPStan (#46). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 4.0.1 - 2025-01-27 + +### Changed + +* Bumped Psalm to 6.x (#44). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 4.0.0 - 2025-01-15 + +### Changed + +* Nothing + +### Added + +* Support for `laminas/laminas-servicemanager` 4.x (#42). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.6.0 - 2025-11-03 + +### Changed + +* Removed PHP 8.1, added PHP 8.4 and 8.5 support (#50). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.5.1 - 2024-05-03 + +### Changed + +* Same code as 3.5.0. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.5.0 - 2024-04-25 + +### Changed + +* Disabled the `laminas/laminas-dependency-plugin` Composer plugin (#39). + +### Added + +* Documentation for version 3 (#39). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.3 - 2023-11-30 + +### Changed + +* Nothing + +### Added + +* PHP 8.3 support (#37). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.2 - 2023-08-28 + +### Changed + +* Nothing + +### Added + +* Codecov (#34). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.1 - 2023-08-18 + +### Changed + +* Updated README.md (#29, #30). +* Issue #31 (#32). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.0 - 2023-08-07 + +### Changed + +* Nothing + +### Added + +* Psalm, coding standard check, static analysis and tests (#27). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.3.0 - 2023-03-29 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* `laminas/laminas-dependency-plugin` (#25). + +### Fixed + +* Nothing + +## 3.2.1 - 2022-04-29 + +### Changed + +* Allow exactly PHP 8.0 and 8.1. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.2.0 - 2022-04-29 + +### Changed + +* Allow PHP 8.0 and 8.1. +* Updated the tags in README.md. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.1.1 - 2020-11-02 + +### Changed + +* Require version 2 of `laminas/laminas-dependency-plugin`. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + ## 3.1.0 - 2020-11-02 ### Changed + * Composer 2 compatibility. * Update composer.json to require version 2 of laminas/laminas-dependency-plugin to be Composer 2 compatible. ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed + * Nothing ## 3.0.0 - 2020-05-08 ### Changed + * Updated package dependencies and php version. ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 2.0.0 - 2020-01-30 ### Changed + * Laminas and Mezzio migration. ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Support ### Fixed -* Nothing +* Nothing ## 1.0.0 - 2018-04-11 -* [BC break] replaced delegate with handler +* [BC break] replaced delegate with handler ## 0.3.2 - unreleased ### Changed + * after dispatch event now considers the event parameter `response` to return if the event listeners did not return a ResponseInterface directly ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 0.3.1 - 2017-05-09 ### Changed + * throw a more appropriate error message in case controller was not initialized properly ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 0.3.0 - 2017-04-21 ### Changed + * added the controller as dispatch event parameter * controller event names ### Added + * new controller event `ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH` after dispatching, which allows you to capture the returned response, and possible override the response generation ### Deprecated + * Nothing ### Removed + * `ControllerEvent::EVENT_CONTROLLER_DISPATCH` renamed to `ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH` ### Fixed -* Nothing +* Nothing ## 0.2.1 - 2017-03-18 ### Changed + * updated expressive helpers dependency to 4.0 ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 0.2.0 - 2017-03-15 ### Changed + * Updated factories to use PSR11 container * Updated base controller classes to use PSR15 middleware * Updated `UrlHelperPlugin` to use new version of expressive helpers ### Added + * `UrlHelperPlugin` now supports the additional `UrlHelper` generate parameters * Abstract controller added property `DelegateInterface` $delegate, replacing the $next ### Deprecated + * Nothing ### Removed + * $next property from AbstractController(use $delegate instead) * $response property from AbstractController ### Fixed -* Nothing +* Nothing ## 0.1.1 - 2017-03-11 ### Added + * Update php file headers doc blocks ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 0.1.0 - 2017-03-07 Initial tagged release ### Added + * Everything ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed + * Nothing diff --git a/README.md b/README.md index 53dc995..fbe463b 100644 --- a/README.md +++ b/README.md @@ -3,24 +3,35 @@ This is Dotkernel's controller package that can be used like middleware inside Dotkernel or Mezzio application. It provides base classes for action-based controllers similar to a Laminas controller component. It is more lightweight, though, but supports controller plugins and event listeners. +It works with any PSR-11 container. ## Documentation Documentation is available at: https://docs.dotkernel.org/dot-controller/. +## Versions + +| Version | Supported | PHP versions | +| --- | --- | --- | +| 5.x | Yes | 8.3, 8.4, 8.5, 8.6 | +| 4.x | Yes | 8.2, 8.3, 8.4, 8.5 | +| 3.x | No | 8.2, 8.3, 8.4, 8.5 | + +To upgrade from 4.x, read the "Upgrading" page of the version 5 documentation. + ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-controller) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-controller/4.2.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-controller/5.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-controller)](https://github.com/dotkernel/dot-controller/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-controller)](https://github.com/dotkernel/dot-controller/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-controller)](https://github.com/dotkernel/dot-controller/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-controller)](https://github.com/dotkernel/dot-controller/blob/4.0/LICENSE.md) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-controller)](https://github.com/dotkernel/dot-controller/blob/5.0/LICENSE.md) -[![Build Static](https://github.com/dotkernel/dot-controller/actions/workflows/continuous-integration.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-controller/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-controller/actions/workflows/continuous-integration.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-controller/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-controller/graph/badge.svg?token=VUBG5LM4CK)](https://codecov.io/gh/dotkernel/dot-controller) -[![PHPStan](https://github.com/dotkernel/dot-controller/actions/workflows/static-analysis.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-controller/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-controller/actions/workflows/static-analysis.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-controller/actions/workflows/static-analysis.yml) ## Installation @@ -58,7 +69,7 @@ class UserController extends AbstractActionController { //... } - + public function registerAction() { //... @@ -91,4 +102,4 @@ In this case you can do the following: Now when a request for this route comes in, your controller will run first. Dotkernel controllers are designed to ignore requests that cannot be matched to one of its methods, so if no action matches, it will call the next middleware, in our case, the second controller. -If this is the last controller, and the action does not match here, it will go to the default 404 Not found page (handled by NotFoundDelegate). +If this is the last controller, and the action does not match here, it will go to the default 404 Not found page (handled by `NotFoundHandler`). diff --git a/SECURITY.md b/SECURITY.md index cced106..1e9ea10 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,9 +4,9 @@ | Version | Supported | PHP Version | |---------|--------------------|----------------------------------------------------------------------------------------------------------------| +| 5.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-controller/5.0.0) | | 4.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-controller/4.2.0) | -| 3.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-controller/3.6.0) | -| <= 2.x | :x: | | +| <= 3.x | :x: | | ## Reporting Potential Security Issues @@ -34,4 +34,4 @@ If we verify a reported security vulnerability, our policy is: release branch. - After patching the release branches, we will immediately issue new security - fix releases for each patched release branch. \ No newline at end of file + fix releases for each patched release branch. diff --git a/composer.json b/composer.json index be6ee33..3a8f2d3 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "dotkernel/dot-controller", "type": "library", - "description": "Dotkernel controller like middleware component with plugin support", + "description": "Dotkernel controller-like middleware component with plugin and event support for any PSR-11 container", "license": "MIT", "homepage": "https://github.com/dotkernel/dot-controller", "keywords": [ @@ -9,7 +9,7 @@ "plugin", "laminas", "mezzio", - "service-manager" + "psr-11" ], "authors": [ { @@ -18,19 +18,24 @@ } ], "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", - "dotkernel/dot-event": "^4.0.0", - "laminas/laminas-servicemanager": "^4.0", - "mezzio/mezzio-helpers": "^5.8.0", - "mezzio/mezzio-template": "^2.4.0", - "psr/http-message": "^1.0 || ^2.0" + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", + "laminas/laminas-eventmanager": "^3.16", + "mezzio/mezzio-helpers": "^5.16", + "mezzio/mezzio-template": "^2.9 || ^3.1", + "psr/container": "^1.1 || ^2.0", + "psr/http-message": "^1.0 || ^2.0", + "psr/http-server-handler": "^1.0", + "psr/http-server-middleware": "^1.0" }, "require-dev": { "laminas/laminas-coding-standard": "^3.0", "laminas/laminas-diactoros": "^3.0", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.2" + "phpunit/phpunit": "^12.5" + }, + "suggest": { + "laminas/laminas-servicemanager": "Runs the controller initializers that the ConfigProvider registers" }, "autoload": { "psr-4": { diff --git a/docs/book/v5/configuration.md b/docs/book/v5/configuration.md new file mode 100644 index 0000000..fd2467e --- /dev/null +++ b/docs/book/v5/configuration.md @@ -0,0 +1,69 @@ +# Configuration + +You can use the base controllers immediately after the installation. +To use plugins and events, add the `ConfigProvider` to your configuration aggregator (usually `config/config.php`): + +```php +\Dot\Controller\ConfigProvider::class, +``` + +The `ConfigProvider` registers these items: + +- a factory for `Dot\Controller\Plugin\PluginManager` +- the initializers `PluginManagerAwareInitializer` and `ControllerEventListenersInitializer` +- the `dot_controller` configuration key with empty defaults + +## The `dot_controller` key + +```php +'dot_controller' => [ + 'plugin_manager' => [ + 'factories' => [ + // plugin name => factory class name or callable + ], + 'aliases' => [ + // alias => plugin name + ], + ], + 'event_listeners' => [ + // controller class name => list of listeners + ], +], +``` + +The plugin manager supports only the `factories` and `aliases` keys. +Any other key, for example `invokables` or `delegators`, causes an `InvalidArgumentException`. + +## Initializers and containers + +The initializers give each controller the plugin manager, the `debug` flag and the event listeners. +Laminas Service Manager runs the initializers from the `dependencies.initializers` key. +Other PSR-11 containers ignore this key. +With such a container, call the two initializers in the factory of each controller: + +```php +use Dot\Controller\Factory\ControllerEventListenersInitializer; +use Dot\Controller\Factory\PluginManagerAwareInitializer; +use Psr\Container\ContainerInterface; + +class UserControllerFactory +{ + public function __invoke(ContainerInterface $container): UserController + { + $controller = new UserController(); + (new PluginManagerAwareInitializer())($container, $controller); + (new ControllerEventListenersInitializer())($container, $controller); + + return $controller; + } +} +``` + +Do not use such a factory with Laminas Service Manager and the `ConfigProvider` together. +The listeners then attach two times. + +## The `debug` flag + +`PluginManagerAwareInitializer` reads the top-level `debug` configuration key and calls `setDebug()` on each controller. +The values `true`, `1`, `'1'`, `'true'`, `'on'` and `'yes'` enable it. +Any other value, or no value, disables it. diff --git a/docs/book/v5/events.md b/docs/book/v5/events.md new file mode 100644 index 0000000..f40665b --- /dev/null +++ b/docs/book/v5/events.md @@ -0,0 +1,257 @@ +# Events + +Dotkernel's controller package supports events of two types: global events (like middleware) and events that you trigger manually. + +## Getting started + +- Each event listener for a controller must implement `Dot\Controller\Event\ControllerEventListenerInterface`, which extends `Laminas\EventManager\ListenerAggregateInterface`. +- Use the trait `Dot\Controller\Event\ControllerEventListenerTrait` to get default implementations of the interface methods. You can also extend `Dot\Controller\Event\AbstractControllerEventListener`. +- Register each event listener under the `['dot_controller']['event_listeners']` key. Each key is the class name of a controller, and each value is a list of listeners for that controller. +- The key `Dot\Controller\Event\ControllerEventListenerInterface::LISTEN_ALL` attaches the listeners to all controllers. + +Each item in the list of listeners can be one of these: + +- the class name or the service name of a listener +- an array with the keys `type` (the class name or the service name) and `priority` (an integer, `1` by default) + +The package gets the listener from the container when the container has it. +Otherwise, it creates the listener with `new`. + +## Usage + +You can use events in a controller in two ways: + +- the global way: the package attaches the events automatically to all the actions of the controller, and they work like middleware +- the manual way: you attach the events to a controller, and you trigger them where you want + +The examples use this `UserController`: + +```php +use Dot\Controller\AbstractActionController; +use Laminas\Diactoros\Response\HtmlResponse; +use Psr\Http\Message\ResponseInterface; + +class UserController extends AbstractActionController +{ + public function indexAction(): ResponseInterface + { + return new HtmlResponse('User index'); + } + + public function registerAction(): ResponseInterface + { + return new HtmlResponse('Register'); + } + + // POST method that updates the user + public function updateAction(): ResponseInterface + { + return new HtmlResponse('Updated'); + } +} +``` + +### Global method + +First, create the event listener: + +```php +use Dot\Controller\Event\ControllerEvent; +use Dot\Controller\Event\ControllerEventListenerInterface; +use Dot\Controller\Event\ControllerEventListenerTrait; +use Psr\Log\LoggerInterface; + +class UserUpdatedListener implements ControllerEventListenerInterface +{ + use ControllerEventListenerTrait; + + public function __construct( + private LoggerInterface $logger + ) { + } + + public function onBeforeDispatch(ControllerEvent $e): void + { + $this->logger->info('on before dispatch'); + } + + public function onAfterDispatch(ControllerEvent $e): void + { + $this->logger->info('on after dispatch'); + } +} +``` + +The listener needs a logger, so register a factory for it in the container. +Then register the event listener in the configuration key: + +```php +'dot_controller' => [ + 'event_listeners' => [ + UserController::class => [ + UserUpdatedListener::class, + ], + ], +], +``` + +The package triggers `onBeforeDispatch` right before the action runs, and `onAfterDispatch` right after it. +Thus, for any action, the listener runs before and after the action. +Use the `$e` variable to get information about the event. + +The event has these parameters: + +| Parameter | Before dispatch | After dispatch | +| --- | --- | --- | +| `request` | The current request | The request before the action | +| `handler` | The next request handler | The same | +| `controller` | The controller | The same | +| `method` | The name of the action method, for example `updateAction` | The same | +| `response` | Not set | The response of the action | + +For example: + +```php +// UserUpdatedListener +public function onAfterDispatch(ControllerEvent $e): void +{ + $method = $e->getParam('request')->getMethod(); + $action = $e->getParam('method'); + if ($method === 'POST' && $action === 'updateAction') { + $this->logger->info('The user was updated'); + } +} +``` + +Each time a POST request calls `updateAction`, the listener writes a log line right after the action. +Use `onBeforeDispatch` in the same way to write a log line right before the action. + +### Replace the request + +A listener of the "before dispatch" event can give the action a different request. +Set the `request` parameter of the event: + +```php +public function onBeforeDispatch(ControllerEvent $e): void +{ + $request = $e->getParam('request'); + $e->setParam('request', $request->withAttribute('startedAt', time())); +} +``` + +### Stop the dispatch + +A listener that returns a `Psr\Http\Message\ResponseInterface` stops the other listeners, and the controller returns that response. +A response from a "before dispatch" listener prevents the action. +A response from an "after dispatch" listener replaces the response of the action. + +The methods `onBeforeDispatch()` and `onAfterDispatch()` return `void`. +To return a response, attach your own method in `attach()`: + +```php +use Dot\Controller\Event\ControllerEvent; +use Dot\Controller\Event\ControllerEventListenerInterface; +use Dot\Controller\Event\ControllerEventListenerTrait; +use Laminas\Diactoros\Response\RedirectResponse; +use Laminas\EventManager\EventManagerInterface; +use Psr\Http\Message\ResponseInterface; + +class LoginRequiredListener implements ControllerEventListenerInterface +{ + use ControllerEventListenerTrait; + + public function attach(EventManagerInterface $events, $priority = 1): void + { + $this->listeners[] = $events->attach( + ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH, + [$this, 'checkLogin'], + $priority + ); + } + + public function checkLogin(ControllerEvent $e): ?ResponseInterface + { + $request = $e->getParam('request'); + if ($request->getAttribute('identity') === null) { + return new RedirectResponse('/login'); + } + + return null; + } +} +``` + +### Manual method + +```php +use Dot\Controller\Event\ControllerEvent; +use Dot\Controller\Event\ControllerEventListenerInterface; +use Dot\Controller\Event\ControllerEventListenerTrait; +use Laminas\EventManager\EventManagerInterface; +use Psr\Log\LoggerInterface; + +class UserProfileListener implements ControllerEventListenerInterface +{ + use ControllerEventListenerTrait; + + public function __construct( + private LoggerInterface $logger + ) { + } + + public function attach(EventManagerInterface $events, $priority = 1): void + { + $this->listeners[] = $events->attach( + 'user.profile.update', + [$this, 'userProfileUpdated'], + $priority + ); + } + + public function userProfileUpdated(ControllerEvent $e): void + { + $this->logger->info('User profile updated'); + } +} +``` + +The `attach()` method comes from `ListenerAggregateInterface`. +`ControllerEventListenerTrait` gives a default `attach()` that listens to the `onBeforeDispatch` and `onAfterDispatch` events. +This listener replaces it, and attaches a custom event, `user.profile.update`, to the method `userProfileUpdated`. + +Next, register the listener: + +```php +'dot_controller' => [ + 'event_listeners' => [ + UserController::class => [ + UserProfileListener::class, + ], + ], +], +``` + +Now trigger the event from the controller with the built-in `dispatchEvent()` method: + +```php +// UserController +// POST method that updates the user +public function updateAction(): ResponseInterface +{ + // update the user + $this->dispatchEvent('user.profile.update', ['user' => $user]); + + return new HtmlResponse('Updated'); +} +``` + +`dispatchEvent()` returns the event, or the response of a listener that returned one. +The code gives the `user` key to the parameters, so the listener can read it: + +```php +public function userProfileUpdated(ControllerEvent $e): void +{ + $user = $e->getParam('user'); + $this->logger->info('User profile updated', $user->toArray()); +} +``` diff --git a/docs/book/v5/installation.md b/docs/book/v5/installation.md new file mode 100644 index 0000000..83e1b62 --- /dev/null +++ b/docs/book/v5/installation.md @@ -0,0 +1,20 @@ +# Installation + +Install `dot-controller` with this Composer command: + +```shell +composer require dotkernel/dot-controller +``` + +Version 5 requires PHP 8.3, 8.4, 8.5 or 8.6. + +The package works with any [PSR-11](https://www.php-fig.org/psr/psr-11/) container. +The package does not install a container. +Dotkernel and Mezzio applications usually use Laminas Service Manager. +If your application uses it, require it in your own `composer.json`: + +```shell +composer require laminas/laminas-servicemanager +``` + +Upgrade from an older version with the [upgrade guide](upgrading.md). diff --git a/docs/book/v5/overview.md b/docs/book/v5/overview.md new file mode 100644 index 0000000..417358f --- /dev/null +++ b/docs/book/v5/overview.md @@ -0,0 +1,19 @@ +# Overview + +`dot-controller` is Dotkernel's controller package that can be used like middleware inside Dotkernel or Mezzio application. +It provides base classes for action-based controllers similar to a Laminas controller component. +It is more lightweight, though, but supports controller plugins and event listeners. + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-controller) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-controller/5.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-controller)](https://github.com/dotkernel/dot-controller/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-controller)](https://github.com/dotkernel/dot-controller/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-controller)](https://github.com/dotkernel/dot-controller/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-controller)](https://github.com/dotkernel/dot-controller/blob/5.0/LICENSE.md) + +[![Build Static](https://github.com/dotkernel/dot-controller/actions/workflows/continuous-integration.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-controller/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-controller/graph/badge.svg?token=VUBG5LM4CK)](https://codecov.io/gh/dotkernel/dot-controller) +[![PHPStan](https://github.com/dotkernel/dot-controller/actions/workflows/static-analysis.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-controller/actions/workflows/static-analysis.yml) diff --git a/docs/book/v5/plugins.md b/docs/book/v5/plugins.md new file mode 100644 index 0000000..9b21414 --- /dev/null +++ b/docs/book/v5/plugins.md @@ -0,0 +1,142 @@ +# Plugins + +Dotkernel's controller supports plugins, much like controllers in Laminas applications. +The package has two built-in plugins, and you can add your own plugins. + +## Usage + +Each controller plugin must implement `Dot\Controller\Plugin\PluginInterface`. +Create a factory for the plugin and register it under the `['dot_controller']['plugin_manager']['factories']` key, with the plugin name as key. + +After registration, any controller can use the plugin: call a method with the name of the plugin. +If the plugin is invokable (it has an `__invoke()` method), the call invokes it with your arguments. +Otherwise, the call returns the plugin. + +Each call creates a new plugin instance. +To keep an instance, store it in a variable. + +Plugins give all controllers a function without manual injection of dependencies. +Use plugins only for functions that many controllers need. +Do not add unnecessary plugins to the controllers. + +### Example + +First, create the plugin. For this example, a string helper: + +```php +use Dot\Controller\Plugin\PluginInterface; + +class StringPlugin implements PluginInterface +{ + // A method must be public to be available in a controller. + public function toUpper(string $string): string + { + return strtoupper($string); + } +} +``` + +Create a factory for the plugin. +The plugin manager calls the factory with the application container, the plugin name and the build options: + +```php +use Psr\Container\ContainerInterface; + +class StringPluginFactory +{ + public function __invoke(ContainerInterface $container): StringPlugin + { + return new StringPlugin(); + } +} +``` + +Register the factory under the `['dot_controller']['plugin_manager']['factories']` key: + +```php +'dot_controller' => [ + 'plugin_manager' => [ + 'factories' => [ + 'string' => StringPluginFactory::class, + ], + ], +], +``` + +Do not register the plugin factory in the `dependencies` key. +The plugin manager is a separate PSR-11 container, and it uses only its own configuration. + +Use the plugin in a controller: + +```php +// In a controller action +$this->string(); // returns the StringPlugin instance +$this->string()->toUpper('test'); // returns 'TEST' +``` + +### Aliases + +Give a plugin a second name with the `aliases` key: + +```php +'dot_controller' => [ + 'plugin_manager' => [ + 'aliases' => [ + 'str' => 'string', + ], + ], +], +``` + +### Errors + +| Situation | Exception | +| --- | --- | +| No plugin has this name | `Dot\Controller\Exception\PluginNotFoundException`, a PSR-11 `NotFoundExceptionInterface` | +| The factory does not return a `PluginInterface` | `Dot\Controller\Exception\InvalidPluginException`, a PSR-11 `ContainerExceptionInterface` | +| The plugin manager configuration has an unsupported key | `Dot\Controller\Exception\InvalidArgumentException` | + +## Built-in plugins + +The package has two built-in plugins, `url` and `template`. +The plugin manager registers each one only when the application container has the service that it needs. + +### `url` + +The `url` plugin is a `Dot\Controller\Plugin\UrlHelperPlugin`. +It needs the `Mezzio\Helper\UrlHelper` service. +Call it with arguments to generate a URL, or without arguments to get the plugin: + +```php +// In a controller action +$url = $this->url('account', ['action' => 'foo', 'hash' => 'bar']); + +// The same URL in two steps +$plugin = $this->url(); +$url = $plugin->generate('account', ['action' => 'foo', 'hash' => 'bar']); +``` + +A `null` route name generates a URL for the route that matched the current request. + +### `template` + +The `template` plugin is a `Dot\Controller\Plugin\TemplatePlugin`. +It needs the `Mezzio\Template\TemplateRendererInterface` service. +Call it with a template name to render the template, or without arguments to get the plugin: + +```php +use Laminas\Diactoros\Response\HtmlResponse; + +// In a controller action +return new HtmlResponse( + $this->template('page::home', [ + 'foo' => 'bar', + ]) +); +``` + +The plugin also has the methods `render()` and `addDefaultParam()`: + +```php +$this->template()->addDefaultParam('page::home', 'title', 'Home'); +``` diff --git a/docs/book/v5/upgrading.md b/docs/book/v5/upgrading.md new file mode 100644 index 0000000..9ba16d8 --- /dev/null +++ b/docs/book/v5/upgrading.md @@ -0,0 +1,108 @@ +# Upgrading + +This page lists the changes in version 5 that can break your code. +For each change, it gives the symptom and the fix. + +## Upgrade from version 4 + +### Requirements + +| Change | Symptom | Fix | +| --- | --- | --- | +| PHP 8.2 support stops | Composer cannot install version 5 | Use PHP 8.3, 8.4, 8.5 or 8.6 | +| The package does not require `laminas/laminas-servicemanager` | `Class "Laminas\ServiceManager\ServiceManager" not found` | Add `laminas/laminas-servicemanager` to the `composer.json` of your application | +| The package does not require `dotkernel/dot-event` | `Class "Dot\Event\..." not found` | Add `dotkernel/dot-event` to the `composer.json` of your application if your code uses it | + +### Plugin manager + +| Change | Symptom | Fix | +| --- | --- | --- | +| `PluginManager` no longer extends `Laminas\ServiceManager\AbstractPluginManager` | A call to `setService()`, `configure()`, `setInvokableClass()` or another Laminas method fails | Use `setFactory()`, `setAlias()`, `get()`, `has()` or `build()` | +| The plugin manager supports only the `factories` and `aliases` keys | `InvalidArgumentException` at startup | Move each `invokables` entry to `factories`. Remove `delegators`, `abstract_factories`, `initializers`, `shared`, `lazy_services` and `services` | +| The Laminas exceptions are gone | A `catch` of `ServiceNotFoundException` or `InvalidServiceException` does not catch | Catch `Psr\Container\NotFoundExceptionInterface` or `Psr\Container\ContainerExceptionInterface` | +| `PluginManager` has no template parameter | A `@var PluginManager<...>` annotation fails static analysis | Use `PluginManager` without a template parameter | + +#### Replace an invokable plugin + +Before: + +```php +'dot_controller' => [ + 'plugin_manager' => [ + 'invokables' => [ + 'string' => StringPlugin::class, + ], + ], +], +``` + +After: + +```php +'dot_controller' => [ + 'plugin_manager' => [ + 'factories' => [ + 'string' => static fn (): StringPlugin => new StringPlugin(), + ], + ], +], +``` + +Use a factory class if your configuration is cached, because a cached configuration cannot hold a closure. + +#### Catch a missing plugin + +Before: + +```php +use Laminas\ServiceManager\Exception\ServiceNotFoundException; + +try { + $this->plugin('string'); +} catch (ServiceNotFoundException $exception) { + // ... +} +``` + +After: + +```php +use Psr\Container\NotFoundExceptionInterface; + +try { + $this->plugin('string'); +} catch (NotFoundExceptionInterface $exception) { + // ... +} +``` + +### Controllers and events + +| Change | Symptom | Fix | +| --- | --- | --- | +| `ControllerEvent` extends `Laminas\EventManager\Event` | `$event instanceof Dot\Event\Event` is `false` | Check for `Dot\Controller\Event\ControllerEvent` or `Laminas\EventManager\EventInterface` | +| `dispatchEvent()` returns `ControllerEvent\|ResponseInterface` | A class that overrides `dispatchEvent()` causes a fatal error | Change the return type of the override | +| `getPluginManager()` returns `PluginManager`, not `?PluginManager` | A class that implements `PluginManagerAwareInterface` or overrides the method causes a fatal error | Change the return type to `PluginManager` | +| `plugin()` returns `PluginInterface` | An override with the old return type causes a fatal error | Change the return type to `PluginInterface` | +| A listener response now stops the dispatch | Before version 5, a listener that returned a response caused a `TypeError` | No change is necessary. Make sure that your listeners return a response only when they want to stop the dispatch | +| An `action` attribute that is not a string selects `index` | Before version 5, it caused a `TypeError` | No change is necessary | +| The action `0` no longer selects `index` | A request for `/route/0` goes to the next middleware | Add a route for this case if you need it | + +### Plugins + +| Change | Symptom | Fix | +| --- | --- | --- | +| `UrlHelperPlugin` takes a `?string` fragment identifier | `TypeError` when you give an integer | Give a string | +| `TemplatePlugin` returns the plugin for a `null` or empty template name | Before version 5, it caused a `TypeError` | No change is necessary | + +### Configuration + +| Change | Symptom | Fix | +| --- | --- | --- | +| A listener entry without a valid `type`, or with a priority that is not an integer, throws `RuntimeException` | Startup fails with a clear message | Fix the entry in `dot_controller.event_listeners` | +| The `debug` flag accepts `1`, `'1'`, `'true'`, `'on'` and `'yes'` | Before version 5, a value that was not a boolean caused a `TypeError` | No change is necessary | + +## Upgrade from version 3 + +Version 3 is no longer supported. +Upgrade to version 4 first with the version 4 documentation, then follow the steps above. diff --git a/docs/book/v5/usage.md b/docs/book/v5/usage.md new file mode 100644 index 0000000..8503903 --- /dev/null +++ b/docs/book/v5/usage.md @@ -0,0 +1,74 @@ +# Usage + +Middleware controllers handle more than one route. +The package uses these conventions: + +- Register controllers in the routes just like any Mezzio middleware. + Define an `action` route parameter (it can be optional) in the route, for example `/user[/{action}]`. +- The package converts the value of the `action` parameter to a method name of the controller. + It removes the underscore, dot and hyphen characters, converts the name to camel case, and adds the suffix `Action`. + For example, the route and action pair `/user/forgot-password` calls the method `forgotPasswordAction`. +- When the `action` parameter is missing, empty, or not a string, the default action is `index`. + Always define an `indexAction` in your controllers, to show a default page or to redirect. + +To create an action-based controller, extend the abstract class `Dot\Controller\AbstractActionController`. + +## Example + +This `UserController` has a default action and a register action. +It handles the routes `/user` and `/user/register`: + +```php +use Dot\Controller\AbstractActionController; +use Laminas\Diactoros\Response\HtmlResponse; +use Psr\Http\Message\ResponseInterface; + +class UserController extends AbstractActionController +{ + public function indexAction(): ResponseInterface + { + return new HtmlResponse('User index'); + } + + public function registerAction(): ResponseInterface + { + return new HtmlResponse('Register'); + } +} +``` + +Register this controller as routed middleware in the file `RoutesDelegator.php`, just like regular middleware: + +```php +// Example from a Dotkernel RoutesDelegator +$app->route( + '/user[/{action}]', + UserController::class, + [RequestMethodInterface::METHOD_GET, RequestMethodInterface::METHOD_POST], + 'user' +); +``` + +### Multiple controllers for the same route + +**Use case:** +A package defines a controller with default actions. +You want to add actions to the same controller name (more exactly, the same route name). +You do not want to extend the controller of the package. +Do these steps: + +- Create your own controller, independent of the controller of the package, with the new actions. +- Mezzio lets you define an array of middleware for a route. Register your controller before the controller of the package. + +When a request for this route comes in, your controller runs first. +A Dotkernel controller ignores a request that does not match one of its methods. +It then calls the next middleware, in this case the second controller. +If the action does not match in the last controller either, the request goes to the default "404 Not Found" page (handled by `NotFoundHandler`). + +## Plugins + +- [Plugins](plugins.md) + +## Events + +- [Events](events.md) diff --git a/mkdocs.yml b/mkdocs.yml index 80b3c25..6358ac4 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,12 +2,21 @@ docs_dir: docs/book site_dir: docs/html extra: project: Packages - current_version: v4 + current_version: v5 versions: + - v5 - v4 - v3 nav: - Home: index.md + - v5: + - Overview: v5/overview.md + - Installation: v5/installation.md + - Configuration: v5/configuration.md + - Usage: v5/usage.md + - Plugins: v5/plugins.md + - Events: v5/events.md + - Upgrading: v5/upgrading.md - v4: - Overview: v4/overview.md - Installation: v4/installation.md diff --git a/phpstan.neon b/phpstan.neon index 8a8b704..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,13 +1,8 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test treatPhpDocTypesAsCertain: false - ignoreErrors: - - message: '#Call to an undefined method .*::somePlugin\(\)\.#' - path: test/AbstractControllerTest.php - - message: '#Call to an undefined method .*::callablePlugin\(\)\.#' - path: test/AbstractControllerTest.php diff --git a/phpunit.xml b/phpunit.xml index 5302ca2..a5851b1 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,12 +1,24 @@ - + ./test - - + ./src diff --git a/src/AbstractActionController.php b/src/AbstractActionController.php index 5ea6229..77f0271 100644 --- a/src/AbstractActionController.php +++ b/src/AbstractActionController.php @@ -6,8 +6,9 @@ use Dot\Controller\Event\ControllerEvent; use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\ServerRequestInterface; -use function array_merge; +use function is_string; use function method_exists; use function strtolower; use function trim; @@ -16,38 +17,44 @@ abstract class AbstractActionController extends AbstractController { public function dispatch(): ResponseInterface { - $action = strtolower(trim($this->request->getAttribute('action', 'index'))); - if (empty($action)) { + $action = $this->request->getAttribute('action'); + $action = is_string($action) ? strtolower(trim($action)) : ''; + if ($action === '') { $action = 'index'; } $action = AbstractController::getMethodFromAction($action); - if (method_exists($this, $action)) { - $r = $this->dispatchEvent(ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH, [ - 'request' => $this->request, - 'handler' => $this->getHandler(), - 'controller' => $this, - 'method' => $action, - ]); - if ($r instanceof ResponseInterface) { - return $r; - } - - $this->request = $r->getParam('request'); - $response = $this->$action(); - $params = array_merge($r->getParams(), ['response' => $response]); - - $r = $this->dispatchEvent(ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH, $params); - if ($r instanceof ResponseInterface) { - return $r; - } - - return $response; + if (! method_exists($this, $action)) { + // Go to the next middleware. If no middleware handles the request, the result is a 404 response. + return $this->getHandler()->handle($this->request); } - //just go the next middleware, it will eventually hit a 404 if no one handles the request - $handler = $this->getHandler(); - return $handler->handle($this->request); + $event = $this->dispatchEvent(ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH, [ + 'request' => $this->request, + 'handler' => $this->getHandler(), + 'controller' => $this, + 'method' => $action, + ]); + if ($event instanceof ResponseInterface) { + return $event; + } + + $request = $event->getParam('request'); + if ($request instanceof ServerRequestInterface) { + $this->request = $request; + } + + $response = $this->$action(); + + $event = $this->dispatchEvent( + ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH, + [...$event->getParams(), 'response' => $response] + ); + if ($event instanceof ResponseInterface) { + return $event; + } + + return $response; } } diff --git a/src/AbstractController.php b/src/AbstractController.php index d1c810d..47a71ba 100644 --- a/src/AbstractController.php +++ b/src/AbstractController.php @@ -16,7 +16,6 @@ use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; -use function call_user_func_array; use function is_callable; use function lcfirst; use function sprintf; @@ -71,38 +70,46 @@ public function getHandler(): RequestHandlerInterface } /** - * Method overloading: return/call plugins + * Method overloading: return or call plugins * - * If the plugin is a functor, call it, passing the parameters provided. + * If the plugin is invokable, call it with the given parameters. * Otherwise, return the plugin instance. + * + * @param array $params + * @throws ContainerExceptionInterface */ public function __call(string $method, array $params): mixed { $plugin = $this->plugin($method); if (is_callable($plugin)) { - return call_user_func_array($plugin, $params); + return $plugin(...$params); } + return $plugin; } /** - * Get plugin instance + * Create a new plugin instance on each call. * + * @param array $options * @throws ContainerExceptionInterface */ - public function plugin(string $name, array $options = []): PluginInterface|callable|null + public function plugin(string $name, array $options = []): PluginInterface { - return $this->getPluginManager()?->build($name, $options); + return $this->getPluginManager()->build($name, $options); } - public function getPluginManager(): ?PluginManager + /** + * @throws RuntimeException + */ + public function getPluginManager(): PluginManager { - if (! $this->pluginManager) { + if ($this->pluginManager === null) { throw new RuntimeException( sprintf( 'Controller plugin manager not set for controller `%s`.' - . ' Enable the controller module by merging' - . ' its ConfigProvider and make sure the controller is registered in the service manager', + . ' Merge the ConfigProvider of dot-controller, register the controller in the container,' + . ' and make sure that the container runs the PluginManagerAwareInitializer', static::class ) ); diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 68097ca..ae33437 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -11,6 +11,12 @@ class ConfigProvider { + /** + * @return array{ + * dependencies: array{factories: array, initializers: list}, + * dot_controller: array{plugin_manager: array, event_listeners: array}, + * } + */ public function __invoke(): array { return [ @@ -22,6 +28,9 @@ public function __invoke(): array ]; } + /** + * @return array{factories: array, initializers: list} + */ public function getDependenciesConfig(): array { return [ diff --git a/src/Event/ControllerEvent.php b/src/Event/ControllerEvent.php index 02c7642..c7e18c9 100644 --- a/src/Event/ControllerEvent.php +++ b/src/Event/ControllerEvent.php @@ -5,7 +5,7 @@ namespace Dot\Controller\Event; use ArrayAccess; -use Dot\Event\Event; +use Laminas\EventManager\Event; /** * @template TTarget of object|string|null @@ -16,4 +16,16 @@ class ControllerEvent extends Event { public const EVENT_CONTROLLER_BEFORE_DISPATCH = 'event.controller.beforeDispatch'; public const EVENT_CONTROLLER_AFTER_DISPATCH = 'event.controller.afterDispatch'; + + /** + * @param TTarget $target + * @param TParams $params + */ + public function __construct( + ?string $name = null, + object|string|null $target = null, + array|object $params = [] + ) { + parent::__construct($name, $target, $params); + } } diff --git a/src/Event/ControllerEventListenerInterface.php b/src/Event/ControllerEventListenerInterface.php index 8ba34dc..ee19600 100644 --- a/src/Event/ControllerEventListenerInterface.php +++ b/src/Event/ControllerEventListenerInterface.php @@ -10,7 +10,13 @@ interface ControllerEventListenerInterface extends ListenerAggregateInterface { public const LISTEN_ALL = 1; + /** + * @param ControllerEvent> $e + */ public function onBeforeDispatch(ControllerEvent $e): void; + /** + * @param ControllerEvent> $e + */ public function onAfterDispatch(ControllerEvent $e): void; } diff --git a/src/Event/ControllerEventListenerTrait.php b/src/Event/ControllerEventListenerTrait.php index 3964646..e93d19a 100644 --- a/src/Event/ControllerEventListenerTrait.php +++ b/src/Event/ControllerEventListenerTrait.php @@ -28,10 +28,16 @@ public function attach(EventManagerInterface $events, $priority = 1): void ); } + /** + * @param ControllerEvent> $e + */ public function onBeforeDispatch(ControllerEvent $e): void { } + /** + * @param ControllerEvent> $e + */ public function onAfterDispatch(ControllerEvent $e): void { } diff --git a/src/Event/DispatchControllerEventsTrait.php b/src/Event/DispatchControllerEventsTrait.php index 962b435..2a33d6c 100644 --- a/src/Event/DispatchControllerEventsTrait.php +++ b/src/Event/DispatchControllerEventsTrait.php @@ -6,35 +6,41 @@ use Dot\Controller\AbstractController; use Dot\Controller\Exception\RuntimeException; -use Dot\Event\Event; use Laminas\EventManager\EventManagerAwareTrait; -use Laminas\EventManager\ResponseCollection; use Psr\Http\Message\ResponseInterface; trait DispatchControllerEventsTrait { use EventManagerAwareTrait; + /** + * Trigger a controller event. + * + * When a listener returns a response, the other listeners do not run and this method returns that response. + * Otherwise, it returns the event, which can hold params that the listeners changed. + * + * @param array $data + * @return ControllerEvent>|ResponseInterface + * @throws RuntimeException + */ public function dispatchEvent( string $name, array $data = [], object|string|null $target = null - ): Event|ResponseCollection { + ): ControllerEvent|ResponseInterface { if (! $this instanceof AbstractController) { throw new RuntimeException('Only controllers can dispatch controller events'); } - if ($target === null) { - $target = $this; - } - - $event = new ControllerEvent($name, $target, $data); - $r = $this->getEventManager()->triggerEventUntil(function ($r) { - return $r instanceof ResponseInterface; - }, $event); + $event = new ControllerEvent($name, $target ?? $this, $data); + $result = $this->getEventManager()->triggerEventUntil( + static fn (mixed $response): bool => $response instanceof ResponseInterface, + $event + ); - if ($r->stopped()) { - return $r->last(); + $last = $result->last(); + if ($result->stopped() && $last instanceof ResponseInterface) { + return $last; } return $event; diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php new file mode 100644 index 0000000..3c87aea --- /dev/null +++ b/src/Exception/InvalidArgumentException.php @@ -0,0 +1,9 @@ +get('config')['dot_controller']; + $config = $container->has('config') ? $container->get('config') : []; + $listeners = is_array($config) ? ($config['dot_controller']['event_listeners'] ?? []) : []; + if (! is_array($listeners)) { + return; + } - if (isset($config['event_listeners']) && is_array($config['event_listeners'])) { - foreach ($config['event_listeners'] as $ctrl => $listeners) { - if ( - $controller::class === $ctrl - || $ctrl === ControllerEventListenerInterface::LISTEN_ALL - ) { - if (is_array($listeners)) { - foreach ($listeners as $listenerConfig) { - if (is_array($listenerConfig)) { - $listener = $listenerConfig['type'] ?? ''; - $priority = (int) ($listenerConfig['priority'] ?? 1); + foreach ($listeners as $target => $entries) { + if ($target !== $controller::class && $target !== ControllerEventListenerInterface::LISTEN_ALL) { + continue; + } + if (! is_array($entries)) { + continue; + } - $listener = $this->getControllerListener($container, $listener); - $listener->attach($controller->getEventManager(), $priority); - } elseif (is_string($listenerConfig)) { - $listener = $listenerConfig; - $priority = 1; + foreach ($entries as $entry) { + $name = is_array($entry) ? ($entry['type'] ?? null) : $entry; + $priority = is_array($entry) ? ($entry['priority'] ?? 1) : 1; - $listener = $this->getControllerListener($container, $listener); - $listener->attach($controller->getEventManager(), $priority); - } - } - } + if (! is_string($name) || $name === '') { + throw new RuntimeException(sprintf( + 'Each controller event listener entry for `%s` must name a listener class or service,' + . ' %s given', + $controller::class, + get_debug_type($name) + )); + } + if (is_string($priority) && is_numeric($priority)) { + $priority = (int) $priority; } + if (! is_int($priority)) { + throw new RuntimeException(sprintf( + 'The priority of controller event listener `%s` must be an integer, %s given', + $name, + get_debug_type($priority) + )); + } + + $this->getControllerListener($container, $name)->attach($controller->getEventManager(), $priority); } } } @@ -70,16 +85,13 @@ public function attachControllerListeners(ContainerInterface $container, Abstrac /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface + * @throws RuntimeException */ protected function getControllerListener( ContainerInterface $container, string $listenerName ): ControllerEventListenerInterface { - $listener = $listenerName; - if ($container->has($listener)) { - $listener = $container->get($listener); - } - + $listener = $container->has($listenerName) ? $container->get($listenerName) : $listenerName; if (is_string($listener) && class_exists($listener)) { $listener = new $listener(); } @@ -88,7 +100,7 @@ protected function getControllerListener( throw new RuntimeException(sprintf( 'Controller event listener must be an instance of %s, but %s was provided', ControllerEventListenerInterface::class, - is_object($listener) ? $listener::class : gettype($listener) + get_debug_type($listener) )); } diff --git a/src/Factory/PluginManagerAwareInitializer.php b/src/Factory/PluginManagerAwareInitializer.php index ddcb960..6159377 100644 --- a/src/Factory/PluginManagerAwareInitializer.php +++ b/src/Factory/PluginManagerAwareInitializer.php @@ -11,6 +11,11 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function filter_var; +use function is_array; + +use const FILTER_VALIDATE_BOOLEAN; + class PluginManagerAwareInitializer { /** @@ -21,12 +26,16 @@ public function __invoke(ContainerInterface $container, object|null $instance = { if ($instance instanceof PluginManagerAwareInterface) { $pluginManager = $container->get(PluginManager::class); - $instance->setPluginManager($pluginManager); + if ($pluginManager instanceof PluginManager) { + $instance->setPluginManager($pluginManager); + } } - // we'll inject the debug flag here too, for now + // The debug flag is injected here too. if ($instance instanceof AbstractController) { - $instance->setDebug($container->get('config')['debug'] ?? false); + $config = $container->has('config') ? $container->get('config') : []; + $debug = is_array($config) ? ($config['debug'] ?? false) : false; + $instance->setDebug(filter_var($debug, FILTER_VALIDATE_BOOLEAN)); } } } diff --git a/src/Factory/PluginManagerFactory.php b/src/Factory/PluginManagerFactory.php index 0987f94..8c3fee4 100644 --- a/src/Factory/PluginManagerFactory.php +++ b/src/Factory/PluginManagerFactory.php @@ -4,6 +4,7 @@ namespace Dot\Controller\Factory; +use Dot\Controller\Exception\InvalidArgumentException; use Dot\Controller\Plugin\PluginManager; use Dot\Controller\Plugin\TemplatePlugin; use Dot\Controller\Plugin\UrlHelperPlugin; @@ -13,27 +14,44 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function is_array; + class PluginManagerFactory { /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface + * @throws InvalidArgumentException */ public function __invoke(ContainerInterface $container): PluginManager { - $pluginManager = new PluginManager($container, $container->get('config')['dot_controller']['plugin_manager']); + $config = $container->has('config') ? $container->get('config') : []; + $config = is_array($config) ? ($config['dot_controller']['plugin_manager'] ?? []) : []; + if (! is_array($config)) { + throw new InvalidArgumentException('The "dot_controller.plugin_manager" config must be an array.'); + } + + $pluginManager = new PluginManager($container, $config); - //register the built-in plugins, if the required component is present + // Register the built-in plugins when the required service is present. if ($container->has(UrlHelper::class)) { - $pluginManager->setFactory('url', function (ContainerInterface $container) { - return new UrlHelperPlugin($container->get(UrlHelper::class)); - }); + $pluginManager->setFactory( + 'url', + static function (ContainerInterface $container): UrlHelperPlugin { + $helper = $container->get(UrlHelper::class); + return new UrlHelperPlugin($helper); + } + ); } if ($container->has(TemplateRendererInterface::class)) { - $pluginManager->setFactory('template', function (ContainerInterface $container) { - return new TemplatePlugin($container->get(TemplateRendererInterface::class)); - }); + $pluginManager->setFactory( + 'template', + static function (ContainerInterface $container): TemplatePlugin { + $renderer = $container->get(TemplateRendererInterface::class); + return new TemplatePlugin($renderer); + } + ); } return $pluginManager; diff --git a/src/Plugin/PluginManager.php b/src/Plugin/PluginManager.php index 32d1aff..f6db6bd 100644 --- a/src/Plugin/PluginManager.php +++ b/src/Plugin/PluginManager.php @@ -4,30 +4,176 @@ namespace Dot\Controller\Plugin; -use Laminas\ServiceManager\AbstractPluginManager; -use Laminas\ServiceManager\Exception\InvalidServiceException; +use Dot\Controller\Exception\InvalidArgumentException; +use Dot\Controller\Exception\InvalidPluginException; +use Dot\Controller\Exception\PluginNotFoundException; +use Psr\Container\ContainerInterface; -use function gettype; -use function is_object; +use function array_diff; +use function array_keys; +use function class_exists; +use function implode; +use function is_array; +use function is_callable; +use function is_string; use function sprintf; /** - * @template InstanceType - * @extends AbstractPluginManager + * A PSR-11 container for controller plugins. + * + * It supports the "factories" and "aliases" keys of the "dot_controller.plugin_manager" config. + * A factory receives the application container, the plugin name and the build options. */ -class PluginManager extends AbstractPluginManager +class PluginManager implements ContainerInterface { - protected string $instanceOf = PluginInterface::class; + private const SUPPORTED_KEYS = ['factories', 'aliases']; - public function validate(mixed $instance): void + /** @var array */ + private array $factories = []; + + /** @var array */ + private array $aliases = []; + + /** @var array */ + private array $instances = []; + + /** + * @param array $config + * @throws InvalidArgumentException + */ + public function __construct( + private readonly ContainerInterface $container, + array $config = [], + ) { + $unsupported = array_diff(array_keys($config), self::SUPPORTED_KEYS); + if ($unsupported !== []) { + throw new InvalidArgumentException(sprintf( + 'The controller plugin manager supports only the keys "%s". Remove the keys "%s".', + implode('", "', self::SUPPORTED_KEYS), + implode('", "', $unsupported) + )); + } + + foreach ($this->readMap($config, 'factories') as $name => $factory) { + if (! is_callable($factory) && ! is_string($factory)) { + throw InvalidPluginException::fromFactory($name, $factory); + } + $this->setFactory($name, $factory); + } + + foreach ($this->readMap($config, 'aliases') as $alias => $target) { + if (! is_string($target)) { + throw new InvalidArgumentException(sprintf( + 'The alias "%s" of the controller plugin manager must point to a plugin name.', + $alias + )); + } + $this->setAlias($alias, $target); + } + } + + public function setFactory(string $name, callable|string $factory): void + { + $this->factories[$name] = $factory; + unset($this->instances[$name]); + } + + public function setAlias(string $alias, string $target): void + { + $this->aliases[$alias] = $target; + } + + public function has(string $id): bool + { + return isset($this->factories[$this->resolveName($id)]); + } + + /** + * Return the shared instance of a plugin. Create it on the first call. + * + * @throws PluginNotFoundException + * @throws InvalidPluginException + */ + public function get(string $id): PluginInterface + { + $name = $this->resolveName($id); + + return $this->instances[$name] ??= $this->build($name); + } + + /** + * Create a new instance of a plugin on each call. + * + * @param array $options + * @throws PluginNotFoundException + * @throws InvalidPluginException + */ + public function build(string $name, array $options = []): PluginInterface { - if (! $instance instanceof $this->instanceOf) { - throw new InvalidServiceException(sprintf( - '%s can only create instances of %s; %s is invalid', - static::class, - $this->instanceOf, - is_object($instance) ? $instance::class : gettype($instance) + $name = $this->resolveName($name); + $factory = $this->factories[$name] ?? throw PluginNotFoundException::fromName($name); + + if (is_string($factory) && ! is_callable($factory)) { + if (! class_exists($factory)) { + throw InvalidPluginException::fromFactory($name, $factory); + } + $factory = new $factory(); + } + + if (! is_callable($factory)) { + throw InvalidPluginException::fromFactory($name, $factory); + } + + $plugin = $factory($this->container, $name, $options); + if (! $plugin instanceof PluginInterface) { + throw InvalidPluginException::fromInstance($name, $plugin); + } + + return $plugin; + } + + /** + * Follow the aliases until a name without an alias is found. + * + * @throws InvalidArgumentException + */ + private function resolveName(string $name): string + { + $visited = []; + while (isset($this->aliases[$name])) { + if (isset($visited[$name])) { + throw new InvalidArgumentException(sprintf( + 'The alias "%s" of the controller plugin manager is part of a cycle.', + $name + )); + } + $visited[$name] = true; + $name = $this->aliases[$name]; + } + + return $name; + } + + /** + * @param array $config + * @return array + * @throws InvalidArgumentException + */ + private function readMap(array $config, string $key): array + { + $map = $config[$key] ?? []; + if (! is_array($map)) { + throw new InvalidArgumentException(sprintf( + 'The "%s" key of the controller plugin manager must be an array.', + $key )); } + + $result = []; + foreach ($map as $name => $value) { + $result[(string) $name] = $value; + } + + return $result; } } diff --git a/src/Plugin/PluginManagerAwareInterface.php b/src/Plugin/PluginManagerAwareInterface.php index 4a96489..2d47cac 100644 --- a/src/Plugin/PluginManagerAwareInterface.php +++ b/src/Plugin/PluginManagerAwareInterface.php @@ -8,5 +8,5 @@ interface PluginManagerAwareInterface { public function setPluginManager(PluginManager $plugins): void; - public function getPluginManager(): ?PluginManager; + public function getPluginManager(): PluginManager; } diff --git a/src/Plugin/TemplatePlugin.php b/src/Plugin/TemplatePlugin.php index 816f1ad..eb69965 100644 --- a/src/Plugin/TemplatePlugin.php +++ b/src/Plugin/TemplatePlugin.php @@ -6,32 +6,40 @@ use Mezzio\Template\TemplateRendererInterface; -use function func_get_args; - class TemplatePlugin implements PluginInterface { - protected TemplateRendererInterface $template; - - public function __construct(TemplateRendererInterface $template) - { - $this->template = $template; + public function __construct( + protected TemplateRendererInterface $template + ) { } - public function __invoke(?string $templateName = null, array $params = []): self|string + /** + * Without a template name, return the plugin. Otherwise, render the template. + * + * @param array|object $params + */ + public function __invoke(?string $templateName = null, array|object $params = []): self|string { - $args = func_get_args(); - if (empty($args)) { + if ($templateName === null || $templateName === '') { return $this; } return $this->render($templateName, $params); } - public function render(string $templateName, array $params = []): string + /** + * @param non-empty-string $templateName + * @param array|object $params + */ + public function render(string $templateName, array|object $params = []): string { return $this->template->render($templateName, $params); } + /** + * @param non-empty-string $templateName + * @param non-empty-string $param + */ public function addDefaultParam(string $templateName, string $param, mixed $value): void { $this->template->addDefaultParam($templateName, $param, $value); diff --git a/src/Plugin/UrlHelperPlugin.php b/src/Plugin/UrlHelperPlugin.php index e3b2e41..9bca1ea 100644 --- a/src/Plugin/UrlHelperPlugin.php +++ b/src/Plugin/UrlHelperPlugin.php @@ -6,37 +6,49 @@ use Mezzio\Helper\UrlHelper; -use function func_get_args; +use function func_num_args; class UrlHelperPlugin implements PluginInterface { - protected UrlHelper $urlHelper; - - public function __construct(UrlHelper $helper) - { - $this->urlHelper = $helper; + public function __construct( + protected UrlHelper $urlHelper + ) { } + /** + * Without arguments, return the plugin. Otherwise, generate a URL. + * A null route name means the route that matched the current request. + * + * @param non-empty-string|null $routeName + * @param array $routeParams + * @param array $queryParams + * @param array $options + */ public function __invoke( ?string $routeName = null, array $routeParams = [], array $queryParams = [], - mixed $fragmentIdentifier = null, + ?string $fragmentIdentifier = null, array $options = [] ): self|string { - $args = func_get_args(); - if (empty($args)) { + if (func_num_args() === 0) { return $this; } return $this->generate($routeName, $routeParams, $queryParams, $fragmentIdentifier, $options); } + /** + * @param non-empty-string|null $routeName + * @param array $routeParams + * @param array $queryParams + * @param array $options + */ public function generate( ?string $routeName = null, array $routeParams = [], array $queryParams = [], - mixed $fragmentIdentifier = null, + ?string $fragmentIdentifier = null, array $options = [] ): string { return $this->urlHelper->generate($routeName, $routeParams, $queryParams, $fragmentIdentifier, $options); diff --git a/test/AbstractActionControllerTest.php b/test/AbstractActionControllerTest.php index 831e888..a9ffe69 100644 --- a/test/AbstractActionControllerTest.php +++ b/test/AbstractActionControllerTest.php @@ -4,51 +4,153 @@ namespace DotTest\Controller; -use Dot\Controller\AbstractActionController; -use Laminas\Diactoros\Response; -use PHPUnit\Framework\MockObject\Exception; +use Dot\Controller\Event\ControllerEvent; +use DotTest\Controller\Fixture\PassThroughHandler; +use DotTest\Controller\Fixture\TestController; +use Laminas\Diactoros\Response\TextResponse; +use Laminas\Diactoros\ServerRequest; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; -use Psr\Http\Server\RequestHandlerInterface; class AbstractActionControllerTest extends TestCase { - /** - * @throws Exception - */ - public function testNonExistingActionWillReturnResponse(): void + private TestController $controller; + private PassThroughHandler $handler; + + protected function setUp(): void + { + $this->controller = new TestController(); + $this->handler = new PassThroughHandler(); + } + + public function testMissingActionCallsTheNextHandler(): void { - $request = $this->createMock(ServerRequestInterface::class); - $handler = $this->createMock(RequestHandlerInterface::class); + $response = $this->controller->process($this->request('missing'), $this->handler); - $request->expects($this->any())->method('getAttribute')->withAnyParameters()->willReturn('test'); + $this->assertSame(404, $response->getStatusCode()); + $this->assertSame(1, $this->handler->calls); + $this->assertSame([], $this->controller->calledActions); + } - $subject = new class extends AbstractActionController { - }; + public function testExistingActionReturnsItsResponse(): void + { + $response = $this->controller->process($this->request('Foo-Bar'), $this->handler); - $response = $subject->process($request, $handler); - $this->assertContainsOnlyInstancesOf(ResponseInterface::class, [$response]); + $this->assertSame('fooBar', (string) $response->getBody()); + $this->assertSame(0, $this->handler->calls); } /** - * @throws Exception + * @return iterable */ - public function testExistingActionWillReturnResponse(): void + public static function defaultActionProvider(): iterable + { + yield 'null' => [null]; + yield 'empty' => ['']; + yield 'whitespace' => [' ']; + yield 'integer' => [5]; + } + + #[DataProvider('defaultActionProvider')] + public function testInvalidOrEmptyActionUsesIndex(mixed $action): void + { + $response = $this->controller->process($this->request($action), $this->handler); + + $this->assertSame('index', (string) $response->getBody()); + } + + public function testMissingActionAttributeUsesIndex(): void + { + $response = $this->controller->process(new ServerRequest(), $this->handler); + + $this->assertSame('index', (string) $response->getBody()); + } + + public function testZeroActionIsNotTreatedAsEmpty(): void + { + $response = $this->controller->process($this->request('0'), $this->handler); + + $this->assertSame(404, $response->getStatusCode()); + $this->assertSame([], $this->controller->calledActions); + } + + public function testBeforeDispatchListenerResponseStopsTheAction(): void { - $request = $this->createMock(ServerRequestInterface::class); - $handler = $this->createMock(RequestHandlerInterface::class); + $this->controller->getEventManager()->attach( + ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH, + static fn (): TextResponse => new TextResponse('denied', 403) + ); - $request->expects($this->any())->method('getAttribute')->withAnyParameters()->willReturn('index'); + $response = $this->controller->process($this->request('index'), $this->handler); - $subject = new class extends AbstractActionController { - public function indexAction(): ResponseInterface - { - return new Response(); + $this->assertSame(403, $response->getStatusCode()); + $this->assertSame([], $this->controller->calledActions); + } + + public function testAfterDispatchListenerResponseReplacesTheActionResponse(): void + { + $this->controller->getEventManager()->attach( + ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH, + static fn (): TextResponse => new TextResponse('replaced', 202) + ); + + $response = $this->controller->process($this->request('index'), $this->handler); + + $this->assertSame(202, $response->getStatusCode()); + $this->assertSame(['index'], $this->controller->calledActions); + } + + public function testListenerReturnValueThatIsNotAResponseIsIgnored(): void + { + $this->controller->getEventManager()->attach( + ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH, + static fn (): string => 'not a response' + ); + + $response = $this->controller->process($this->request('index'), $this->handler); + + $this->assertSame('index', (string) $response->getBody()); + } + + public function testBeforeDispatchListenerCanReplaceTheRequest(): void + { + $this->controller->getEventManager()->attach( + ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH, + static function (ControllerEvent $event): void { + $request = $event->getParam('request'); + if ($request instanceof ServerRequestInterface) { + $event->setParam('request', $request->withAttribute('fromListener', true)); + } } - }; + ); + + $response = $this->controller->process($this->request('request-attribute'), $this->handler); + + $this->assertSame('changed', (string) $response->getBody()); + } - $response = $subject->process($request, $handler); - $this->assertContainsOnlyInstancesOf(ResponseInterface::class, [$response]); + public function testAfterDispatchEventHoldsTheBeforeParamsAndTheResponse(): void + { + $params = []; + $this->controller->getEventManager()->attach( + ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH, + static function (ControllerEvent $event) use (&$params): void { + $params = $event->getParams(); + } + ); + + $this->controller->process($this->request('index'), $this->handler); + + $this->assertIsArray($params); + $this->assertSame('indexAction', $params['method']); + $this->assertSame($this->controller, $params['controller']); + $this->assertSame($this->handler, $params['handler']); + $this->assertInstanceOf(TextResponse::class, $params['response']); + } + + private function request(mixed $action): ServerRequestInterface + { + return (new ServerRequest())->withAttribute('action', $action); } } diff --git a/test/AbstractControllerTest.php b/test/AbstractControllerTest.php index 3498e42..ec1a0e9 100644 --- a/test/AbstractControllerTest.php +++ b/test/AbstractControllerTest.php @@ -4,131 +4,101 @@ namespace DotTest\Controller; -use Dot\Controller\AbstractController as Subject; +use Dot\Controller\Exception\PluginNotFoundException; use Dot\Controller\Exception\RuntimeException; -use Dot\Controller\Plugin\PluginInterface; use Dot\Controller\Plugin\PluginManager; -use Laminas\Diactoros\Response; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use DotTest\Controller\Fixture\InMemoryContainer; +use DotTest\Controller\Fixture\PassThroughHandler; +use DotTest\Controller\Fixture\PlainPlugin; +use DotTest\Controller\Fixture\StringPluginFactory; +use DotTest\Controller\Fixture\TestController; +use Laminas\Diactoros\ServerRequest; use PHPUnit\Framework\TestCase; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\ServerRequestInterface; -use Psr\Http\Server\RequestHandlerInterface; class AbstractControllerTest extends TestCase { - private PluginManager|MockObject $pluginManager; - private PluginInterface|MockObject $plugin; - private ServerRequestInterface|MockObject $request; - private RequestHandlerInterface|MockObject $handler; - private Subject $subject; - - /** - * @throws Exception - */ - public function setUp(): void + private TestController $controller; + private PluginManager $pluginManager; + + protected function setUp(): void { - $this->pluginManager = $this->createMock(PluginManager::class); - $this->plugin = $this->createMock(PluginInterface::class); - $this->request = $this->createMock(ServerRequestInterface::class); - $this->handler = $this->createMock(RequestHandlerInterface::class); - $this->subject = new class extends Subject { - public function dispatch(): ResponseInterface - { - return new Response(); - } - }; + $this->pluginManager = new PluginManager(new InMemoryContainer(), [ + 'factories' => [ + 'string' => StringPluginFactory::class, + 'plain' => static fn (): PlainPlugin => new PlainPlugin(), + ], + ]); + $this->controller = new TestController(); } public function testGetMethodFromAction(): void { - $testAction = 'test.this-action_name'; - $method = Subject::getMethodFromAction($testAction); - $this->assertSame('testThisActionNameAction', $method); + $this->assertSame('testThisActionNameAction', TestController::getMethodFromAction('test.this-action_name')); } public function testGetPluginManager(): void { - $this->subject->setPluginManager($this->pluginManager); - $this->assertInstanceOf(PluginManager::class, $this->subject->getPluginManager()); + $this->controller->setPluginManager($this->pluginManager); + + $this->assertSame($this->pluginManager, $this->controller->getPluginManager()); } public function testNoPluginManager(): void { $this->expectException(RuntimeException::class); - $this->subject->getPluginManager(); + $this->expectExceptionMessage('Controller plugin manager not set'); + + $this->controller->getPluginManager(); + } + + public function testProcessStoresTheRequestAndTheHandler(): void + { + $request = new ServerRequest(); + $handler = new PassThroughHandler(); + + $this->controller->process($request, $handler); + + $this->assertSame($request, $this->controller->getRequest()); + $this->assertSame($handler, $this->controller->getHandler()); } - public function testGetRequest(): void + public function testDebug(): void { - $this->subject->process($this->request, $this->handler); - $this->assertSame($this->request, $this->subject->getRequest()); + $this->assertFalse($this->controller->isDebug()); + + $this->controller->setDebug(true); + + $this->assertTrue($this->controller->isDebug()); } - public function testGetHandler(): void + public function testPluginCreatesANewInstanceOnEachCall(): void { - $this->subject->process($this->request, $this->handler); - $this->assertSame($this->handler, $this->subject->getHandler()); + $this->controller->setPluginManager($this->pluginManager); + + $this->assertNotSame($this->controller->plugin('plain'), $this->controller->plugin('plain')); } - public function testDebug(): void + public function testMagicCallReturnsAPluginThatIsNotInvokable(): void { - $this->assertFalse($this->subject->isDebug()); + $this->controller->setPluginManager($this->pluginManager); - $this->subject->setDebug(true); - $this->assertTrue($this->subject->isDebug()); + $this->assertInstanceOf(PlainPlugin::class, $this->controller->__call('plain', [])); } - public function testCallPlugin(): void + public function testMagicCallInvokesAnInvokablePlugin(): void { - $this->pluginManager->expects($this->once()) - ->method('build') - ->with('somePlugin') - ->willReturn($this->plugin); - - $controller = new class ($this->pluginManager) extends Subject { - public function __construct(PluginManager $pluginManager) - { - $this->pluginManager = $pluginManager; - } - - public function dispatch(): ResponseInterface - { - return new Response(); - } - }; - - $plugin = $controller->somePlugin(); - - $this->assertInstanceOf(PluginInterface::class, $plugin); + $this->controller->setPluginManager($this->pluginManager); + + $this->assertSame('TEST', $this->controller->__call('string', ['test'])); } - public function testCallCallablePlugin(): void + public function testMagicCallWithAnUnknownPluginThrows(): void { - $mockCallablePlugin = function ($param) { - return "Mock plugin called with parameter: $param"; - }; - - $this->pluginManager->expects($this->once()) - ->method('build') - ->with('callablePlugin') - ->willReturn($mockCallablePlugin); - - $this->subject = new class ($this->pluginManager) extends Subject { - public function __construct(PluginManager $pluginManager) - { - $this->pluginManager = $pluginManager; - } - - public function dispatch(): ResponseInterface - { - return new Response(); - } - }; - - $result = $this->subject->callablePlugin('paramValue'); - - $this->assertSame('Mock plugin called with parameter: paramValue', $result); + $this->controller->setPluginManager($this->pluginManager); + + $this->expectException(PluginNotFoundException::class); + $this->expectExceptionMessage('Controller plugin "unknown" is not registered.'); + + $this->controller->__call('unknown', []); } } diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index ddb9290..eaed0b9 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -7,42 +7,25 @@ use Dot\Controller\ConfigProvider; use Dot\Controller\Factory\ControllerEventListenersInitializer; use Dot\Controller\Factory\PluginManagerAwareInitializer; +use Dot\Controller\Factory\PluginManagerFactory; use Dot\Controller\Plugin\PluginManager; use PHPUnit\Framework\TestCase; class ConfigProviderTest extends TestCase { - protected array $config; - - protected function setup(): void + public function testConfigHasTheExpectedKeys(): void { - $this->config = (new ConfigProvider())(); - } - - public function testHasDependencies(): void - { - $this->assertArrayHasKey('dependencies', $this->config); - $this->assertArrayHasKey('dot_controller', $this->config); - $this->assertArrayHasKey('plugin_manager', $this->config['dot_controller']); - $this->assertArrayHasKey('event_listeners', $this->config['dot_controller']); - } + $config = (new ConfigProvider())(); - public function testDependenciesHasFactories(): void - { - $this->assertArrayHasKey('factories', $this->config['dependencies']); - $this->assertArrayHasKey(PluginManager::class, $this->config['dependencies']['factories']); - } - - public function testDependenciesHasInitializers(): void - { - $this->assertArrayHasKey('initializers', $this->config['dependencies']); - $this->assertContainsEquals( - PluginManagerAwareInitializer::class, - $this->config['dependencies']['initializers'] + $this->assertSame([], $config['dot_controller']['plugin_manager']); + $this->assertSame([], $config['dot_controller']['event_listeners']); + $this->assertSame( + PluginManagerFactory::class, + $config['dependencies']['factories'][PluginManager::class] ); - $this->assertContainsEquals( - ControllerEventListenersInitializer::class, - $this->config['dependencies']['initializers'] + $this->assertSame( + [PluginManagerAwareInitializer::class, ControllerEventListenersInitializer::class], + $config['dependencies']['initializers'] ); } } diff --git a/test/Event/ControllerEventListenerTraitTest.php b/test/Event/ControllerEventListenerTraitTest.php index 5f5c557..0c380d9 100644 --- a/test/Event/ControllerEventListenerTraitTest.php +++ b/test/Event/ControllerEventListenerTraitTest.php @@ -5,68 +5,58 @@ namespace DotTest\Controller\Event; use Dot\Controller\Event\ControllerEvent; -use Dot\Controller\Event\ControllerEventListenerTrait as Subject; -use Laminas\EventManager\EventManagerInterface; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Controller\Fixture\TestListener; +use Laminas\EventManager\EventManager; use PHPUnit\Framework\TestCase; -use function is_callable; - class ControllerEventListenerTraitTest extends TestCase { - private object $traitObject; - - /** - * @throws Exception - */ protected function setUp(): void { - $eventManager = $this->createMock(EventManagerInterface::class); - - $this->traitObject = new class ($eventManager) { - use Subject; + TestListener::reset(); + } - private EventManagerInterface $eventManager; + public function testAttachListensToBothControllerEvents(): void + { + $events = new EventManager(); + (new TestListener())->attach($events); - public function __construct(EventManagerInterface $eventManager) - { - $this->eventManager = $eventManager; - } + $events->triggerEvent(new ControllerEvent( + ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH, + null, + ['method' => 'indexAction'] + )); + $events->triggerEvent(new ControllerEvent(ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH)); - public function getEventManager(): EventManagerInterface - { - return $this->eventManager; - } - }; + $this->assertSame(['before:indexAction', 'after'], TestListener::$log); } - public function testAttach(): void + public function testDetachRemovesTheListeners(): void { - $eventManager = $this->traitObject->getEventManager(); + $events = new EventManager(); + $listener = new TestListener(); + $listener->attach($events); + $listener->detach($events); + + $events->triggerEvent(new ControllerEvent(ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH)); - $eventManager->expects($this->exactly(2)) - ->method('attach') - ->willReturnMap([ - [ - ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH, - $this->callback(function ($callback) { - return is_callable($callback) - && $callback[0] === $this->traitObject - && $callback[1] === 'onBeforeDispatch'; - }), - 1, - ], - [ - ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH, - $this->callback(function ($callback) { - return is_callable($callback) - && $callback[0] === $this->traitObject - && $callback[1] === 'onAfterDispatch'; - }), - 1, - ], - ]); + $this->assertSame([], TestListener::$log); + } - $this->traitObject->attach($eventManager); + public function testPriorityOrdersTheListeners(): void + { + $events = new EventManager(); + $events->attach( + ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH, + static function (): void { + TestListener::$log[] = 'low'; + }, + 1 + ); + (new TestListener())->attach($events, 10); + + $events->triggerEvent(new ControllerEvent(ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH)); + + $this->assertSame(['after', 'low'], TestListener::$log); } } diff --git a/test/Event/DispatchControllerEventsTraitTest.php b/test/Event/DispatchControllerEventsTraitTest.php index 67b6620..3cbd470 100644 --- a/test/Event/DispatchControllerEventsTraitTest.php +++ b/test/Event/DispatchControllerEventsTraitTest.php @@ -4,76 +4,79 @@ namespace DotTest\Controller\Event; -use Dot\Controller\AbstractController; use Dot\Controller\Event\ControllerEvent; -use Dot\Controller\Event\DispatchControllerEventsTrait as Subject; +use Dot\Controller\Event\DispatchControllerEventsTrait; use Dot\Controller\Exception\RuntimeException; -use Laminas\Diactoros\Response; +use DotTest\Controller\Fixture\TestController; +use Laminas\Diactoros\Response\TextResponse; use PHPUnit\Framework\TestCase; -use Psr\Http\Message\ResponseInterface; use stdClass; class DispatchControllerEventsTraitTest extends TestCase { - private AbstractController $subject; + private TestController $controller; protected function setUp(): void { - $this->subject = new class extends AbstractController { - use Subject; - - public function dispatch(): ResponseInterface - { - return new Response(); - } - }; + $this->controller = new TestController(); } - public function testInvalidControllerDispatch(): void + public function testOnlyControllersCanDispatch(): void { - $eventName = 'test.event.name'; - - $data = ['key' => 'value']; - - $invalidController = new class { - use Subject; + $plainObject = new class { + use DispatchControllerEventsTrait; }; $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Only controllers can dispatch controller events'); - $invalidController->dispatchEvent($eventName, ['data' => $data]); + $plainObject->dispatchEvent('test.event.name'); } public function testDispatchWithDefaultTarget(): void { - $eventName = 'test.event.name'; - - $data = ['key' => 'value']; - - $result = $this->subject->dispatchEvent($eventName, ['data' => $data]); + $result = $this->controller->dispatchEvent('test.event.name', ['key' => 'value']); $this->assertInstanceOf(ControllerEvent::class, $result); - - $this->assertSame($eventName, $result->getName()); - $this->assertSame($this->subject, $result->getTarget()); - $this->assertSame($data, $result->getParam('data')); + $this->assertSame('test.event.name', $result->getName()); + $this->assertSame($this->controller, $result->getTarget()); + $this->assertSame('value', $result->getParam('key')); } - public function testDispatchEventWithExplicitTarget(): void + public function testDispatchWithExplicitTarget(): void { - $eventName = 'test.event.name'; + $target = new stdClass(); - $data = ['key' => 'value']; + $result = $this->controller->dispatchEvent('test.event.name', [], $target); - $targetObject = new stdClass(); + $this->assertInstanceOf(ControllerEvent::class, $result); + $this->assertSame($target, $result->getTarget()); + } - $result = $this->subject->dispatchEvent($eventName, ['data' => $data], $targetObject); + public function testListenerResponseIsReturnedAndStopsTheOtherListeners(): void + { + $response = new TextResponse('stop'); + $calls = 0; + $events = $this->controller->getEventManager(); + $events->attach('test.event.name', static fn (): TextResponse => $response, 10); + $events->attach( + 'test.event.name', + static function () use (&$calls): void { + $calls++; + }, + 1 + ); + + $result = $this->controller->dispatchEvent('test.event.name'); + + $this->assertSame($response, $result); + $this->assertSame(0, $calls); + } - $this->assertInstanceOf(ControllerEvent::class, $result); + public function testListenerReturnValueThatIsNotAResponseReturnsTheEvent(): void + { + $this->controller->getEventManager()->attach('test.event.name', static fn (): string => 'value'); - $this->assertSame($eventName, $result->getName()); - $this->assertSame($targetObject, $result->getTarget()); - $this->assertSame($data, $result->getParam('data')); + $this->assertInstanceOf(ControllerEvent::class, $this->controller->dispatchEvent('test.event.name')); } } diff --git a/test/Factory/ControllerEventListenersInitializerTest.php b/test/Factory/ControllerEventListenersInitializerTest.php index 358120a..b9b2555 100644 --- a/test/Factory/ControllerEventListenersInitializerTest.php +++ b/test/Factory/ControllerEventListenersInitializerTest.php @@ -4,75 +4,159 @@ namespace DotTest\Controller\Factory; -use Dot\Controller\AbstractController; +use Dot\Controller\Event\ControllerEvent; use Dot\Controller\Event\ControllerEventListenerInterface; -use Dot\Controller\Factory\ControllerEventListenersInitializer as Subject; -use Laminas\EventManager\EventManager; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use Dot\Controller\Exception\RuntimeException; +use Dot\Controller\Factory\ControllerEventListenersInitializer; +use DotTest\Controller\Fixture\InMemoryContainer; +use DotTest\Controller\Fixture\TestController; +use DotTest\Controller\Fixture\TestListener; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; +use stdClass; class ControllerEventListenersInitializerTest extends TestCase { - private ContainerInterface|MockObject $container; - private AbstractController|MockObject $controller; - private EventManager|MockObject $eventManager; - private Subject $subject; + private ControllerEventListenersInitializer $initializer; + private TestController $controller; - /** - * @throws Exception - */ - public function setUp(): void + protected function setUp(): void { - $this->container = $this->createMock(ContainerInterface::class); - $this->controller = $this->createMock(AbstractController::class); - $this->eventManager = $this->createMock(EventManager::class); - $this->subject = new Subject(); + TestListener::reset(); + $this->initializer = new ControllerEventListenersInitializer(); + $this->controller = new TestController(); } - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws Exception - */ - public function testAttachControllerListeners(): void + public function testAttachesAListenerGivenAsClassName(): void + { + $this->initialize([TestController::class => [TestListener::class]]); + + $this->assertSame(['before:indexAction', 'after'], $this->dispatch()); + } + + public function testAttachesAListenerGivenWithTypeAndPriority(): void { - $config = [ - 'dot_controller' => [ - 'event_listeners' => [ - AbstractController::class => [ - [ - 'type' => 'ListenerClass1', - 'priority' => 10, - ], - 'ListenerClass2', - ], - ], - ], - ]; - $this->container->method('get')->with('config')->willReturn($config); - - $this->container->method('has')->willReturnMap([ - ['ListenerClass1', true], - ['ListenerClass2', true], + $this->initialize([TestController::class => [['type' => TestListener::class, 'priority' => '10']]]); + $this->controller->getEventManager()->attach( + ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH, + static function (): void { + TestListener::$log[] = 'low'; + }, + 1 + ); + + $this->assertSame(['before:indexAction', 'after', 'low'], $this->dispatch()); + } + + public function testAttachesAListenerFromTheContainer(): void + { + $container = new InMemoryContainer([ + 'config' => ['dot_controller' => ['event_listeners' => [TestController::class => ['listener']]]], + 'listener' => new TestListener(), ]); - $this->container->method('get')->willReturnMap([ - ['ListenerClass1', $this->createMock(ControllerEventListenerInterface::class)], - ['ListenerClass2', $this->createMock(ControllerEventListenerInterface::class)], + ($this->initializer)($container, $this->controller); + + $this->assertSame(['before:indexAction', 'after'], $this->dispatch()); + } + + public function testListenAllAttachesToEachController(): void + { + $this->initialize([ControllerEventListenerInterface::LISTEN_ALL => [TestListener::class]]); + + $this->assertSame(['before:indexAction', 'after'], $this->dispatch()); + } + + public function testIgnoresListenersOfOtherControllers(): void + { + $this->initialize([stdClass::class => [TestListener::class]]); + + $this->assertSame([], $this->dispatch()); + } + + public function testIgnoresInstancesThatAreNotControllers(): void + { + $container = new InMemoryContainer(); + + ($this->initializer)($container, new stdClass()); + + $this->assertSame([], $this->dispatch()); + } + + public function testConfigWithoutTheControllerKeyAttachesNothing(): void + { + ($this->initializer)(new InMemoryContainer(['config' => []]), $this->controller); + ($this->initializer)(new InMemoryContainer(), $this->controller); + + $this->assertSame([], $this->dispatch()); + } + + public function testInvalidListenerListsAreSkipped(): void + { + ($this->initializer)( + new InMemoryContainer(['config' => ['dot_controller' => ['event_listeners' => 'invalid']]]), + $this->controller + ); + $this->initialize([TestController::class => 'invalid']); + + $this->assertSame([], $this->dispatch()); + } + + public function testEntryWithoutAValidTypeThrows(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('must name a listener class or service, int given'); + + $this->initialize([TestController::class => [['type' => 5]]]); + } + + public function testEntryWithAnInvalidPriorityThrows(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('must be an integer, array given'); + + $this->initialize([TestController::class => [['type' => TestListener::class, 'priority' => []]]]); + } + + public function testUnknownListenerThrows(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('but string was provided'); + + $this->initialize([TestController::class => ['UnknownListener']]); + } + + public function testListenerOfTheWrongTypeThrows(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('but stdClass was provided'); + + $this->initialize([TestController::class => [stdClass::class]]); + } + + /** + * @param array $listeners + */ + private function initialize(array $listeners): void + { + $container = new InMemoryContainer([ + 'config' => ['dot_controller' => ['event_listeners' => $listeners]], ]); - $this->controller->method('getEventManager')->willReturn($this->eventManager); + $this->initializer->attachControllerListeners($container, $this->controller); + } - $this->eventManager->expects($this->any())->method('attach') - ->with($this->isInstanceOf(ControllerEventListenerInterface::class), 10); - $this->eventManager->expects($this->any())->method('attach') - ->with($this->isInstanceOf(ControllerEventListenerInterface::class), 1); + /** + * @return list + */ + private function dispatch(): array + { + $before = $this->controller->dispatchEvent( + ControllerEvent::EVENT_CONTROLLER_BEFORE_DISPATCH, + ['method' => 'indexAction'] + ); + $this->assertInstanceOf(ControllerEvent::class, $before); + $this->controller->dispatchEvent(ControllerEvent::EVENT_CONTROLLER_AFTER_DISPATCH); - $this->expectNotToPerformAssertions(); - $this->subject->attachControllerListeners($this->container, $this->controller); + return TestListener::$log; } } diff --git a/test/Factory/PluginManagerAwareInitializerTest.php b/test/Factory/PluginManagerAwareInitializerTest.php index bab017c..cd47790 100644 --- a/test/Factory/PluginManagerAwareInitializerTest.php +++ b/test/Factory/PluginManagerAwareInitializerTest.php @@ -4,77 +4,87 @@ namespace DotTest\Controller\Factory; -use Dot\Controller\AbstractController; -use Dot\Controller\Factory\PluginManagerAwareInitializer as Subject; +use Dot\Controller\Factory\PluginManagerAwareInitializer; use Dot\Controller\Plugin\PluginManager; -use Dot\Controller\Plugin\PluginManagerAwareInterface; -use Laminas\Diactoros\Response; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use DotTest\Controller\Fixture\InMemoryContainer; +use DotTest\Controller\Fixture\TestController; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; -use Psr\Http\Message\ResponseInterface; +use stdClass; class PluginManagerAwareInitializerTest extends TestCase { - private Subject $subject; - private ContainerInterface|MockObject $container; - private PluginManager|MockObject $pluginManager; + private PluginManagerAwareInitializer $initializer; - /** - * @throws Exception - */ - public function setUp(): void + protected function setUp(): void + { + $this->initializer = new PluginManagerAwareInitializer(); + } + + public function testSetsThePluginManager(): void { - $this->subject = new Subject(); - $this->container = $this->createMock(ContainerInterface::class); - $this->pluginManager = $this->createMock(PluginManager::class); + $container = new InMemoryContainer(); + $pluginManager = new PluginManager($container); + $container->set(PluginManager::class, $pluginManager); + $controller = new TestController(); + + ($this->initializer)($container, $controller); + + $this->assertSame($pluginManager, $controller->getPluginManager()); } /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @throws Exception + * @return iterable */ - public function testInvokeSetsPluginManagerWhenInstanceIsPluginManagerAwareInterface(): void + public static function debugProvider(): iterable { - $this->container->expects($this->once()) - ->method('get') - ->with(PluginManager::class) - ->willReturn($this->pluginManager); + yield 'true' => [true, true]; + yield 'int 1' => [1, true]; + yield 'string 1' => ['1', true]; + yield 'string true' => ['true', true]; + yield 'false' => [false, false]; + yield 'int 0' => [0, false]; + yield 'string false' => ['false', false]; + yield 'null' => [null, false]; + } - $instance = $this->createMock(PluginManagerAwareInterface::class); + #[DataProvider('debugProvider')] + public function testSetsTheDebugFlag(mixed $debug, bool $expected): void + { + $container = $this->container(['debug' => $debug]); + $controller = new TestController(); - $instance->expects($this->once()) - ->method('setPluginManager') - ->with($this->equalTo($this->pluginManager)); + ($this->initializer)($container, $controller); - $this->subject->__invoke($this->container, $instance); + $this->assertSame($expected, $controller->isDebug()); + } + + public function testMissingDebugKeyMeansFalse(): void + { + $controller = new TestController(); + $controller->setDebug(true); + + ($this->initializer)($this->container([]), $controller); + + $this->assertFalse($controller->isDebug()); + } + + public function testIgnoresOtherInstances(): void + { + $this->expectNotToPerformAssertions(); + + ($this->initializer)(new InMemoryContainer(), new stdClass()); + ($this->initializer)(new InMemoryContainer()); } /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface + * @param array $config */ - public function testInvokeSetsDebugFlagWhenInstanceIsAbstractController(): void + private function container(array $config): InMemoryContainer { - $this->container->method('get') - ->willReturnMap([ - [PluginManager::class, $this->pluginManager], - ['config', ['debug' => true]], - ]); - - $instance = new class extends AbstractController { - public function dispatch(): ResponseInterface - { - return new Response(); - } - }; - - $this->subject->__invoke($this->container, $instance); - - $this->assertTrue($instance->isDebug()); + $container = new InMemoryContainer(['config' => $config]); + $container->set(PluginManager::class, new PluginManager($container)); + + return $container; } } diff --git a/test/Factory/PluginManagerFactoryTest.php b/test/Factory/PluginManagerFactoryTest.php index 1d3c2b1..449cfaa 100644 --- a/test/Factory/PluginManagerFactoryTest.php +++ b/test/Factory/PluginManagerFactoryTest.php @@ -4,96 +4,72 @@ namespace DotTest\Controller\Factory; -use Dot\Controller\Factory\PluginManagerFactory as Subject; -use Dot\Controller\Plugin\PluginManager; +use Dot\Controller\Exception\InvalidArgumentException; +use Dot\Controller\Factory\PluginManagerFactory; use Dot\Controller\Plugin\TemplatePlugin; use Dot\Controller\Plugin\UrlHelperPlugin; +use DotTest\Controller\Fixture\InMemoryContainer; +use DotTest\Controller\Fixture\StringPlugin; +use DotTest\Controller\Fixture\StringPluginFactory; use Mezzio\Helper\UrlHelper; use Mezzio\Template\TemplateRendererInterface; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; class PluginManagerFactoryTest extends TestCase { - private Subject $subject; - private ContainerInterface|MockObject $container; - private TemplateRendererInterface|MockObject $templateRenderer; - private UrlHelper|MockObject $urlHelper; - - /** - * @throws Exception - */ - public function setUp(): void + public function testRegistersTheUrlPluginWhenTheHelperIsPresent(): void { - $this->subject = new Subject(); - $this->container = $this->createMock(ContainerInterface::class); - $this->templateRenderer = $this->createMock(TemplateRendererInterface::class); - $this->urlHelper = $this->createMock(UrlHelper::class); + $container = new InMemoryContainer([UrlHelper::class => $this->createStub(UrlHelper::class)]); + + $pluginManager = (new PluginManagerFactory())($container); + + $this->assertInstanceOf(UrlHelperPlugin::class, $pluginManager->get('url')); + $this->assertFalse($pluginManager->has('template')); } - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testInvokeWithUrlHelper(): void + public function testRegistersTheTemplatePluginWhenTheRendererIsPresent(): void { - $config = [ - 'dot_controller' => [ - 'plugin_manager' => [], - ], - ]; - - $this->container->method('has')->willReturnMap([ - [UrlHelper::class, true], - [TemplateRendererInterface::class, false], + $container = new InMemoryContainer([ + TemplateRendererInterface::class => $this->createStub(TemplateRendererInterface::class), ]); - $this->container->method('get')->willReturnMap([ - [TemplateRendererInterface::class, $this->templateRenderer], - [UrlHelper::class, $this->urlHelper], - ['config', $config], - ]); + $pluginManager = (new PluginManagerFactory())($container); - $pluginManager = $this->subject->__invoke($this->container); + $this->assertInstanceOf(TemplatePlugin::class, $pluginManager->get('template')); + $this->assertFalse($pluginManager->has('url')); + } - $this->assertContainsOnlyInstancesOf(PluginManager::class, [$pluginManager]); - $this->assertTrue($pluginManager->has('url')); + public function testRegistersNoBuiltInPluginWithoutTheServices(): void + { + $pluginManager = (new PluginManagerFactory())(new InMemoryContainer()); + + $this->assertFalse($pluginManager->has('url')); $this->assertFalse($pluginManager->has('template')); - $this->assertInstanceOf(UrlHelperPlugin::class, $pluginManager->get('url')); } - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testInvokeWithTemplateRenderer(): void + public function testRegistersThePluginsFromTheConfig(): void { - $config = [ - 'dot_controller' => [ - 'plugin_manager' => [], + $container = new InMemoryContainer([ + 'config' => [ + 'dot_controller' => [ + 'plugin_manager' => ['factories' => ['string' => StringPluginFactory::class]], + ], ], - ]; - - $this->container->method('has')->willReturnMap([ - [UrlHelper::class, false], - [TemplateRendererInterface::class, true], ]); - $this->container->method('get')->willReturnMap([ - [TemplateRendererInterface::class, $this->templateRenderer], - [UrlHelper::class, $this->urlHelper], - ['config', $config], + $pluginManager = (new PluginManagerFactory())($container); + + $this->assertInstanceOf(StringPlugin::class, $pluginManager->get('string')); + } + + public function testInvalidPluginManagerConfigThrows(): void + { + $container = new InMemoryContainer([ + 'config' => ['dot_controller' => ['plugin_manager' => 'invalid']], ]); - $pluginManager = $this->subject->__invoke($this->container); + $this->expectException(InvalidArgumentException::class); - $this->assertContainsOnlyInstancesOf(PluginManager::class, [$pluginManager]); - $this->assertTrue($pluginManager->has('template')); - $this->assertFalse($pluginManager->has('url')); - $this->assertInstanceOf(TemplatePlugin::class, $pluginManager->get('template')); + (new PluginManagerFactory())($container); } } diff --git a/test/Fixture/ContainerErrorException.php b/test/Fixture/ContainerErrorException.php new file mode 100644 index 0000000..ffc639b --- /dev/null +++ b/test/Fixture/ContainerErrorException.php @@ -0,0 +1,19 @@ + $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::fromId($id); + } + + $service = $this->services[$id]; + if (! $service instanceof Closure) { + return $service; + } + + try { + return $service($this); + } catch (Throwable $exception) { + throw ContainerErrorException::fromPrevious($id, $exception); + } + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services); + } +} diff --git a/test/Fixture/PassThroughHandler.php b/test/Fixture/PassThroughHandler.php new file mode 100644 index 0000000..c690ed0 --- /dev/null +++ b/test/Fixture/PassThroughHandler.php @@ -0,0 +1,25 @@ +calls++; + + return new TextResponse('next', 404); + } +} diff --git a/test/Fixture/PlainPlugin.php b/test/Fixture/PlainPlugin.php new file mode 100644 index 0000000..8fdf6be --- /dev/null +++ b/test/Fixture/PlainPlugin.php @@ -0,0 +1,18 @@ + $options + */ + public function __construct( + public readonly array $options = [], + ) { + } +} diff --git a/test/Fixture/ServiceNotFoundException.php b/test/Fixture/ServiceNotFoundException.php new file mode 100644 index 0000000..e170f04 --- /dev/null +++ b/test/Fixture/ServiceNotFoundException.php @@ -0,0 +1,18 @@ + */ + public array $calledActions = []; + + public function indexAction(): ResponseInterface + { + $this->calledActions[] = 'index'; + + return new TextResponse('index'); + } + + public function fooBarAction(): ResponseInterface + { + $this->calledActions[] = 'fooBar'; + + return new TextResponse('fooBar'); + } + + public function requestAttributeAction(): ResponseInterface + { + $this->calledActions[] = 'requestAttribute'; + + $value = $this->getRequest()->getAttribute('fromListener'); + + return new TextResponse($value === null ? 'none' : 'changed'); + } +} diff --git a/test/Fixture/TestListener.php b/test/Fixture/TestListener.php new file mode 100644 index 0000000..b381ae8 --- /dev/null +++ b/test/Fixture/TestListener.php @@ -0,0 +1,38 @@ + */ + public static array $log = []; + + public static function reset(): void + { + self::$log = []; + } + + /** + * @param ControllerEvent> $e + */ + public function onBeforeDispatch(ControllerEvent $e): void + { + $method = $e->getParam('method'); + self::$log[] = 'before:' . (is_string($method) ? $method : ''); + } + + /** + * @param ControllerEvent> $e + */ + public function onAfterDispatch(ControllerEvent $e): void + { + self::$log[] = 'after'; + } +} diff --git a/test/Plugin/PluginManagerTest.php b/test/Plugin/PluginManagerTest.php index 9d2429f..7259d00 100644 --- a/test/Plugin/PluginManagerTest.php +++ b/test/Plugin/PluginManagerTest.php @@ -4,46 +4,179 @@ namespace DotTest\Controller\Plugin; -use Dot\Controller\Plugin\PluginInterface; -use Dot\Controller\Plugin\PluginManager as Subject; -use Laminas\ServiceManager\Exception\InvalidServiceException; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use Dot\Controller\Exception\InvalidArgumentException; +use Dot\Controller\Exception\InvalidPluginException; +use Dot\Controller\Plugin\PluginManager; +use DotTest\Controller\Fixture\InMemoryContainer; +use DotTest\Controller\Fixture\PlainPlugin; +use DotTest\Controller\Fixture\StringPlugin; +use DotTest\Controller\Fixture\StringPluginFactory; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; +use Psr\Container\NotFoundExceptionInterface; +use stdClass; class PluginManagerTest extends TestCase { - protected ContainerInterface|MockObject $container; - protected Subject $subject; + private InMemoryContainer $container; - /** - * @throws Exception - */ - protected function setup(): void + protected function setUp(): void { - $this->container = $this->createMock(ContainerInterface::class); - $this->subject = new Subject($this->container); + $this->container = new InMemoryContainer(); } - /** - * @throws ContainerExceptionInterface - * @throws Exception - */ - public function testInstanceOf(): void + public function testBuildsAPluginFromAFactoryClassName(): void { - $plugin = $this->createMock(PluginInterface::class); - $this->expectNotToPerformAssertions(); - $this->subject->validate($plugin); + $pluginManager = new PluginManager($this->container, [ + 'factories' => ['string' => StringPluginFactory::class], + ]); + + $this->assertTrue($pluginManager->has('string')); + $this->assertInstanceOf(StringPlugin::class, $pluginManager->build('string')); + } + + public function testCallsTheFactoryWithTheContainerTheNameAndTheOptions(): void + { + $arguments = []; + $pluginManager = new PluginManager($this->container); + $pluginManager->setFactory( + 'plain', + static function ( + ContainerInterface $container, + string $name, + array $options + ) use (&$arguments): PlainPlugin { + $arguments = [$container, $name]; + + return new PlainPlugin($options); + } + ); + + $plugin = $pluginManager->build('plain', ['key' => 'value']); + + $this->assertInstanceOf(PlainPlugin::class, $plugin); + $this->assertSame(['key' => 'value'], $plugin->options); + $this->assertSame([$this->container, 'plain'], $arguments); + } + + public function testGetSharesAndBuildCreates(): void + { + $pluginManager = new PluginManager($this->container, [ + 'factories' => ['plain' => static fn (): PlainPlugin => new PlainPlugin()], + ]); + + $this->assertSame($pluginManager->get('plain'), $pluginManager->get('plain')); + $this->assertNotSame($pluginManager->build('plain'), $pluginManager->build('plain')); + } + + public function testSetFactoryReplacesTheSharedInstance(): void + { + $pluginManager = new PluginManager($this->container, [ + 'factories' => ['plain' => static fn (): PlainPlugin => new PlainPlugin()], + ]); + $first = $pluginManager->get('plain'); + + $pluginManager->setFactory('plain', static fn (): PlainPlugin => new PlainPlugin()); + + $this->assertNotSame($first, $pluginManager->get('plain')); + } + + public function testResolvesAliases(): void + { + $pluginManager = new PluginManager($this->container, [ + 'factories' => ['string' => StringPluginFactory::class], + 'aliases' => ['text' => 'str', 'str' => 'string'], + ]); + + $this->assertTrue($pluginManager->has('text')); + $this->assertSame($pluginManager->get('text'), $pluginManager->get('string')); + } + + public function testAliasCycleThrows(): void + { + $pluginManager = new PluginManager($this->container, [ + 'aliases' => ['a' => 'b', 'b' => 'a'], + ]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('is part of a cycle'); + + $pluginManager->has('a'); + } + + public function testUnknownPluginThrowsANotFoundException(): void + { + $pluginManager = new PluginManager($this->container); + + $this->assertFalse($pluginManager->has('unknown')); + $this->expectException(NotFoundExceptionInterface::class); + $this->expectExceptionMessage('Controller plugin "unknown" is not registered.'); + + $pluginManager->get('unknown'); + } + + public function testPluginOfTheWrongTypeThrows(): void + { + $pluginManager = new PluginManager($this->container); + $pluginManager->setFactory('invalid', static fn (): stdClass => new stdClass()); + + $this->expectException(InvalidPluginException::class); + $this->expectExceptionMessage('must implement Dot\Controller\Plugin\PluginInterface, stdClass given'); + + $pluginManager->build('invalid'); } - /** - * @throws ContainerExceptionInterface - */ - public function testInvalidInstanceOf(): void + public function testFactoryClassThatDoesNotExistThrows(): void { - $this->expectException(InvalidServiceException::class); - $this->subject->validate('invalidPlugin'); + $pluginManager = new PluginManager($this->container, [ + 'factories' => ['missing' => 'Missing\Factory'], + ]); + + $this->expectException(InvalidPluginException::class); + + $pluginManager->build('missing'); + } + + public function testFactoryClassThatIsNotInvokableThrows(): void + { + $pluginManager = new PluginManager($this->container, [ + 'factories' => ['plain' => stdClass::class], + ]); + + $this->expectException(InvalidPluginException::class); + $this->expectExceptionMessage('must be callable or the name of an invokable class, stdClass given'); + + $pluginManager->build('plain'); + } + + public function testFactoryOfTheWrongTypeThrows(): void + { + $this->expectException(InvalidPluginException::class); + + new PluginManager($this->container, ['factories' => ['plain' => 5]]); + } + + public function testUnsupportedConfigKeyThrows(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Remove the keys "invokables", "delegators".'); + + new PluginManager($this->container, ['factories' => [], 'invokables' => [], 'delegators' => []]); + } + + public function testConfigKeyThatIsNotAnArrayThrows(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The "aliases" key of the controller plugin manager must be an array.'); + + new PluginManager($this->container, ['aliases' => 'invalid']); + } + + public function testAliasTargetThatIsNotAStringThrows(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The alias "a" of the controller plugin manager must point to a plugin name.'); + + new PluginManager($this->container, ['aliases' => ['a' => 5]]); } } diff --git a/test/Plugin/TemplatePluginTest.php b/test/Plugin/TemplatePluginTest.php index e3cdbe6..9e55eb6 100644 --- a/test/Plugin/TemplatePluginTest.php +++ b/test/Plugin/TemplatePluginTest.php @@ -4,73 +4,52 @@ namespace DotTest\Controller\Plugin; -use Dot\Controller\Plugin\TemplatePlugin as Subject; +use Dot\Controller\Plugin\TemplatePlugin; use Mezzio\Template\TemplateRendererInterface; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use stdClass; class TemplatePluginTest extends TestCase { - protected TemplateRendererInterface|MockObject $templateRenderer; - protected Subject $subject; - - /** - * @throws Exception - */ - protected function setup(): void + public function testInvokeWithoutArgumentsReturnsThePlugin(): void { - $this->templateRenderer = $this->createMock(TemplateRendererInterface::class); - $this->subject = new Subject($this->templateRenderer); - } + $plugin = new TemplatePlugin($this->createStub(TemplateRendererInterface::class)); - public function testInvokeWithoutArguments(): void - { - $result = $this->subject->__invoke(); - - $this->assertInstanceOf(Subject::class, $result); + $this->assertSame($plugin, $plugin()); + $this->assertSame($plugin, $plugin(null)); + $this->assertSame($plugin, $plugin('')); } - public function testInvokeWithArguments(): void + public function testInvokeWithANameRendersTheTemplate(): void { - $templateName = 'test-template'; - $params = ['param1' => 'value1', 'param2' => 'value2']; - - $this->templateRenderer->expects($this->once()) + $renderer = $this->createMock(TemplateRendererInterface::class); + $renderer->expects($this->once()) ->method('render') - ->with($templateName, $params) - ->willReturn('Test content'); + ->with('test::template', ['key' => 'value']) + ->willReturn('content'); - $result = $this->subject->__invoke($templateName, $params); - - $this->assertSame('Test content', $result); + $this->assertSame('content', (new TemplatePlugin($renderer))('test::template', ['key' => 'value'])); } - public function testRender(): void + public function testRenderAcceptsAnObject(): void { - $templateName = 'test-template'; - $params = ['param1' => 'value1', 'param2' => 'value2']; - - $this->templateRenderer->expects($this->once()) + $params = new stdClass(); + $renderer = $this->createMock(TemplateRendererInterface::class); + $renderer->expects($this->once()) ->method('render') - ->with($templateName, $params) - ->willReturn('Test content'); + ->with('test::template', $params) + ->willReturn('content'); - $result = $this->subject->render($templateName, $params); - - $this->assertSame('Test content', $result); + $this->assertSame('content', (new TemplatePlugin($renderer))->render('test::template', $params)); } public function testAddDefaultParam(): void { - $templateName = 'test-template'; - $param = 'defaultParam'; - $value = 'defaultValue'; - - $this->templateRenderer->expects($this->once()) + $renderer = $this->createMock(TemplateRendererInterface::class); + $renderer->expects($this->once()) ->method('addDefaultParam') - ->with($templateName, $param, $value); + ->with('test::template', 'key', 'value'); - $this->subject->addDefaultParam($templateName, $param, $value); + (new TemplatePlugin($renderer))->addDefaultParam('test::template', 'key', 'value'); } } diff --git a/test/Plugin/UrlHelperPluginTest.php b/test/Plugin/UrlHelperPluginTest.php index 718efe7..75661c3 100644 --- a/test/Plugin/UrlHelperPluginTest.php +++ b/test/Plugin/UrlHelperPluginTest.php @@ -4,66 +4,57 @@ namespace DotTest\Controller\Plugin; -use Dot\Controller\Plugin\UrlHelperPlugin as Subject; +use Dot\Controller\Plugin\UrlHelperPlugin; use Mezzio\Helper\UrlHelper; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; class UrlHelperPluginTest extends TestCase { - private UrlHelper|MockObject $urlHelper; - private Subject $subject; - - /** - * @throws Exception - */ - public function setUp(): void + public function testInvokeWithoutArgumentsReturnsThePlugin(): void { - $this->urlHelper = $this->createMock(UrlHelper::class); - $this->subject = new Subject($this->urlHelper); + $plugin = new UrlHelperPlugin($this->createStub(UrlHelper::class)); + + $this->assertSame($plugin, $plugin()); } - public function testInvokeWithoutArguments(): void + public function testInvokeWithArgumentsGeneratesTheUrl(): void { - $result = $this->subject->__invoke(); - - $this->assertInstanceOf(Subject::class, $result); + $helper = $this->createMock(UrlHelper::class); + $helper->expects($this->once()) + ->method('generate') + ->with('test.route', ['id' => 123], ['sort' => 'asc'], 'section', ['reuse_result_params' => false]) + ->willReturn('/test/123?sort=asc#section'); + + $result = (new UrlHelperPlugin($helper))( + 'test.route', + ['id' => 123], + ['sort' => 'asc'], + 'section', + ['reuse_result_params' => false] + ); + + $this->assertSame('/test/123?sort=asc#section', $result); } - public function testInvokeWithArguments(): void + public function testNullRouteNameMeansTheCurrentRoute(): void { - $routeName = 'test.route'; - $routeParams = ['id' => 123]; - $queryParams = ['sort' => 'asc']; - $fragmentIdentifier = 'section'; - $options = ['absolute' => true]; - - $this->urlHelper->expects($this->once()) + $helper = $this->createMock(UrlHelper::class); + $helper->expects($this->once()) ->method('generate') - ->with($routeName, $routeParams, $queryParams, $fragmentIdentifier, $options) - ->willReturn('https://example.com/test-route?id=123&sort=asc#section'); - - $result = $this->subject->__invoke($routeName, $routeParams, $queryParams, $fragmentIdentifier, $options); + ->with(null, ['id' => 5], [], null, []) + ->willReturn('/current/5'); - $this->assertSame('https://example.com/test-route?id=123&sort=asc#section', $result); + $this->assertSame('/current/5', (new UrlHelperPlugin($helper))(null, ['id' => 5])); } public function testGenerate(): void { - $routeName = 'test.route'; - $routeParams = ['id' => 123]; - $queryParams = ['sort' => 'asc']; - $fragmentIdentifier = 'section'; - $options = ['absolute' => true]; - - $this->urlHelper->expects($this->once()) + $helper = $this->createMock(UrlHelper::class); + $helper->expects($this->once()) ->method('generate') - ->with($routeName, $routeParams, $queryParams, $fragmentIdentifier, $options) - ->willReturn('https://example.com/test-route?id=123&sort=asc#section'); - - $result = $this->subject->generate($routeName, $routeParams, $queryParams, $fragmentIdentifier, $options); + ->with('test.route', [], [], null, []) + ->willReturn('/test'); - $this->assertSame('https://example.com/test-route?id=123&sort=asc#section', $result); + $this->assertSame('/test', (new UrlHelperPlugin($helper))->generate('test.route')); } }