From cc6a1274af9c75f15815aa0426d05db362f97f5e Mon Sep 17 00:00:00 2001 From: bidi Date: Wed, 25 Nov 2026 15:42:00 +0200 Subject: [PATCH] code refactor, updated composer, docs, workflow, tests Signed-off-by: bidi --- .github/workflows/codecov.yml | 8 +- .github/workflows/static-analysis.yml | 12 +- .gitignore | 1 + .laminas-ci.json | 3 + CHANGELOG.md | 240 +++++++-- README.md | 73 ++- SECURITY.md | 1 + composer.json | 13 +- config/autoload/navigation.global.php.dist | 2 +- docs/book/v5/components.md | 38 ++ docs/book/v5/configuration.md | 9 + docs/book/v5/container-providers.md | 66 +++ docs/book/v5/installation.md | 20 + docs/book/v5/navigation-renderer.md | 48 ++ docs/book/v5/overview.md | 17 + docs/book/v5/required-page-options.md | 25 + docs/book/v5/upgrading.md | 43 ++ docs/book/v5/usage.md | 73 +++ mkdocs.yml | 13 +- phpstan.neon | 2 +- phpunit.xml | 17 +- src/ConfigProvider.php | 6 + src/Factory/NavigationMiddlewareFactory.php | 6 +- src/Factory/NavigationOptionsFactory.php | 11 +- src/Factory/NavigationRendererFactory.php | 10 +- src/Factory/NavigationServiceFactory.php | 10 +- src/Factory/ProviderPluginManagerFactory.php | 13 +- src/Filter/IsAllowedFilter.php | 26 +- src/NavigationContainer.php | 80 ++- src/NavigationMiddleware.php | 1 + src/Options/NavigationOptions.php | 13 +- src/Page.php | 23 +- src/Provider/ArrayProvider.php | 30 +- src/Provider/Factory.php | 16 +- src/Provider/FactoryInterface.php | 3 + src/Provider/InvokableProviderFactory.php | 35 ++ src/Provider/ProviderPluginManager.php | 66 ++- src/Service/Navigation.php | 148 ++++-- src/Service/NavigationInterface.php | 13 + src/View/AbstractNavigationRenderer.php | 14 +- src/View/NavigationRenderer.php | 17 + src/View/RendererInterface.php | 18 + test/ConfigProviderTest.php | 1 + .../NavigationMiddlewareFactoryTest.php | 41 +- test/Factory/NavigationOptionsFactoryTest.php | 72 +-- .../Factory/NavigationRendererFactoryTest.php | 75 +-- test/Factory/NavigationServiceFactoryTest.php | 117 ++--- .../ProviderPluginManagerFactoryTest.php | 102 ++-- test/Filter/IsAllowedFilterTest.php | 125 ++--- test/NavigationContainerTest.php | 62 ++- test/NavigationMiddlewareTest.php | 36 +- test/Options/NavigationOptionsTest.php | 2 +- test/PageTest.php | 12 + test/Provider/ArrayProviderTest.php | 51 +- test/Provider/FactoryTest.php | 115 ++--- test/Provider/ProviderPluginManagerTest.php | 119 +++++ test/Service/NavigationTest.php | 456 +++++++++--------- test/TestData/Container.php | 38 ++ test/TestData/CustomProvider.php | 19 + test/TestData/ServiceNotFoundException.php | 12 + test/View/NavigationRendererTest.php | 100 ++-- 61 files changed, 1896 insertions(+), 942 deletions(-) create mode 100644 docs/book/v5/components.md create mode 100644 docs/book/v5/configuration.md create mode 100644 docs/book/v5/container-providers.md create mode 100644 docs/book/v5/installation.md create mode 100644 docs/book/v5/navigation-renderer.md create mode 100644 docs/book/v5/overview.md create mode 100644 docs/book/v5/required-page-options.md create mode 100644 docs/book/v5/upgrading.md create mode 100644 docs/book/v5/usage.md create mode 100644 src/Provider/InvokableProviderFactory.php create mode 100644 test/Provider/ProviderPluginManagerTest.php create mode 100644 test/TestData/Container.php create mode 100644 test/TestData/CustomProvider.php create mode 100644 test/TestData/ServiceNotFoundException.php diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index c0fbc53..9652006 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') }} @@ -50,6 +50,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..ab8e910 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -4,7 +4,7 @@ on: name: Run PHPStan checks jobs: - mutation: + phpstan: name: PHPStan ${{ matrix.php }}-${{ matrix.os }} runs-on: ${{ matrix.os }} @@ -15,20 +15,20 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 with: php-version: "${{ matrix.php }}" - coverage: pcov + coverage: none ini-values: assert.exception=1, zend.assertions=1, error_reporting=-1, log_errors_max_len=0, display_errors=On tools: composer:v2, cs2pr @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -47,4 +47,4 @@ jobs: run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi - name: Run static analysis with PHPStan - run: vendor/bin/phpstan analyse + run: vendor/bin/phpstan analyse --memory-limit 1G diff --git a/.gitignore b/.gitignore index 4d3fdcb..49bb1b5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ clover.xml coveralls-upload.json .phpcs-cache +.phpunit.cache .phpunit.result.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 a08dda1..f62a1ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,130 +1,294 @@ +# Changelog + +## 5.0.0 - TBD + +### Added + +- PHP 8.6 support. +- `NavigationInterface::setQueryParams()`. `NavigationMiddleware` sets the query parameters of the request. +- `NavigationContainer::hasPages()`. +- `Dot\Navigation\Provider\InvokableProviderFactory`. + +### Changed + +- `ProviderPluginManager` is a plain class and supports only the `factories` and `aliases` config keys. +- The factories throw `Dot\Navigation\Exception\RuntimeException` in place of `\Exception`. +- `IsAllowedFilter` is `final`. +- `NavigationContainer::current()` and `getChildren()` return `Page`. +- `render()` and `renderPartial()` throw `InvalidArgumentException` for an empty template name. +- `Navigation::isAllowed()` accepts a string `roles` option as one role. +- Documented the value rules of `htmlAttributes()`. Its output does not change. +- Allowed `mezzio/mezzio-template` 3.x. +- Declared the packages that the code uses directly: `laminas/laminas-stdlib`, `mezzio/mezzio-router`, `psr/container` and `psr/http-server-handler`. +- PHPStan level 8. PHPUnit 12. + +### Deprecated + +- Nothing. + +### Removed + +- PHP 8.2 support. +- The `laminas/laminas-servicemanager` requirement. + +### Fixed + +- `isActive()` compares the keys of the parameters, not only the values. +- `isActive()` uses the query of the request, not `$_GET`. +- `setRouteResult()` clears the active and href caches. +- A parent page without a `route` option is active when a sub-page is active. +- `getPartial()` returns `null` before `setPartial()`. +- `Page::getName()` and `getHref()` accept int names and the URI `"0"`. +- Invalid config gives a package exception, not a PHP warning or a `TypeError`. + +## 4.2.0 - 2025-10-31 + +### Changed + +- Removed PHP 8.1 support and added PHP 8.4 and 8.5 support. + +## 4.1.0 - 2025-03-06 + +### Changed + +- Replaced Psalm with PHPStan. + +## 4.0.3 - 2025-01-30 + +### Fixed + +- Fixed mixed up messages in `NavigationServiceFactory`. + +## 4.0.2 - 2025-01-28 + +### Changed + +- Bumped Psalm to 6.x. + +### Fixed + +- Fixed `.laminas-ci.json`. + +## 4.0.1 - 2025-01-20 + +### Fixed + +- Fixed the documentation and the static analysis badge. + +## 4.0.0 - 2025-01-20 + +### Added + +- Support for `laminas/laminas-servicemanager` 4.x. +- Documentation for v4. + +## 3.6.0 - 2025-11-17 + +### Changed + +- Removed PHP 8.1 support and added PHP 8.4 and 8.5 support. + +## 3.5.1 - 2024-07-31 + +### Changed + +- Bumped the minimum version of `dotkernel/dot-helpers` to 3.5.1. + +## 3.5.0 - 2024-05-03 + +### Added + +- Documentation. + +## 3.4.2 - 2023-11-30 + +### Fixed + +- Added a missing annotation. + +## 3.4.1 - 2023-08-22 + +### Added + +- Codecov. + +### Fixed + +- Added the missing static analysis badge and two missing return types. + +## 3.4.0 - 2023-07-20 + +### Changed + +- Code quality. + +## 3.3.0 - 2023-03-29 + +### Removed + +- `laminas/laminas-dependency-plugin`. + +## 3.2.0 - 2022-05-03 + +### Changed + +- Updated `composer.json`, the README and `OSSMETADATA`. + ## 3.1.0 - 2020-11-03 ### Changed -* Composer 2 compatibility. -* Update composer.json to require version 2 of laminas/laminas-dependency-plugin to be Composer 2 compatible. + +- Composer 2 compatibility. +- Update composer.json to require version 2 of laminas/laminas-dependency-plugin to be Composer 2 compatible. ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* bump min version of laminas/laminas-dependency-plugin -* bump min version of dotkernel/dot-helpers + +- bump min version of laminas/laminas-dependency-plugin +- bump min version of dotkernel/dot-helpers ## 2.0.0 - 2020-01-30 ### Changed -* Laminas and Mezzio migration. + +- Laminas and Mezzio migration. ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Support + +- Support ### Fixed -* Nothing +- Nothing ## 1.0.0 - 2018-05-15 Migration to Zend Expressive 3 ### Changed -* Middleware changed from `http-interop/http-middleware` to `psr/http-server-middleware` + +- Middleware changed from `http-interop/http-middleware` to `psr/http-server-middleware` ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* nothing +- nothing ## 0.2.1 - 2017-03-22 ### Changed -* Nothing + +- Nothing ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* navigation service getHref error when using page option `uri` +- navigation service getHref error when using page option `uri` ## 0.2.0 - 2017-03-17 Migration to ZE2 ### Changed -* updated dependencies -* updated to PSR11 container -* updated middleware to PSR15 -* changed the way menu item route is configured, to support new UrlHelper options + +- updated dependencies +- updated to PSR11 container +- updated middleware to PSR15 +- changed the way menu item route is configured, to support new UrlHelper options ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing +- Nothing ## 0.1.1 - 2017-03-11 Updated php file headers doc blocks ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing +- Nothing ## 0.1.0 - 2017-03-09 Initial tagged release ### Added -* Everything + +- Everything ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing diff --git a/README.md b/README.md index 0986b4c..c45c614 100644 --- a/README.md +++ b/README.md @@ -9,79 +9,78 @@ Documentation is available at: https://docs.dotkernel.org/dot-navigation/. ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-navigation) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-navigation/4.2.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-navigation/5.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-navigation)](https://github.com/dotkernel/dot-navigation/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-navigation)](https://github.com/dotkernel/dot-navigation/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-navigation)](https://github.com/dotkernel/dot-navigation/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-navigation)](https://github.com/dotkernel/dot-navigation/blob/4.0/LICENSE.md) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-navigation)](https://github.com/dotkernel/dot-navigation/blob/5.0/LICENSE.md) -[![Build Static](https://github.com/dotkernel/dot-navigation/actions/workflows/continuous-integration.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-navigation/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-navigation/actions/workflows/continuous-integration.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-navigation/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-navigation/graph/badge.svg?token=AI9WFYDDX9)](https://codecov.io/gh/dotkernel/dot-navigation) -[![PHPStan](https://github.com/dotkernel/dot-navigation/actions/workflows/static-analysis.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-navigation/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-navigation/actions/workflows/static-analysis.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-navigation/actions/workflows/static-analysis.yml) ## Installation -Install `dotkernel/dot-navigation` by executing the following Composer command: +Install `dotkernel/dot-navigation` with this Composer command: ```shell composer require dotkernel/dot-navigation ``` -Merge `ConfigProvider` to your application's configuration. +Add `Dot\Navigation\ConfigProvider` to the configuration of your application. -> The package uses dot-helpers package, please merge dot-helpers `ConfigProvider` to your application's configuration also, if it's not merged already! +> The package uses dot-helpers. Also add the `ConfigProvider` of dot-helpers to the configuration of your application, if it is not there. -Register `NavigationMiddleware` in your middleware pipe between the routing and the dispatching middleware. +Add `NavigationMiddleware` to the middleware pipeline, after the routing middleware and before the dispatch middleware. + +The factories use only `Psr\Container\ContainerInterface`, so they work with each PSR-11 container that accepts a factory for each service name. +The package does not require `laminas/laminas-servicemanager`. If your application uses it, require it in your application. ## Configuration -Locate dot-navigation's distributable config file `vendor/dotkernel/dot-navigation/config/autoload/navigation.global.php.dist` and duplicate it in your project as `config/autoload/navigation.global.php` +Copy the configuration file `vendor/dotkernel/dot-navigation/config/autoload/navigation.global.php.dist` to `config/autoload/navigation.global.php` in your project. ## Components -A menu, or navigation container, is a class implementing the `RecursiveIterator` interface. -It has a hierarchical structure, with nodes called pages (see the `Page` class) that may have children. It is basically a tree - -A Page extends the NavigationContainer class. The NavigationContainer is the top most node which represents the entire menu. -The children of this node are Page instances that define each navigation item. +A menu, or navigation container, is an instance of `NavigationContainer`. It implements `RecursiveIterator`. +It is a tree, and its nodes are pages (see the `Page` class). A page can have sub-pages. -A page has a reference to its parent and can have options and attributes. There is no limitation on what is accepted as options or attributes. +`Page` extends `NavigationContainer`. The container is the top node, and it represents the full menu. +`hasPages()` and `hasChildren()` tell if a container or a page has sub-pages. -Options can be any piece of information that describes a page. -Some predefined options exist in order for the navigation module to work seamlessly with other dot modules. +A page has a parent, options and attributes. +Options describe the page, for example its label, link and permission. +Attributes are key-value pairs. A template usually writes them as HTML attributes. -Attributes are key value pairs that define the menu item. -They are usually inserted as HTML attributes when parsing the menu, but of course, this is implementation-specific. - -A `NavigationService` class, is the service that handles all defined menu containers. -It can fetch the container from its provider, check if a page is active or not, and get the page's generated URI. +The `Navigation` service (`Dot\Navigation\Service\Navigation`) handles all menu containers. +It loads a container from its provider. It tells if a page is allowed or active, and it makes the URI of a page. ## Container providers -Each menu can be created from different sources. The responsibility of creating a menu container from the source falls on a container provider. +A container provider makes a menu container from a source. Each provider implements `ProviderInterface`. -Each provider must implement the interface `ProviderInterface` and be registered in the ProviderPluginManager. +The package has one provider, `ArrayProvider`. It makes a menu container from a PHP array in the configuration file. -We offer just one provider for now, `ArrayProvider`, that is able to fetch and create a menu container from a php array that is defined in the configuration file. +To add a provider, register its factory in the `provider_manager` configuration key. This key supports `factories` and `aliases`. +For a provider that needs no services, use `Dot\Navigation\Provider\InvokableProviderFactory`. ## NavigationRenderer -Used to render the navigation container in a displayable format. -It can render a simple HTML unordered list or use a partial template to render the menu in a template engine. - -The partial method is usually the more flexible one, custom rules can be defined and checked in the template. +The renderer renders a navigation container with a template. +`render()` and `renderPartial()` give the template the container, the navigation service and the extra parameters. -If you are using Twig, there is already a Twig extension provided in package dot-twigrenderer that you can use to easily parse the menus inside your templates +If you use Twig, the package dot-twigrenderer has a Twig extension for menus. -When using the partial method, the template will receive as parameters the container, the navigation service, and any extra parameters set by the developer. +Templates refer to a navigation container by its name in the configuration file. -Navigation containers are referred to, when parsed, by their name, as defined in the configuration file. +`htmlAttributes()` writes the attributes of a page as HTML attributes. Each value must be a string or a list of strings. +Other value types throw a `TypeError`. Write a number or a boolean as a string, for example `'tabindex' => '0'`. -## Required page options and attributes +## Page options -The following are options that each page should define in the configuration +Each page can have these options: -* `label` - the text of the menu item -* `route` or `uri` - defines the route or link the menu item will have -* `permission` - can be used optionally if authorization service is present, to omit menu items that are not authorized to visit. +- `label` - the text of the menu item +- `route` or `uri` - the route or the link of the menu item +- `permission` - optional. If an authorization service is in the container, the page shows only when the user has this permission diff --git a/SECURITY.md b/SECURITY.md index 04274c2..b59f03e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,6 +4,7 @@ | Version | Supported | PHP Version | |---------|--------------------|----------------------------------------------------------------------------------------------------------------| +| 5.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-navigation/5.0.0) | | 4.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-navigation/4.2.0) | | 3.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-navigation/3.6.0) | | <= 2.x | :x: | | diff --git a/composer.json b/composer.json index e34d47b..a3877ad 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "dotkernel/dot-navigation", "type": "library", - "description": "Dotkernel navigation component", + "description": "Dotkernel navigation component, for any PSR-11 container", "license": "MIT", "homepage": "https://github.com/dotkernel/dot-navigation", "keywords": [ @@ -24,20 +24,23 @@ } }, "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", "dotkernel/dot-authorization": "^3.4.1", "dotkernel/dot-helpers": "^3.7.0", "laminas/laminas-escaper": "^2.13.0", - "laminas/laminas-servicemanager": "^4.0", - "mezzio/mezzio-template": "^2.9.0", + "laminas/laminas-stdlib": "^3.22", + "mezzio/mezzio-router": "^4.0", + "mezzio/mezzio-template": "^2.13.0 || ^3.1.0", + "psr/container": "^1.1 || ^2.0", "psr/http-message": "^1.0 || ^2.0", + "psr/http-server-handler": "^1.0.2", "psr/http-server-middleware": "^1.0.2" }, "require-dev": { "laminas/laminas-coding-standard": "^3.0.0", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.4.2" + "phpunit/phpunit": "^12.5.22" }, "autoload": { "psr-4": { diff --git a/config/autoload/navigation.global.php.dist b/config/autoload/navigation.global.php.dist index 9ef184e..71b6c9b 100644 --- a/config/autoload/navigation.global.php.dist +++ b/config/autoload/navigation.global.php.dist @@ -36,7 +36,7 @@ return [ 'route' => ['route_name' => 'home'/*,...*/], ], 'attributes' => [ - 'name' => 'Menu #1', + 'name' => 'Menu #2', ] ] ], diff --git a/docs/book/v5/components.md b/docs/book/v5/components.md new file mode 100644 index 0000000..2efb2a0 --- /dev/null +++ b/docs/book/v5/components.md @@ -0,0 +1,38 @@ +# Components + +## Navigation container + +A menu, or navigation container, is an instance of `Dot\Navigation\NavigationContainer`. +The container implements `RecursiveIterator`. It is a tree, and its nodes are pages (`Dot\Navigation\Page`). + +`Page` extends `NavigationContainer`, so a page can have sub-pages. +The container is the top node, and it represents the full menu. + +Use these methods to find the sub-pages: + +- `hasPages()` tells if the container or the page has sub-pages. +- `hasChildren()` gives the same result as `hasPages()`. Templates use it to show a sub-menu. +- `current()` returns the page at the current position. On an empty container, or after the last page, it throws `Dot\Navigation\Exception\RuntimeException`. +- `findOneByOption()`, `findByOption()`, `findOneByAttribute()` and `findByAttribute()` search all pages and sub-pages. + +`hasChildren()` does not follow the `RecursiveIterator` contract. It tells if the container has pages, not if the current page has sub-pages. +Because of this, `RecursiveIteratorIterator::LEAVES_ONLY` gives no pages. Use `RecursiveIteratorIterator::SELF_FIRST` or `RecursiveIteratorIterator::CHILD_FIRST`. + +```php +$iterator = new RecursiveIteratorIterator($container, RecursiveIteratorIterator::SELF_FIRST); +foreach ($iterator as $page) { + echo $page->getLabel(); +} +``` + +## Page + +A page has a parent, options and attributes. + +- Options describe the page, for example `label`, `uri`, `route` and `permission`. See [Page options](required-page-options.md). +- Attributes are key-value pairs. A template usually writes them as HTML attributes. See [Page attributes](navigation-renderer.md#page-attributes). + +## Navigation service + +The navigation service is `Dot\Navigation\Service\Navigation`. Get it from the container with `Dot\Navigation\Service\NavigationInterface`. +It loads the menu containers from their providers. It also tells if a page is allowed or active, and it makes the URI of a page. diff --git a/docs/book/v5/configuration.md b/docs/book/v5/configuration.md new file mode 100644 index 0000000..184d4c7 --- /dev/null +++ b/docs/book/v5/configuration.md @@ -0,0 +1,9 @@ +# Configuration + +After installation, add `dot-navigation` to your configuration aggregator (usually `config/config.php`): + +```php +Dot\Navigation\ConfigProvider::class, +``` + +Copy the configuration file `vendor/dotkernel/dot-navigation/config/autoload/navigation.global.php.dist` to `config/autoload/navigation.global.php` in your project. diff --git a/docs/book/v5/container-providers.md b/docs/book/v5/container-providers.md new file mode 100644 index 0000000..25a3a99 --- /dev/null +++ b/docs/book/v5/container-providers.md @@ -0,0 +1,66 @@ +# Container providers + +A container provider makes a menu container from a source. Each provider implements `Dot\Navigation\Provider\ProviderInterface`. + +The package has one provider, `Dot\Navigation\Provider\ArrayProvider`. It makes a menu container from a PHP array in the configuration. +These names select it in the `type` key of a container: `Dot\Navigation\Provider\ArrayProvider`, `ArrayProvider`, `arrayProvider`, `arrayprovider`, `Array` and `array`. + +`ArrayProvider` throws `Dot\Navigation\Exception\InvalidArgumentException` when the `attributes`, `options` or `pages` key of a page is not an array. + +## Register a custom provider + +`Dot\Navigation\Provider\ProviderPluginManager` makes the providers. Configure it in the `provider_manager` key. +It reads only two keys: + +- `factories`: a map of a provider name to a factory. The factory is a class name or a callable. +- `aliases`: a map of an alias to a provider name. + +A factory gets the PSR-11 container, the provider name and the `options` of the container config: + +```php +use Dot\Navigation\Provider\ProviderInterface; +use Psr\Container\ContainerInterface; + +class MyProviderFactory +{ + public function __invoke(ContainerInterface $container, string $requestedName, ?array $options = null): ProviderInterface + { + return new MyProvider($container->get(MyRepository::class), $options ?? []); + } +} +``` + +Register the factory and an alias in the configuration: + +```php +return [ + 'dot_navigation' => [ + 'containers' => [ + 'main' => [ + 'type' => 'my', + 'options' => [], + ], + ], + 'provider_manager' => [ + 'factories' => [ + MyProvider::class => MyProviderFactory::class, + ], + 'aliases' => [ + 'my' => MyProvider::class, + ], + ], + ], +]; +``` + +For a provider that needs no services, use `Dot\Navigation\Provider\InvokableProviderFactory`. +It calls `new $requestedName($options)`, or `new $requestedName()` when there are no options. + +```php +'factories' => [ + MySimpleProvider::class => Dot\Navigation\Provider\InvokableProviderFactory::class, +], +``` + +The plugin manager makes a new provider each time that the navigation service loads a container. +An unknown provider name, or a factory that does not return a `ProviderInterface`, throws `Dot\Navigation\Exception\RuntimeException`. diff --git a/docs/book/v5/installation.md b/docs/book/v5/installation.md new file mode 100644 index 0000000..7d5e56e --- /dev/null +++ b/docs/book/v5/installation.md @@ -0,0 +1,20 @@ +# Installation + +Install `dotkernel/dot-navigation` with this Composer command: + +```shell +composer require dotkernel/dot-navigation +``` + +Add `Dot\Navigation\ConfigProvider` to the configuration of your application. + +> The package uses `dotkernel/dot-helpers`. Also add `Dot\Helpers\ConfigProvider` to the configuration of your application, if it is not there. + +Add `Dot\Navigation\NavigationMiddleware` to the middleware pipeline, after the routing middleware and before the dispatch middleware. +The middleware gives the route result and the query parameters of the request to the navigation service. + +## Dependency injection container + +The factories of the package use only `Psr\Container\ContainerInterface`. +They work with each PSR-11 container that accepts a factory for each service name, for example Laminas Service Manager. +The package does not require `laminas/laminas-servicemanager`. If your application uses it, require it in your application. diff --git a/docs/book/v5/navigation-renderer.md b/docs/book/v5/navigation-renderer.md new file mode 100644 index 0000000..1c02d3d --- /dev/null +++ b/docs/book/v5/navigation-renderer.md @@ -0,0 +1,48 @@ +# Navigation renderer + +`Dot\Navigation\View\NavigationRenderer` renders a navigation container with a template. Get it from the container with `Dot\Navigation\View\RendererInterface`. + +- `render(string|NavigationContainer $container, string $template, array $params = [])` renders the container with a template. +- `renderPartial(string|NavigationContainer $container, string $partial, array $params = [])` does the same with a partial template. + +The first argument is the name of a container in the configuration, or a container object. +The template gets these parameters: `container`, `navigation` (the navigation service) and the keys of `$params`. +An empty template name throws `Dot\Navigation\Exception\InvalidArgumentException`. + +If you use Twig, the package `dotkernel/dot-twigrenderer` has a Twig extension for menus. +Its functions include `navigation()`, `navigationPartial()` and `pageAttributes()`. + +## Page attributes + +`htmlAttributes(array $attributes)` writes the attributes of a page as HTML attributes. The Twig function `pageAttributes(page)` calls it. + +- Each value must be a string or a list of strings. A list is joined with spaces, for example `'class' => ['nav-link', 'active']`. +- An int, float, bool or `null` value throws a `TypeError`. Write the value as a string, for example `'tabindex' => '0'` or `'aria-expanded' => 'false'`. +- For a boolean attribute, write the name as the value, for example `'hidden' => 'hidden'`. To leave the attribute out, do not add the key. +- For a key that starts with `on` and for `constraints`, an array is encoded as JSON. +- The method escapes each value. Twig does not escape the output again. Use only valid attribute names as keys, because the method does not check them. +- The method does not change an `id` value. Do not use `[` or `]` in an `id`. + +```php +$renderer->htmlAttributes(['class' => ['nav-link', 'active'], 'href' => '#']); +// ' class="nav-link active" href="#"' +``` + +The browser decodes the escaped characters, so the class is `nav-link active` and the link is `#`. + +## Show only the allowed pages + +`Dot\Navigation\Filter\IsAllowedFilter` skips each page that the user is not allowed to see, and its sub-pages. +It uses `NavigationInterface::isAllowed()`. + +```php +use Dot\Navigation\Filter\IsAllowedFilter; + +$visible = new RecursiveIteratorIterator( + new IsAllowedFilter($navigation->getContainer('default'), $navigation), + RecursiveIteratorIterator::SELF_FIRST +); +foreach ($visible as $page) { + echo $page->getLabel(); +} +``` diff --git a/docs/book/v5/overview.md b/docs/book/v5/overview.md new file mode 100644 index 0000000..8ad647a --- /dev/null +++ b/docs/book/v5/overview.md @@ -0,0 +1,17 @@ +# Overview + +`dot-navigation` is Dotkernel's component that allows you to easily define and parse menus inside templates, using a configuration based approach. + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-navigation) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-navigation/5.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-navigation)](https://github.com/dotkernel/dot-navigation/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-navigation)](https://github.com/dotkernel/dot-navigation/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-navigation)](https://github.com/dotkernel/dot-navigation/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-navigation)](https://github.com/dotkernel/dot-navigation/blob/5.0/LICENSE.md) + +[![Build Static](https://github.com/dotkernel/dot-navigation/actions/workflows/continuous-integration.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-navigation/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-navigation/graph/badge.svg?token=AI9WFYDDX9)](https://codecov.io/gh/dotkernel/dot-navigation) +[![PHPStan](https://github.com/dotkernel/dot-navigation/actions/workflows/static-analysis.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-navigation/actions/workflows/static-analysis.yml) diff --git a/docs/book/v5/required-page-options.md b/docs/book/v5/required-page-options.md new file mode 100644 index 0000000..8605f0f --- /dev/null +++ b/docs/book/v5/required-page-options.md @@ -0,0 +1,25 @@ +# Page options + +Each page can have these options: + +- `label`: the text of the menu item. Without it, `getLabel()` returns `Not defined`. +- `uri`: the link of the menu item. +- `route`: the route of the menu item. The navigation service uses it when there is no `uri`. +- `name`: an optional name. Error messages use it. +- `permission`: optional. If an authorization service is in the container, the page shows only when the user has this permission. +- `roles`: optional, used with `permission`. A string or a list of role names. + +A page needs `uri` or `route`. Without one of them, `getHref()` throws `Dot\Navigation\Exception\RuntimeException`. + +## The `route` option + +| Key | Use | +| --- | --- | +| `route_name` | the name of the route. Required | +| `route_params` | the route parameters | +| `query_params` | the query parameters | +| `fragment_id` | the fragment of the URI | +| `options` | the router options | +| `ignore_params` | a list of request parameter names that the active check does not compare. Not used to make the URI | + +See [Usage](usage.md) for the rule that makes a page active. diff --git a/docs/book/v5/upgrading.md b/docs/book/v5/upgrading.md new file mode 100644 index 0000000..61dd634 --- /dev/null +++ b/docs/book/v5/upgrading.md @@ -0,0 +1,43 @@ +# Upgrading + +## Upgrade from 4.x to 5.0 + +| Change | Symptom | Fix | +| --- | --- | --- | +| PHP 8.2 support removed | Composer cannot install 5.x on PHP 8.2 | use PHP 8.3 or higher, or stay on 4.x | +| `laminas/laminas-servicemanager` is not required | a class from Laminas Service Manager is not found | require `laminas/laminas-servicemanager` in your application if you use it | +| `ProviderPluginManager` does not extend `AbstractPluginManager` | `Call to undefined method ...ProviderPluginManager::get()` | call `build()` | +| `provider_manager` supports only `factories` and `aliases` | a provider from `invokables` is not found | register it in `factories` with `InvokableProviderFactory::class` | +| package exceptions in the provider manager | a `catch` for a Laminas exception does not run | catch `Dot\Navigation\Exception\ExceptionInterface` | +| factories throw `Dot\Navigation\Exception\RuntimeException` | a check for the exact class `Exception` fails | catch `ExceptionInterface` or `\RuntimeException` | +| `NavigationInterface::setQueryParams()` added | a custom implementation is a fatal error | add the method | +| `isActive()` uses the query of the request, not `$_GET` | a page with `query_params` is not active when the application does not use `NavigationMiddleware` | add `NavigationMiddleware` to the pipeline, or call `setQueryParams()` | +| `IsAllowedFilter` is `final` | a subclass is a fatal error | wrap the filter, do not extend it | +| `NavigationContainer::current()` and `getChildren()` return `Page`, and `current()` throws at an invalid position | a subclass that returns `NavigationContainer` is a fatal error | change the return type | +| `areParamsEqual()` compares keys | a page that was active through a value match is not active now | set the correct `route_params` or `ignore_params` | +| `render()` and `renderPartial()` reject an empty template name | `InvalidArgumentException` | give a template name | +| invalid page config throws package exceptions | `InvalidArgumentException` for a page key that is not an array, or for `roles` that are not a string or an array | correct the config | + +## Replace the Laminas plugin manager + +Before, in 4.x: + +```php +'provider_manager' => [ + 'invokables' => [ + MyProvider::class => MyProvider::class, + ], +], +``` + +After, in 5.0: + +```php +'provider_manager' => [ + 'factories' => [ + MyProvider::class => Dot\Navigation\Provider\InvokableProviderFactory::class, + ], +], +``` + +A factory class or a callable with the signature `__invoke(ContainerInterface $container, string $requestedName, ?array $options = null)` works in both versions. diff --git a/docs/book/v5/usage.md b/docs/book/v5/usage.md new file mode 100644 index 0000000..a39e68f --- /dev/null +++ b/docs/book/v5/usage.md @@ -0,0 +1,73 @@ +# Usage + +This is an example of `config/autoload/navigation.global.php`. +Change the menu structure here. + +```php + [ + //enable menu item active if any child is active + 'active_recursion' => true, + + //map a provider name to its config + 'containers' => [ + 'default' => [ + 'type' => 'ArrayProvider', + 'options' => [ + 'items' => [ + [ + 'options' => [ + 'label' => 'Menu #1', + 'route' => [ + 'route_name' => 'home', + 'route_params' => [], + 'query_params' => [], + 'fragment_id' => null, + 'options' => [], + + //the below parameters are not used in route generation + //they are used in finding if a page is active by omitting some parameters from the check + 'ignore_params' => [] + ], + ], + 'attributes' => [ + 'name' => 'Menu #1', + ] + ], + [ + 'options' => [ + 'label' => 'Menu #2', + 'route' => ['route_name' => 'home'], + ], + 'attributes' => [ + 'name' => 'Menu #2', + ] + ] + ], + ], + ], + ], + + //register custom providers here + 'provider_manager' => [], + ], +]; +``` + +## Active pages + +`NavigationInterface::isActive($page)` tells if a page is active for the current request. +`NavigationMiddleware` gives the route result and the query parameters of the request to the navigation service. + +A page with a `route` option is active when all of these conditions are true: + +- The `route_name` of the page is the name of the matched route. +- Each request parameter is also a page parameter, with the same name and the same value. The request parameters are the matched route parameters and the query parameters. The page parameters are `route_params` and `query_params`. +- The comparison ignores the request parameters in `ignore_params`. + +The values `1` and `'1'` are equal. For example, a page with `'route_params' => ['id' => 1]` is not active for the request `page=1`, because the names are different. +A page without parameters is not active for `/list/1`, because the request has the parameter `id`. Add `'ignore_params' => ['id']` to make it active. + +If `active_recursion` is `true`, a page is also active when one of its sub-pages is active. This is also true for a parent page that has a `uri` and no `route`. diff --git a/mkdocs.yml b/mkdocs.yml index 3edc779..c1a40ff 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,12 +2,23 @@ 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 + - Configuration: v5/configuration.md + - Installation: v5/installation.md + - Components: v5/components.md + - "Container Providers": v5/container-providers.md + - "Navigation Renderer": v5/navigation-renderer.md + - "Page Options": v5/required-page-options.md + - Usage: v5/usage.md + - Upgrading: v5/upgrading.md - v4: - Overview: v4/overview.md - Configuration: v4/configuration.md diff --git a/phpstan.neon b/phpstan.neon index 349be25..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,7 +1,7 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test diff --git a/phpunit.xml b/phpunit.xml index 6de330b..849f05e 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,14 +1,23 @@ + xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" + bootstrap="vendor/autoload.php" + colors="true" + cacheDirectory=".phpunit.cache" + displayDetailsOnAllIssues="true" + failOnDeprecation="true" + failOnNotice="true" + failOnWarning="true" + failOnRisky="true" + failOnPhpunitDeprecation="true" + failOnPhpunitNotice="true" + failOnPhpunitWarning="true" + beStrictAboutOutputDuringTests="true"> ./test - ./src diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 185e1e4..d69d87b 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -20,6 +20,9 @@ class ConfigProvider { + /** + * @return array + */ public function __invoke(): array { return [ @@ -32,6 +35,9 @@ public function __invoke(): array ]; } + /** + * @return array> + */ public function getDependencyConfig(): array { return [ diff --git a/src/Factory/NavigationMiddlewareFactory.php b/src/Factory/NavigationMiddlewareFactory.php index 1069078..e80661a 100644 --- a/src/Factory/NavigationMiddlewareFactory.php +++ b/src/Factory/NavigationMiddlewareFactory.php @@ -4,9 +4,9 @@ namespace Dot\Navigation\Factory; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\NavigationMiddleware; use Dot\Navigation\Service\NavigationInterface; -use Exception; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; @@ -18,12 +18,12 @@ class NavigationMiddlewareFactory /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Exception + * @throws RuntimeException */ public function __invoke(ContainerInterface $container): NavigationMiddleware { if (! $container->has(NavigationInterface::class)) { - throw new Exception(self::MESSAGE_MISSING_NAVIGATION); + throw new RuntimeException(self::MESSAGE_MISSING_NAVIGATION); } return new NavigationMiddleware( diff --git a/src/Factory/NavigationOptionsFactory.php b/src/Factory/NavigationOptionsFactory.php index 71f7826..c2a0140 100644 --- a/src/Factory/NavigationOptionsFactory.php +++ b/src/Factory/NavigationOptionsFactory.php @@ -4,8 +4,8 @@ namespace Dot\Navigation\Factory; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\Options\NavigationOptions; -use Exception; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; @@ -21,21 +21,24 @@ class NavigationOptionsFactory /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Exception + * @throws RuntimeException */ public function __invoke(ContainerInterface $container): NavigationOptions { if (! $container->has('config')) { - throw new Exception(self::MESSAGE_MISSING_CONFIG); + throw new RuntimeException(self::MESSAGE_MISSING_CONFIG); } $config = $container->get('config'); + if (! is_array($config)) { + throw new RuntimeException(self::MESSAGE_MISSING_CONFIG); + } if ( ! array_key_exists('dot_navigation', $config) || ! is_array($config['dot_navigation']) || empty($config['dot_navigation']) ) { - throw new Exception(self::MESSAGE_MISSING_PACKAGE_CONFIG); + throw new RuntimeException(self::MESSAGE_MISSING_PACKAGE_CONFIG); } return new NavigationOptions( diff --git a/src/Factory/NavigationRendererFactory.php b/src/Factory/NavigationRendererFactory.php index 1180500..8af5c19 100644 --- a/src/Factory/NavigationRendererFactory.php +++ b/src/Factory/NavigationRendererFactory.php @@ -4,10 +4,10 @@ namespace Dot\Navigation\Factory; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\Options\NavigationOptions; use Dot\Navigation\Service\NavigationInterface; use Dot\Navigation\View\NavigationRenderer; -use Exception; use Mezzio\Template\TemplateRendererInterface; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; @@ -22,20 +22,20 @@ class NavigationRendererFactory /** * @throws NotFoundExceptionInterface * @throws ContainerExceptionInterface - * @throws Exception + * @throws RuntimeException */ public function __invoke(ContainerInterface $container): NavigationRenderer { if (! $container->has(NavigationInterface::class)) { - throw new Exception(self::MESSAGE_MISSING_NAVIGATION_INTERFACE); + throw new RuntimeException(self::MESSAGE_MISSING_NAVIGATION_INTERFACE); } if (! $container->has(TemplateRendererInterface::class)) { - throw new Exception(self::MESSAGE_MISSING_TEMPLATE_RENDERER); + throw new RuntimeException(self::MESSAGE_MISSING_TEMPLATE_RENDERER); } if (! $container->has(NavigationOptions::class)) { - throw new Exception(self::MESSAGE_MISSING_NAVIGATION_OPTIONS); + throw new RuntimeException(self::MESSAGE_MISSING_NAVIGATION_OPTIONS); } return new NavigationRenderer( diff --git a/src/Factory/NavigationServiceFactory.php b/src/Factory/NavigationServiceFactory.php index 6827b27..ad350a9 100644 --- a/src/Factory/NavigationServiceFactory.php +++ b/src/Factory/NavigationServiceFactory.php @@ -6,11 +6,11 @@ use Dot\Authorization\AuthorizationInterface; use Dot\Helpers\Route\RouteHelper; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\Options\NavigationOptions; use Dot\Navigation\Provider\Factory; use Dot\Navigation\Provider\ProviderPluginManager; use Dot\Navigation\Service\Navigation; -use Exception; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; @@ -24,20 +24,20 @@ class NavigationServiceFactory /** * @throws NotFoundExceptionInterface * @throws ContainerExceptionInterface - * @throws Exception + * @throws RuntimeException */ public function __invoke(ContainerInterface $container): Navigation { if (! $container->has(RouteHelper::class)) { - throw new Exception(self::MESSAGE_MISSING_ROUTE_HELPER); + throw new RuntimeException(self::MESSAGE_MISSING_ROUTE_HELPER); } if (! $container->has(ProviderPluginManager::class)) { - throw new Exception(self::MESSAGE_MISSING_PLUGIN_MANAGER); + throw new RuntimeException(self::MESSAGE_MISSING_PLUGIN_MANAGER); } if (! $container->has(NavigationOptions::class)) { - throw new Exception(self::MESSAGE_MISSING_NAVIGATION_OPTIONS); + throw new RuntimeException(self::MESSAGE_MISSING_NAVIGATION_OPTIONS); } /** @var NavigationOptions $options */ diff --git a/src/Factory/ProviderPluginManagerFactory.php b/src/Factory/ProviderPluginManagerFactory.php index aaa7dc3..5ce2f0e 100644 --- a/src/Factory/ProviderPluginManagerFactory.php +++ b/src/Factory/ProviderPluginManagerFactory.php @@ -4,8 +4,8 @@ namespace Dot\Navigation\Factory; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\Provider\ProviderPluginManager; -use Exception; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; @@ -22,21 +22,24 @@ class ProviderPluginManagerFactory /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Exception + * @throws RuntimeException */ public function __invoke(ContainerInterface $container): ProviderPluginManager { if (! $container->has('config')) { - throw new Exception(self::MESSAGE_MISSING_CONFIG); + throw new RuntimeException(self::MESSAGE_MISSING_CONFIG); } $config = $container->get('config'); + if (! is_array($config)) { + throw new RuntimeException(self::MESSAGE_MISSING_CONFIG); + } if ( ! array_key_exists('dot_navigation', $config) || ! is_array($config['dot_navigation']) || empty($config['dot_navigation']) ) { - throw new Exception(self::MESSAGE_MISSING_PACKAGE_CONFIG); + throw new RuntimeException(self::MESSAGE_MISSING_PACKAGE_CONFIG); } $config = $config['dot_navigation']; @@ -44,7 +47,7 @@ public function __invoke(ContainerInterface $container): ProviderPluginManager ! array_key_exists('provider_manager', $config) || ! is_array($config['provider_manager']) ) { - throw new Exception(self::MESSAGE_MISSING_CONFIG_PROVIDER_MANAGER); + throw new RuntimeException(self::MESSAGE_MISSING_CONFIG_PROVIDER_MANAGER); } $config = $config['provider_manager']; diff --git a/src/Filter/IsAllowedFilter.php b/src/Filter/IsAllowedFilter.php index 3d548e6..d8a3ca4 100644 --- a/src/Filter/IsAllowedFilter.php +++ b/src/Filter/IsAllowedFilter.php @@ -4,17 +4,25 @@ namespace Dot\Navigation\Filter; +use Dot\Navigation\Page; use Dot\Navigation\Service\NavigationInterface; use RecursiveFilterIterator; use RecursiveIterator; -class IsAllowedFilter extends RecursiveFilterIterator +/** + * Skips the pages that the current user is not allowed to see, and their sub-pages. + * + * @extends RecursiveFilterIterator> + */ +final class IsAllowedFilter extends RecursiveFilterIterator { - protected NavigationInterface $navigation; - - public function __construct(RecursiveIterator $iterator, NavigationInterface $navigation) - { - $this->navigation = $navigation; + /** + * @param RecursiveIterator $iterator + */ + public function __construct( + private readonly RecursiveIterator $iterator, + private readonly NavigationInterface $navigation, + ) { parent::__construct($iterator); } @@ -23,10 +31,8 @@ public function accept(): bool return $this->navigation->isAllowed($this->current()); } - public function getChildren(): IsAllowedFilter + public function getChildren(): self { - /** @var RecursiveIterator $innerIterator */ - $innerIterator = $this->getInnerIterator(); - return new self($innerIterator->getChildren(), $this->navigation); + return new self($this->iterator->getChildren(), $this->navigation); } } diff --git a/src/NavigationContainer.php b/src/NavigationContainer.php index 7b4fec4..7864077 100644 --- a/src/NavigationContainer.php +++ b/src/NavigationContainer.php @@ -4,23 +4,29 @@ namespace Dot\Navigation; +use Dot\Navigation\Exception\RuntimeException; use RecursiveIterator; use RecursiveIteratorIterator; -use function count; - +/** + * @implements RecursiveIterator + */ class NavigationContainer implements RecursiveIterator { - protected int $index = 0; + protected int $index = 0; + /** @var list */ protected array $children = []; + /** + * @param array $pages + */ public function __construct(array $pages = []) { $this->addPages($pages); } /** - * @param Page[] $pages + * @param array $pages */ public function addPages(array $pages): void { @@ -34,8 +40,15 @@ public function addPage(Page $page): void $this->children[] = $page; } - public function current(): NavigationContainer + /** + * @throws RuntimeException + */ + public function current(): Page { + if (! $this->valid()) { + throw new RuntimeException('The navigation container has no page at the current position'); + } + return $this->children[$this->index]; } @@ -59,22 +72,32 @@ public function rewind(): void $this->index = 0; } + /** + * Tells if this container has pages. Templates use it to show a sub-menu. + * Unlike the RecursiveIterator contract, it does not check the current page only. + * Because of this, RecursiveIteratorIterator::LEAVES_ONLY gives no pages. + */ public function hasChildren(): bool { - return count($this->children) > 0; + return $this->hasPages(); } - public function getChildren(): NavigationContainer + public function hasPages(): bool { - return $this->children[$this->index]; + return $this->children !== []; } - public function findOneByAttribute(string $attribute, mixed $value): ?Page + /** + * @throws RuntimeException + */ + public function getChildren(): Page { - $iterator = new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST); + return $this->current(); + } - /** @var Page $page */ - foreach ($iterator as $page) { + public function findOneByAttribute(string $attribute, mixed $value): ?Page + { + foreach ($this->iteratePages() as $page) { if ($page->getAttribute($attribute) === $value) { return $page; } @@ -83,13 +106,13 @@ public function findOneByAttribute(string $attribute, mixed $value): ?Page return null; } + /** + * @return list + */ public function findByAttribute(string $attribute, mixed $value): array { - $result = []; - $iterator = new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST); - - /** @var Page $page */ - foreach ($iterator as $page) { + $result = []; + foreach ($this->iteratePages() as $page) { if ($page->getAttribute($attribute) === $value) { $result[] = $page; } @@ -100,10 +123,7 @@ public function findByAttribute(string $attribute, mixed $value): array public function findOneByOption(string $option, mixed $value): ?Page { - $iterator = new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST); - - /** @var Page $page */ - foreach ($iterator as $page) { + foreach ($this->iteratePages() as $page) { if ($page->getOption($option) === $value) { return $page; } @@ -112,13 +132,13 @@ public function findOneByOption(string $option, mixed $value): ?Page return null; } + /** + * @return list + */ public function findByOption(string $option, mixed $value): array { - $result = []; - $iterator = new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST); - - /** @var Page $page */ - foreach ($iterator as $page) { + $result = []; + foreach ($this->iteratePages() as $page) { if ($page->getOption($option) === $value) { $result[] = $page; } @@ -126,4 +146,12 @@ public function findByOption(string $option, mixed $value): array return $result; } + + /** + * @return RecursiveIteratorIterator<$this> + */ + private function iteratePages(): RecursiveIteratorIterator + { + return new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST); + } } diff --git a/src/NavigationMiddleware.php b/src/NavigationMiddleware.php index dfc2471..f54172f 100644 --- a/src/NavigationMiddleware.php +++ b/src/NavigationMiddleware.php @@ -26,6 +26,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface if ($routeResult instanceof RouteResult) { $this->navigation->setRouteResult($routeResult); } + $this->navigation->setQueryParams($request->getQueryParams()); return $handler->handle($request); } diff --git a/src/Options/NavigationOptions.php b/src/Options/NavigationOptions.php index 92d19a9..ab0ad7f 100644 --- a/src/Options/NavigationOptions.php +++ b/src/Options/NavigationOptions.php @@ -7,25 +7,34 @@ use Laminas\Stdlib\AbstractOptions; /** - * @template TValue - * @template-extends AbstractOptions + * @extends AbstractOptions */ class NavigationOptions extends AbstractOptions { + /** @var array> */ protected array $containers = []; protected bool $activeRecursion = true; + /** + * @param array|null $options + */ public function __construct(?array $options = null) { $this->__strictMode__ = false; parent::__construct($options); } + /** + * @return array> + */ public function getContainers(): array { return $this->containers; } + /** + * @param array> $containers + */ public function setContainers(array $containers): void { $this->containers = $containers; diff --git a/src/Page.php b/src/Page.php index aeac98c..2f66598 100644 --- a/src/Page.php +++ b/src/Page.php @@ -5,13 +5,16 @@ namespace Dot\Navigation; use function count; +use function is_scalar; use function is_string; class Page extends NavigationContainer { - protected ?Page $parent = null; + protected ?Page $parent = null; + /** @var array */ protected array $attributes = []; - protected array $options = []; + /** @var array */ + protected array $options = []; public function hasParent(): bool { @@ -39,6 +42,9 @@ public function setOption(string $option, mixed $value): void $this->options[$option] = $value; } + /** + * @return array + */ public function getOptions(): array { return $this->options; @@ -49,6 +55,9 @@ public function hasOptions(): bool return count($this->options) > 0; } + /** + * @param array $options + */ public function setOptions(array $options): void { $this->options = $options; @@ -64,6 +73,9 @@ public function getAttribute(string $attribute): mixed return $this->attributes[$attribute] ?? null; } + /** + * @return array + */ public function getAttributes(): array { return $this->attributes; @@ -74,6 +86,9 @@ public function hasAttributes(): bool return count($this->attributes) > 0; } + /** + * @param array $attributes + */ public function setAttributes(array $attributes): void { $this->attributes = $attributes; @@ -81,7 +96,9 @@ public function setAttributes(array $attributes): void public function getName(): ?string { - return $this->getOption('name'); + $name = $this->getOption('name'); + + return is_scalar($name) ? (string) $name : null; } public function getOption(string $option): mixed diff --git a/src/Provider/ArrayProvider.php b/src/Provider/ArrayProvider.php index 22c3b02..98730c4 100644 --- a/src/Provider/ArrayProvider.php +++ b/src/Provider/ArrayProvider.php @@ -4,17 +4,23 @@ namespace Dot\Navigation\Provider; +use Dot\Navigation\Exception\InvalidArgumentException; use Dot\Navigation\NavigationContainer; use Dot\Navigation\Page; use function count; use function is_array; +use function sprintf; class ArrayProvider implements ProviderInterface { protected ?NavigationContainer $container = null; - protected array $items = []; + /** @var array> */ + protected array $items = []; + /** + * @param array|null $options + */ public function __construct(?array $options = []) { if (isset($options['items']) && is_array($options['items'])) { @@ -22,6 +28,9 @@ public function __construct(?array $options = []) } } + /** + * @throws InvalidArgumentException + */ public function getContainer(): NavigationContainer { if ($this->container instanceof NavigationContainer) { @@ -37,8 +46,18 @@ public function getContainer(): NavigationContainer return $this->container; } + /** + * @param array $spec + * @throws InvalidArgumentException + */ protected function getPage(array $spec): Page { + foreach (['attributes', 'options', 'pages'] as $key) { + if (isset($spec[$key]) && ! is_array($spec[$key])) { + throw new InvalidArgumentException(sprintf('The navigation page key "%s" must be an array', $key)); + } + } + $page = new Page(); if (isset($spec['attributes'])) { @@ -51,6 +70,9 @@ protected function getPage(array $spec): Page if (isset($spec['pages'])) { foreach ($spec['pages'] as $childSpec) { + if (! is_array($childSpec)) { + throw new InvalidArgumentException('Each item of the navigation page key "pages" must be an array'); + } $page->addPage($this->getPage($childSpec)); } } @@ -58,6 +80,9 @@ protected function getPage(array $spec): Page return $page; } + /** + * @return array> + */ public function getItems(): array { return $this->items; @@ -68,6 +93,9 @@ public function hasItems(): bool return count($this->items) > 0; } + /** + * @param array> $items + */ public function setItems(array $items): void { $this->items = $items; diff --git a/src/Provider/Factory.php b/src/Provider/Factory.php index 54e3ad2..3fc8619 100644 --- a/src/Provider/Factory.php +++ b/src/Provider/Factory.php @@ -5,9 +5,11 @@ namespace Dot\Navigation\Provider; use Dot\Navigation\Exception\RuntimeException; -use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; +use function is_array; +use function is_string; + class Factory implements FactoryInterface { protected ContainerInterface $container; @@ -20,16 +22,22 @@ public function __construct(ContainerInterface $container, ?ProviderPluginManage } /** - * @throws ContainerExceptionInterface + * @param array $specs + * @throws RuntimeException */ public function create(array $specs): ProviderInterface { $type = $specs['type'] ?? ''; - if (empty($type)) { + if (! is_string($type) || $type === '') { throw new RuntimeException('Undefined navigation provider type'); } - return $this->getProviderPluginManager()->build($type, $specs['options'] ?? null); + $options = $specs['options'] ?? null; + if ($options !== null && ! is_array($options)) { + throw new RuntimeException('The navigation provider options must be an array'); + } + + return $this->getProviderPluginManager()->build($type, $options); } public function getProviderPluginManager(): ProviderPluginManager diff --git a/src/Provider/FactoryInterface.php b/src/Provider/FactoryInterface.php index 5968781..38aa62f 100644 --- a/src/Provider/FactoryInterface.php +++ b/src/Provider/FactoryInterface.php @@ -6,6 +6,9 @@ interface FactoryInterface { + /** + * @param array $specs + */ public function create(array $specs): ProviderInterface; public function getProviderPluginManager(): ProviderPluginManager; diff --git a/src/Provider/InvokableProviderFactory.php b/src/Provider/InvokableProviderFactory.php new file mode 100644 index 0000000..02c9b7c --- /dev/null +++ b/src/Provider/InvokableProviderFactory.php @@ -0,0 +1,35 @@ +|null $options + * @throws RuntimeException + */ + public function __invoke( + ContainerInterface $container, + string $requestedName, + ?array $options = null + ): ProviderInterface { + if (! class_exists($requestedName) || ! is_a($requestedName, ProviderInterface::class, true)) { + throw new RuntimeException(sprintf('"%s" is not a navigation provider class', $requestedName)); + } + + return $options === null ? new $requestedName() : new $requestedName($options); + } +} diff --git a/src/Provider/ProviderPluginManager.php b/src/Provider/ProviderPluginManager.php index e258bef..efbe93c 100644 --- a/src/Provider/ProviderPluginManager.php +++ b/src/Provider/ProviderPluginManager.php @@ -4,26 +4,27 @@ namespace Dot\Navigation\Provider; -use Laminas\ServiceManager\AbstractPluginManager; -use Laminas\ServiceManager\Exception\InvalidServiceException; -use Laminas\ServiceManager\Factory\InvokableFactory; +use Dot\Navigation\Exception\RuntimeException; +use Psr\Container\ContainerInterface; -use function gettype; -use function is_object; +use function class_exists; +use function get_debug_type; +use function is_callable; +use function is_string; use function sprintf; /** - * @template InstanceType - * @extends AbstractPluginManager + * Creates navigation providers from the "provider_manager" config. + * It supports only the "factories" and "aliases" keys, and it needs no Laminas class. */ -class ProviderPluginManager extends AbstractPluginManager +class ProviderPluginManager { - protected string $instanceOf = ProviderInterface::class; - + /** @var array */ protected array $factories = [ - ArrayProvider::class => InvokableFactory::class, + ArrayProvider::class => InvokableProviderFactory::class, ]; + /** @var array */ protected array $aliases = [ 'arrayprovider' => ArrayProvider::class, 'arrayProvider' => ArrayProvider::class, @@ -32,15 +33,48 @@ class ProviderPluginManager extends AbstractPluginManager 'Array' => ArrayProvider::class, ]; - public function validate(mixed $instance): void + /** + * @param array{factories?: array, aliases?: array} $config + */ + public function __construct( + protected ContainerInterface $container, + array $config = [], + ) { + $this->factories = [...$this->factories, ...$config['factories'] ?? []]; + $this->aliases = [...$this->aliases, ...$config['aliases'] ?? []]; + } + + public function has(string $name): bool + { + return isset($this->factories[$this->aliases[$name] ?? $name]); + } + + /** + * @param array|null $options + * @throws RuntimeException + */ + public function build(string $name, ?array $options = null): ProviderInterface { - if (! $instance instanceof $this->instanceOf) { - throw new InvalidServiceException(sprintf( + $resolved = $this->aliases[$name] ?? $name; + $factory = $this->factories[$resolved] ?? null; + if (is_string($factory) && class_exists($factory)) { + $factory = new $factory(); + } + + if (! is_callable($factory)) { + throw new RuntimeException(sprintf('Navigation provider "%s" is not registered', $name)); + } + + $provider = $factory($this->container, $resolved, $options); + if (! $provider instanceof ProviderInterface) { + throw new RuntimeException(sprintf( '%s can only create instances of %s; %s is invalid', static::class, - $this->instanceOf, - is_object($instance) ? $instance::class : gettype($instance) + ProviderInterface::class, + get_debug_type($provider) )); } + + return $provider; } } diff --git a/src/Service/Navigation.php b/src/Service/Navigation.php index 57792b0..ba7be01 100644 --- a/src/Service/Navigation.php +++ b/src/Service/Navigation.php @@ -6,16 +6,19 @@ use Dot\Authorization\AuthorizationInterface; use Dot\Helpers\Route\RouteHelper; +use Dot\Navigation\Exception\InvalidArgumentException; use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\NavigationContainer; use Dot\Navigation\Options\NavigationOptions; use Dot\Navigation\Page; use Dot\Navigation\Provider\FactoryInterface; use Mezzio\Router\RouteResult; -use RecursiveIteratorIterator; -use function array_diff; +use function array_key_exists; use function array_merge; +use function is_array; +use function is_scalar; +use function is_string; use function spl_object_hash; use function sprintf; @@ -26,10 +29,15 @@ class Navigation implements NavigationInterface protected NavigationOptions $moduleOptions; protected ?AuthorizationInterface $authorization; protected ?RouteResult $routeResult = null; - protected array $containers = []; - protected array $isActiveCache = []; - protected array $hrefCache = []; - protected bool $isActiveRecursion = true; + /** @var array */ + protected array $containers = []; + /** @var array */ + protected array $isActiveCache = []; + /** @var array */ + protected array $hrefCache = []; + /** @var array */ + protected array $queryParams = []; + protected bool $isActiveRecursion = true; public function __construct( FactoryInterface $providerFactory, @@ -50,7 +58,18 @@ public function getRouteResult(): ?RouteResult public function setRouteResult(RouteResult $routeResult): void { - $this->routeResult = $routeResult; + $this->routeResult = $routeResult; + $this->isActiveCache = []; + $this->hrefCache = []; + } + + /** + * @param array $queryParams + */ + public function setQueryParams(array $queryParams): void + { + $this->queryParams = $queryParams; + $this->isActiveCache = []; } public function getIsActiveRecursion(): bool @@ -66,11 +85,17 @@ public function setIsActiveRecursion(bool $isActiveRecursion): void } } + /** + * @return array + */ public function getIsActiveCache(): array { return $this->isActiveCache; } + /** + * @return array + */ public function getHrefCache(): array { return $this->hrefCache; @@ -94,6 +119,9 @@ public function getContainer(string $name): NavigationContainer return $this->containers[$name]; } + /** + * @throws InvalidArgumentException + */ public function isAllowed(Page $page): bool { //authorization module is optional, this function will always return true if missing @@ -105,7 +133,17 @@ public function isAllowed(Page $page): bool if (isset($options['permission'])) { if (isset($options['roles'])) { - return $this->authorization->isGranted($options['permission'], $options['roles']); + $roles = $options['roles']; + if (is_string($roles)) { + $roles = [$roles]; + } + if (! is_array($roles)) { + throw new InvalidArgumentException( + 'The navigation page option "roles" must be a string or an array' + ); + } + + return $this->authorization->isGranted($options['permission'], $roles); } return $this->authorization->isGranted($options['permission']); } @@ -122,64 +160,90 @@ public function isActive(Page $page): bool $active = false; if ($this->routeResult instanceof RouteResult && $this->routeResult->isSuccess()) { - $routeName = $this->routeResult->getMatchedRouteName(); $pageRoute = $page->getOption('route'); - if ($pageRoute) { - if ($pageRoute['route_name'] === $routeName) { - $reqParams = array_merge($this->routeResult->getMatchedParams(), $_GET); - $pageParams = array_merge($pageRoute['route_params'] ?? [], $pageRoute['query_params'] ?? []); - - $active = $this->areParamsEqual($pageParams, $reqParams, $pageRoute['ignore_params'] ?? []); - } elseif ($this->isActiveRecursion) { - $iterator = new RecursiveIteratorIterator($page, RecursiveIteratorIterator::CHILD_FIRST); - foreach ($iterator as $leaf) { - if (! $leaf instanceof Page) { - continue; - } - if ($this->isActive($leaf)) { - $active = true; - break; - } + if ( + is_array($pageRoute) + && ($pageRoute['route_name'] ?? null) === $this->routeResult->getMatchedRouteName() + ) { + $active = $this->areParamsEqual( + array_merge($pageRoute['route_params'] ?? [], $pageRoute['query_params'] ?? []), + array_merge($this->routeResult->getMatchedParams(), $this->queryParams), + $pageRoute['ignore_params'] ?? [] + ); + } elseif ($this->isActiveRecursion) { + foreach ($page as $child) { + if ($this->isActive($child)) { + $active = true; + break; } } } } + $this->isActiveCache[$hash] = $active; + return $active; } + /** + * Tells if each request parameter, except the ignored ones, is also a page parameter with the same value. + * + * @param array $pageParams + * @param array $requestParams + * @param list $ignoreParams + */ protected function areParamsEqual(array $pageParams, array $requestParams, array $ignoreParams): bool { - foreach ($ignoreParams as $unsetKey) { - if (isset($requestParams[$unsetKey])) { - unset($requestParams[$unsetKey]); + foreach ($ignoreParams as $key) { + unset($requestParams[$key]); + } + + foreach ($requestParams as $key => $value) { + if (! array_key_exists($key, $pageParams) || ! $this->isSameParam($pageParams[$key], $value)) { + return false; } } - $diff = array_diff($requestParams, $pageParams); - return empty($diff); + + return true; } + private function isSameParam(mixed $pageValue, mixed $requestValue): bool + { + if (is_scalar($pageValue) && is_scalar($requestValue)) { + return (string) $pageValue === (string) $requestValue; + } + + return $pageValue === $requestValue; + } + + /** + * @throws RuntimeException + */ public function getHref(Page $page): string { $hash = spl_object_hash($page); if (isset($this->hrefCache[$hash])) { - return (string) $this->hrefCache[$hash]; + return $this->hrefCache[$hash]; } - $href = null; - if ($page->getOption('uri')) { - $href = $page->getOption('uri'); - } elseif ($page->getOption('route')) { - $pageRoute = $page->getOption('route'); - $href = $this->routeHelper->generateUri($pageRoute); + $href = null; + $uri = $page->getOption('uri'); + $route = $page->getOption('route'); + if (is_string($uri) && $uri !== '') { + $href = $uri; + } elseif (is_array($route)) { + $href = (string) $this->routeHelper->generateUri($route); } - if ($href) { - $this->hrefCache[$hash] = (string) $href; - } else { - throw new RuntimeException('Unable to assemble href for navigation page ' . $page->getName()); + if ($href === null || $href === '') { + throw new RuntimeException(sprintf( + 'Unable to assemble href for navigation page "%s"', + $page->getName() ?? $page->getLabel() + )); } - return (string) $href; + $this->hrefCache[$hash] = $href; + + return $href; } } diff --git a/src/Service/NavigationInterface.php b/src/Service/NavigationInterface.php index c9162a1..78c935c 100644 --- a/src/Service/NavigationInterface.php +++ b/src/Service/NavigationInterface.php @@ -14,12 +14,25 @@ public function getRouteResult(): ?RouteResult; public function setRouteResult(RouteResult $routeResult): void; + /** + * Sets the query parameters of the current request. isActive() uses them, not the PHP superglobal. + * + * @param array $queryParams + */ + public function setQueryParams(array $queryParams): void; + public function getIsActiveRecursion(): bool; public function setIsActiveRecursion(bool $isActiveRecursion): void; + /** + * @return array + */ public function getIsActiveCache(): array; + /** + * @return array + */ public function getHrefCache(): array; public function getContainer(string $name): NavigationContainer; diff --git a/src/View/AbstractNavigationRenderer.php b/src/View/AbstractNavigationRenderer.php index 23822ac..e138066 100644 --- a/src/View/AbstractNavigationRenderer.php +++ b/src/View/AbstractNavigationRenderer.php @@ -29,7 +29,7 @@ abstract class AbstractNavigationRenderer implements RendererInterface { protected NavigationInterface $navigation; protected TemplateRendererInterface $template; - protected string $partial; + protected ?string $partial = null; public function __construct(NavigationInterface $navigation, TemplateRendererInterface $template) { @@ -37,6 +37,13 @@ public function __construct(NavigationInterface $navigation, TemplateRendererInt $this->template = $template; } + /** + * Each value must be a string or a list of strings. A list is joined with spaces. + * For a key that starts with "on" and for "constraints", an array is encoded as JSON. + * Any other value type throws a TypeError. + * + * @param array $attributes + */ public function htmlAttributes(array $attributes): string { $xhtml = ''; @@ -105,6 +112,11 @@ protected function getContainer(string|NavigationContainer $container): Navigati } } + /** + * @param array $input + * @param list $valid + * @return array + */ protected function cleanAttributes(array $input, array $valid): array { foreach ($input as $key => $value) { diff --git a/src/View/NavigationRenderer.php b/src/View/NavigationRenderer.php index 3232512..9f4d747 100644 --- a/src/View/NavigationRenderer.php +++ b/src/View/NavigationRenderer.php @@ -4,6 +4,7 @@ namespace Dot\Navigation\View; +use Dot\Navigation\Exception\InvalidArgumentException; use Dot\Navigation\NavigationContainer; use Dot\Navigation\Options\NavigationOptions; use Dot\Navigation\Service\NavigationInterface; @@ -24,8 +25,16 @@ public function __construct( parent::__construct($navigation, $template); } + /** + * @param array $params + * @throws InvalidArgumentException + */ public function renderPartial(string|NavigationContainer $container, string $partial, array $params = []): string { + if ($partial === '') { + throw new InvalidArgumentException('The partial name must not be empty'); + } + $container = $this->getContainer($container); return $this->template->render( @@ -37,8 +46,16 @@ public function renderPartial(string|NavigationContainer $container, string $par ); } + /** + * @param array $params + * @throws InvalidArgumentException + */ public function render(string|NavigationContainer $container, string $template, array $params = []): string { + if ($template === '') { + throw new InvalidArgumentException('The template name must not be empty'); + } + $container = $this->getContainer($container); return $this->template->render( diff --git a/src/View/RendererInterface.php b/src/View/RendererInterface.php index f686463..49ce406 100644 --- a/src/View/RendererInterface.php +++ b/src/View/RendererInterface.php @@ -4,13 +4,31 @@ namespace Dot\Navigation\View; +use Dot\Navigation\Exception\InvalidArgumentException; use Dot\Navigation\NavigationContainer; interface RendererInterface { + /** + * @param array $params + * @throws InvalidArgumentException + */ public function render(string|NavigationContainer $container, string $template, array $params = []): string; + /** + * @param array $params + * @throws InvalidArgumentException + */ public function renderPartial(string|NavigationContainer $container, string $partial, array $params = []): string; + /** + * Returns the attributes as HTML attribute text, with a leading space before each attribute. + * + * Each value must be a string or a list of strings. A list is joined with spaces. + * For a key that starts with "on" and for "constraints", an array is encoded as JSON. + * Any other value type throws a TypeError. + * + * @param array $attributes + */ public function htmlAttributes(array $attributes): string; } diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index 186347d..a4de486 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -23,6 +23,7 @@ class ConfigProviderTest extends TestCase { + /** @var array */ protected array $config; protected function setup(): void diff --git a/test/Factory/NavigationMiddlewareFactoryTest.php b/test/Factory/NavigationMiddlewareFactoryTest.php index fed1db5..91cbba8 100644 --- a/test/Factory/NavigationMiddlewareFactoryTest.php +++ b/test/Factory/NavigationMiddlewareFactoryTest.php @@ -4,54 +4,27 @@ namespace DotTest\Navigation\Factory; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\Factory\NavigationMiddlewareFactory; use Dot\Navigation\NavigationMiddleware; use Dot\Navigation\Service\NavigationInterface; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Navigation\TestData\Container; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; class NavigationMiddlewareFactoryTest extends TestCase { - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateMiddlewareWithoutNavigationInterface(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with(NavigationInterface::class) - ->willReturn(false); - + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(NavigationMiddlewareFactory::MESSAGE_MISSING_NAVIGATION); - (new NavigationMiddlewareFactory())($container); + (new NavigationMiddlewareFactory())(new Container()); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillCreateMiddleware(): void { - $container = $this->createMock(ContainerInterface::class); - $navigation = $this->createMock(NavigationInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with(NavigationInterface::class) - ->willReturn(true); - - $container->expects($this->once()) - ->method('get') - ->with(NavigationInterface::class) - ->willReturn($navigation); + $container = new Container([ + NavigationInterface::class => $this->createStub(NavigationInterface::class), + ]); $middleware = (new NavigationMiddlewareFactory())($container); $this->assertSame(NavigationMiddleware::class, $middleware::class); diff --git a/test/Factory/NavigationOptionsFactoryTest.php b/test/Factory/NavigationOptionsFactoryTest.php index 1d1fa79..21a831e 100644 --- a/test/Factory/NavigationOptionsFactoryTest.php +++ b/test/Factory/NavigationOptionsFactoryTest.php @@ -4,81 +4,45 @@ namespace DotTest\Navigation\Factory; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\Factory\NavigationOptionsFactory; -use Dot\Navigation\Options\NavigationOptions; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Navigation\TestData\Container; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; class NavigationOptionsFactoryTest extends TestCase { - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateNavigationOptionsWithoutConfig(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(false); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(NavigationOptionsFactory::MESSAGE_MISSING_CONFIG); + (new NavigationOptionsFactory())(new Container()); + } + public function testWillNotCreateNavigationOptionsWhenConfigIsNotAnArray(): void + { + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(NavigationOptionsFactory::MESSAGE_MISSING_CONFIG); - (new NavigationOptionsFactory())($container); + (new NavigationOptionsFactory())(new Container(['config' => 'invalid'])); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateNavigationOptionsWithoutPackageConfig(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn([]); - + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(NavigationOptionsFactory::MESSAGE_MISSING_PACKAGE_CONFIG); - (new NavigationOptionsFactory())($container); + (new NavigationOptionsFactory())(new Container(['config' => []])); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillCreateNavigationOptions(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn([ + $container = new Container([ + 'config' => [ 'dot_navigation' => [ - 'active_recursion' => true, + 'active_recursion' => false, ], - ]); + ], + ]); $options = (new NavigationOptionsFactory())($container); - $this->assertSame(NavigationOptions::class, $options::class); + $this->assertFalse($options->getActiveRecursion()); } } diff --git a/test/Factory/NavigationRendererFactoryTest.php b/test/Factory/NavigationRendererFactoryTest.php index b699ac0..27815d8 100644 --- a/test/Factory/NavigationRendererFactoryTest.php +++ b/test/Factory/NavigationRendererFactoryTest.php @@ -4,96 +4,53 @@ namespace DotTest\Navigation\Factory; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\Factory\NavigationRendererFactory; use Dot\Navigation\Options\NavigationOptions; use Dot\Navigation\Service\NavigationInterface; use Dot\Navigation\View\NavigationRenderer; +use DotTest\Navigation\TestData\Container; use Mezzio\Template\TemplateRendererInterface; -use PHPUnit\Framework\MockObject\Exception; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; class NavigationRendererFactoryTest extends TestCase { - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateNavigationRendererWithoutNavigationInterface(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with(NavigationInterface::class) - ->willReturn(false); - + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(NavigationRendererFactory::MESSAGE_MISSING_NAVIGATION_INTERFACE); - (new NavigationRendererFactory())($container); + (new NavigationRendererFactory())(new Container()); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateNavigationRendererWithoutTemplateRendererInterface(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->method('has')->willReturnMap([ - [NavigationInterface::class, true], - [TemplateRendererInterface::class, false], + $container = new Container([ + NavigationInterface::class => $this->createStub(NavigationInterface::class), ]); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(NavigationRendererFactory::MESSAGE_MISSING_TEMPLATE_RENDERER); (new NavigationRendererFactory())($container); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateNavigationRendererWithoutNavigationOptions(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->method('has')->willReturnMap([ - [NavigationInterface::class, true], - [TemplateRendererInterface::class, true], - [NavigationOptions::class, false], + $container = new Container([ + NavigationInterface::class => $this->createStub(NavigationInterface::class), + TemplateRendererInterface::class => $this->createStub(TemplateRendererInterface::class), ]); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(NavigationRendererFactory::MESSAGE_MISSING_NAVIGATION_OPTIONS); (new NavigationRendererFactory())($container); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotCreateNavigationRenderer(): void + public function testWillCreateNavigationRenderer(): void { - $container = $this->createMock(ContainerInterface::class); - $navigation = $this->createMock(NavigationInterface::class); - $renderer = $this->createMock(TemplateRendererInterface::class); - $options = $this->createMock(NavigationOptions::class); - - $container->method('has')->willReturnMap([ - [NavigationInterface::class, true], - [TemplateRendererInterface::class, true], - [NavigationOptions::class, true], - ]); - - $container->method('get')->willReturnMap([ - [NavigationInterface::class, $navigation], - [TemplateRendererInterface::class, $renderer], - [NavigationOptions::class, $options], + $container = new Container([ + NavigationInterface::class => $this->createStub(NavigationInterface::class), + TemplateRendererInterface::class => $this->createStub(TemplateRendererInterface::class), + NavigationOptions::class => new NavigationOptions(), ]); $renderer = (new NavigationRendererFactory())($container); diff --git a/test/Factory/NavigationServiceFactoryTest.php b/test/Factory/NavigationServiceFactoryTest.php index 1af2f12..7142c71 100644 --- a/test/Factory/NavigationServiceFactoryTest.php +++ b/test/Factory/NavigationServiceFactoryTest.php @@ -6,132 +6,81 @@ use Dot\Authorization\AuthorizationInterface; use Dot\Helpers\Route\RouteHelper; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\Factory\NavigationServiceFactory; use Dot\Navigation\Options\NavigationOptions; +use Dot\Navigation\Page; use Dot\Navigation\Provider\ProviderPluginManager; use Dot\Navigation\Service\Navigation; -use Mezzio\Template\TemplateRendererInterface; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Navigation\TestData\Container; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; class NavigationServiceFactoryTest extends TestCase { - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateNavigationServiceWithoutRouteHelper(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with(RouteHelper::class) - ->willReturn(false); - + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(NavigationServiceFactory::MESSAGE_MISSING_ROUTE_HELPER); - (new NavigationServiceFactory())($container); + (new NavigationServiceFactory())(new Container()); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateNavigationServiceWithoutProviderPluginManager(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->method('has')->willReturnMap([ - [RouteHelper::class, true], - [ProviderPluginManager::class, false], + $container = new Container([ + RouteHelper::class => $this->createStub(RouteHelper::class), ]); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(NavigationServiceFactory::MESSAGE_MISSING_PLUGIN_MANAGER); (new NavigationServiceFactory())($container); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateNavigationServiceWithoutNavigationOptions(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->method('has')->willReturnMap([ - [RouteHelper::class, true], - [ProviderPluginManager::class, true], - [NavigationOptions::class, false], + $container = new Container([ + RouteHelper::class => $this->createStub(RouteHelper::class), + ProviderPluginManager::class => new ProviderPluginManager(new Container()), ]); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(NavigationServiceFactory::MESSAGE_MISSING_NAVIGATION_OPTIONS); (new NavigationServiceFactory())($container); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillCreateNavigationServiceWithoutAuthorizationInterface(): void { - $container = $this->createMock(ContainerInterface::class); - $navigation = $this->createMock(RouteHelper::class); - $renderer = $this->createMock(TemplateRendererInterface::class); - $options = $this->createMock(NavigationOptions::class); - - $container->method('has')->willReturnMap([ - [RouteHelper::class, true], - [ProviderPluginManager::class, true], - [NavigationOptions::class, true], - [AuthorizationInterface::class, false], - ]); - - $container->method('get')->willReturnMap([ - [RouteHelper::class, $navigation], - [TemplateRendererInterface::class, $renderer], - [NavigationOptions::class, $options], - [AuthorizationInterface::class, null], + $container = new Container([ + RouteHelper::class => $this->createStub(RouteHelper::class), + ProviderPluginManager::class => new ProviderPluginManager(new Container()), + NavigationOptions::class => new NavigationOptions(['active_recursion' => false]), ]); $service = (new NavigationServiceFactory())($container); $this->assertSame(Navigation::class, $service::class); + $this->assertFalse($service->getIsActiveRecursion()); + + $page = new Page(); + $page->setOption('permission', 'test'); + $this->assertTrue($service->isAllowed($page)); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillCreateNavigationServiceWithAuthorizationInterface(): void { - $container = $this->createMock(ContainerInterface::class); - $navigation = $this->createMock(RouteHelper::class); - $renderer = $this->createMock(TemplateRendererInterface::class); - $options = $this->createMock(NavigationOptions::class); - $authorization = $this->createMock(AuthorizationInterface::class); - - $container->method('has')->willReturnMap([ - [RouteHelper::class, true], - [ProviderPluginManager::class, true], - [NavigationOptions::class, true], - [AuthorizationInterface::class, true], - ]); - - $container->method('get')->willReturnMap([ - [RouteHelper::class, $navigation], - [TemplateRendererInterface::class, $renderer], - [NavigationOptions::class, $options], - [AuthorizationInterface::class, $authorization], + $authorization = $this->createStub(AuthorizationInterface::class); + $authorization->method('isGranted')->willReturn(false); + + $container = new Container([ + RouteHelper::class => $this->createStub(RouteHelper::class), + ProviderPluginManager::class => new ProviderPluginManager(new Container()), + NavigationOptions::class => new NavigationOptions(), + AuthorizationInterface::class => $authorization, ]); $service = (new NavigationServiceFactory())($container); $this->assertSame(Navigation::class, $service::class); + + $page = new Page(); + $page->setOption('permission', 'test'); + $this->assertFalse($service->isAllowed($page)); } } diff --git a/test/Factory/ProviderPluginManagerFactoryTest.php b/test/Factory/ProviderPluginManagerFactoryTest.php index 4f4511d..42a8bf2 100644 --- a/test/Factory/ProviderPluginManagerFactoryTest.php +++ b/test/Factory/ProviderPluginManagerFactoryTest.php @@ -4,108 +4,66 @@ namespace DotTest\Navigation\Factory; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\Factory\ProviderPluginManagerFactory; -use Dot\Navigation\Provider\ProviderPluginManager; -use PHPUnit\Framework\MockObject\Exception; +use Dot\Navigation\Provider\InvokableProviderFactory; +use DotTest\Navigation\TestData\Container; +use DotTest\Navigation\TestData\CustomProvider; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; class ProviderPluginManagerFactoryTest extends TestCase { - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateProviderPluginManagerWithoutConfig(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(false); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(ProviderPluginManagerFactory::MESSAGE_MISSING_CONFIG); + (new ProviderPluginManagerFactory())(new Container()); + } + public function testWillNotCreateProviderPluginManagerWhenConfigIsNotAnArray(): void + { + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(ProviderPluginManagerFactory::MESSAGE_MISSING_CONFIG); - (new ProviderPluginManagerFactory())($container); + (new ProviderPluginManagerFactory())(new Container(['config' => 'invalid'])); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateProviderPluginManagerWithoutPackageConfig(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn([]); - + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(ProviderPluginManagerFactory::MESSAGE_MISSING_PACKAGE_CONFIG); - (new ProviderPluginManagerFactory())($container); + (new ProviderPluginManagerFactory())(new Container(['config' => []])); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateProviderPluginManagerWithoutConfigProviderManager(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn([ + $container = new Container([ + 'config' => [ 'dot_navigation' => [ 'active_recursion' => true, ], - ]); + ], + ]); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage(ProviderPluginManagerFactory::MESSAGE_MISSING_CONFIG_PROVIDER_MANAGER); (new ProviderPluginManagerFactory())($container); } - /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillCreateProviderPluginManager(): void + public function testWillCreateProviderPluginManagerWithConfig(): void { - $container = $this->createMock(ContainerInterface::class); - - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn([ + $container = new Container([ + 'config' => [ 'dot_navigation' => [ - 'provider_manager' => [], + 'provider_manager' => [ + 'factories' => [ + CustomProvider::class => InvokableProviderFactory::class, + ], + ], ], - ]); + ], + ]); $manager = (new ProviderPluginManagerFactory())($container); - $this->assertSame(ProviderPluginManager::class, $manager::class); + $this->assertTrue($manager->has(CustomProvider::class)); } } diff --git a/test/Filter/IsAllowedFilterTest.php b/test/Filter/IsAllowedFilterTest.php index 0035bb6..f419083 100644 --- a/test/Filter/IsAllowedFilterTest.php +++ b/test/Filter/IsAllowedFilterTest.php @@ -12,80 +12,91 @@ use Dot\Navigation\Page; use Dot\Navigation\Provider\FactoryInterface; use Dot\Navigation\Service\Navigation; -use Dot\Navigation\Service\NavigationInterface; -use PHPUnit\Framework\MockObject\Exception; use PHPUnit\Framework\TestCase; -use RecursiveIterator; +use RecursiveIteratorIterator; + +use function array_map; +use function iterator_to_array; class IsAllowedFilterTest extends TestCase { - /** - * @throws Exception - */ - public function testWillAcceptWithoutAuthorization(): void + public function testWillAcceptAllPagesWithoutAuthorization(): void { - $iterator = $this->createMock(RecursiveIterator::class); - $factory = $this->createMock(FactoryInterface::class); - $route = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); - - $navigation = new Navigation($factory, $route, $options, null); - $filter = $this->getMockBuilder(IsAllowedFilter::class) - ->setConstructorArgs([$iterator, $navigation]) - ->onlyMethods(['current']) - ->getMock(); - $filter->method('current')->willReturn(new Page()); - - $this->assertTrue($filter->accept()); + $filter = new IsAllowedFilter($this->getContainer(), $this->getNavigation(null)); + + $this->assertSame(['public', 'private', 'private child', 'other'], $this->getLabels($filter)); } - /** - * @throws Exception - */ - public function testWillAcceptWithAuthorization(): void + public function testWillSkipPageThatIsNotAllowedAndItsSubPages(): void { - $iterator = $this->createMock(RecursiveIterator::class); - $factory = $this->createMock(FactoryInterface::class); - $route = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); - $authorization = $this->createMock(AuthorizationInterface::class); - - $authorization->expects($this->once())->method('isGranted')->willReturn(true); - - $page = new Page(); - $page->setOption('permission', 'test'); - $page->setOption('roles', []); - - $navigation = new Navigation($factory, $route, $options, $authorization); - $filter = $this->getMockBuilder(IsAllowedFilter::class) - ->setConstructorArgs([$iterator, $navigation]) - ->onlyMethods(['current']) - ->getMock(); - $filter->method('current')->willReturn($page); - - $this->assertTrue($filter->accept()); + $authorization = $this->createStub(AuthorizationInterface::class); + $authorization->method('isGranted')->willReturnCallback( + static fn (string $permission): bool => $permission !== 'private' + ); + + $filter = new IsAllowedFilter($this->getContainer(), $this->getNavigation($authorization)); + + $this->assertSame(['public', 'other'], $this->getLabels($filter)); } - /** - * @throws Exception - */ - public function testGetChildren(): void + public function testGetChildrenFiltersTheSubPagesOfTheCurrentPage(): void + { + $authorization = $this->createStub(AuthorizationInterface::class); + $authorization->method('isGranted')->willReturnCallback( + static fn (string $permission): bool => $permission !== 'hidden' + ); + + $visible = new Page(); + $visible->setOptions(['label' => 'visible', 'permission' => 'public']); + $hidden = new Page(); + $hidden->setOptions(['label' => 'hidden', 'permission' => 'hidden']); + $parent = new Page(); + $parent->addPages([$visible, $hidden]); + + $filter = new IsAllowedFilter(new NavigationContainer([$parent]), $this->getNavigation($authorization)); + $filter->rewind(); + + $this->assertSame(['visible'], $this->getLabels($filter->getChildren())); + } + + private function getNavigation(?AuthorizationInterface $authorization): Navigation { - $navigation = $this->createMock(NavigationInterface::class); + return new Navigation( + $this->createStub(FactoryInterface::class), + $this->createStub(RouteHelper::class), + new NavigationOptions(), + $authorization + ); + } + + private function getContainer(): NavigationContainer + { + $public = new Page(); + $public->setOptions(['label' => 'public', 'permission' => 'public']); + + $child = new Page(); + $child->setOptions(['label' => 'private child', 'permission' => 'public']); + + $private = new Page(); + $private->setOptions(['label' => 'private', 'permission' => 'private']); + $private->addPage($child); + + $other = new Page(); + $other->setOptions(['label' => 'other']); - $filter = new IsAllowedFilter(new NavigationContainer([new Page()]), $navigation); - $this->assertSame(IsAllowedFilter::class, $filter->getChildren()::class); + return new NavigationContainer([$public, $private, $other]); } /** - * @throws Exception + * @return list */ - public function testWillCreateFilter(): void + private function getLabels(IsAllowedFilter $filter): array { - $iterator = $this->createMock(RecursiveIterator::class); - $navigation = $this->createMock(NavigationInterface::class); + $iterator = new RecursiveIteratorIterator($filter, RecursiveIteratorIterator::SELF_FIRST); - $filter = new IsAllowedFilter($iterator, $navigation); - $this->assertSame(IsAllowedFilter::class, $filter::class); + return array_map( + static fn (Page $page): string => $page->getLabel(), + iterator_to_array($iterator, false) + ); } } diff --git a/test/NavigationContainerTest.php b/test/NavigationContainerTest.php index 1b3945d..1ffd87d 100644 --- a/test/NavigationContainerTest.php +++ b/test/NavigationContainerTest.php @@ -4,9 +4,14 @@ namespace DotTest\Navigation; +use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\NavigationContainer; use Dot\Navigation\Page; use PHPUnit\Framework\TestCase; +use RecursiveIteratorIterator; + +use function array_map; +use function iterator_to_array; class NavigationContainerTest extends TestCase { @@ -38,7 +43,6 @@ public function testWillReturnCurrentChild(): void $navigationContainer->addPages($pages); $currentPage = $navigationContainer->current(); - $this->assertInstanceOf(Page::class, $currentPage); $this->assertSame($pages[0]->getOption('opt'), $currentPage->getOption('opt')); } @@ -51,7 +55,6 @@ public function testWillReturnNextChild(): void $navigationContainer->next(); $currentPage = $navigationContainer->current(); - $this->assertInstanceOf(Page::class, $currentPage); $this->assertSame($pages[1]->getOption('opt'), $currentPage->getOption('opt')); } @@ -194,8 +197,61 @@ public function testWillFindManyByExistingOption(): void $this->assertSame($pages[0]->getAttribute('opt'), $results[0]->getAttribute('opt')); } + public function testCurrentWillThrowOnEmptyContainer(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The navigation container has no page at the current position'); + (new NavigationContainer())->current(); + } + + public function testHasPagesTellsIfPageHasSubPages(): void + { + $parent = new Page(); + $leaf = new Page(); + $parent->addPage(new Page()); + + $this->assertTrue($parent->hasPages()); + $this->assertFalse($leaf->hasPages()); + $this->assertTrue($parent->hasChildren()); + $this->assertFalse($leaf->hasChildren()); + } + + public function testSelfFirstIterationGivesAllPages(): void + { + $parent = new Page(); + $parent->setOption('label', 'parent'); + $child = new Page(); + $child->setOption('label', 'child'); + $parent->addPage($child); + $leaf = new Page(); + $leaf->setOption('label', 'leaf'); + + $iterator = new RecursiveIteratorIterator( + new NavigationContainer([$parent, $leaf]), + RecursiveIteratorIterator::SELF_FIRST + ); + $labels = array_map( + static fn (Page $page): string => $page->getLabel(), + iterator_to_array($iterator, false) + ); + + $this->assertSame(['parent', 'child', 'leaf'], $labels); + } + + public function testFindIncludesSubPages(): void + { + $parent = new Page(); + $child = new Page(); + $child->setOption('name', 'child'); + $parent->addPage($child); + + $container = new NavigationContainer([$parent]); + $this->assertSame($child, $container->findOneByOption('name', 'child')); + $this->assertSame([$child], $container->findByOption('name', 'child')); + } + /** - * @return Page[] + * @return list */ protected function getTestPages(): array { diff --git a/test/NavigationMiddlewareTest.php b/test/NavigationMiddlewareTest.php index cb3a4e5..a50ddd1 100644 --- a/test/NavigationMiddlewareTest.php +++ b/test/NavigationMiddlewareTest.php @@ -6,7 +6,7 @@ use Dot\Navigation\NavigationMiddleware; use Dot\Navigation\Service\NavigationInterface; -use PHPUnit\Framework\MockObject\Exception; +use Mezzio\Router\RouteResult; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; @@ -14,28 +14,36 @@ class NavigationMiddlewareTest extends TestCase { - /** - * @throws Exception - */ - public function testWillCreateMiddleware(): void + public function testWillPassRouteResultAndQueryParamsToNavigation(): void { + $routeResult = RouteResult::fromRouteFailure([]); + $response = $this->createStub(ResponseInterface::class); + + $request = $this->createStub(ServerRequestInterface::class); + $request->method('getAttribute')->willReturnMap([[RouteResult::class, null, $routeResult]]); + $request->method('getQueryParams')->willReturn(['page' => '2']); + + $handler = $this->createStub(RequestHandlerInterface::class); + $handler->method('handle')->willReturn($response); + $navigation = $this->createMock(NavigationInterface::class); + $navigation->expects($this->once())->method('setRouteResult')->with($routeResult); + $navigation->expects($this->once())->method('setQueryParams')->with(['page' => '2']); $middleware = new NavigationMiddleware($navigation); - $this->assertSame(NavigationMiddleware::class, $middleware::class); + $this->assertSame($response, $middleware->process($request, $handler)); } - /** - * @throws Exception - */ - public function testWillProcessRequest(): void + public function testWillNotSetRouteResultWhenRequestHasNone(): void { + $request = $this->createStub(ServerRequestInterface::class); + $request->method('getQueryParams')->willReturn([]); + $navigation = $this->createMock(NavigationInterface::class); - $request = $this->createMock(ServerRequestInterface::class); - $handler = $this->createMock(RequestHandlerInterface::class); + $navigation->expects($this->never())->method('setRouteResult'); + $navigation->expects($this->once())->method('setQueryParams')->with([]); $middleware = new NavigationMiddleware($navigation); - $response = $middleware->process($request, $handler); - $this->assertContainsOnlyInstancesOf(ResponseInterface::class, [$response]); + $middleware->process($request, $this->createStub(RequestHandlerInterface::class)); } } diff --git a/test/Options/NavigationOptionsTest.php b/test/Options/NavigationOptionsTest.php index b513994..17a6f6e 100644 --- a/test/Options/NavigationOptionsTest.php +++ b/test/Options/NavigationOptionsTest.php @@ -20,7 +20,7 @@ public function testAccessors(): void $options = new NavigationOptions(); $this->assertIsArray($options->getContainers()); $this->assertEmpty($options->getContainers()); - $options->setContainers(['test']); + $options->setContainers(['default' => ['type' => 'array']]); $this->assertIsArray($options->getContainers()); $this->assertCount(1, $options->getContainers()); $this->assertTrue($options->getActiveRecursion()); diff --git a/test/PageTest.php b/test/PageTest.php index 255fbf1..34de478 100644 --- a/test/PageTest.php +++ b/test/PageTest.php @@ -75,6 +75,18 @@ public function testAttributeAccessors(): void $this->assertTrue($page->hasAttributes()); } + public function testGetName(): void + { + $page = new Page(); + $this->assertNull($page->getName()); + $page->setOption('name', 'home'); + $this->assertSame('home', $page->getName()); + $page->setOption('name', 1); + $this->assertSame('1', $page->getName()); + $page->setOption('name', ['invalid']); + $this->assertNull($page->getName()); + } + public function testGetLabel(): void { $page = new Page(); diff --git a/test/Provider/ArrayProviderTest.php b/test/Provider/ArrayProviderTest.php index f006e07..ca2c261 100644 --- a/test/Provider/ArrayProviderTest.php +++ b/test/Provider/ArrayProviderTest.php @@ -4,25 +4,21 @@ namespace DotTest\Navigation\Provider; +use Dot\Navigation\Exception\InvalidArgumentException; use Dot\Navigation\NavigationContainer; use Dot\Navigation\Provider\ArrayProvider; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; class ArrayProviderTest extends TestCase { - public function testWillCreateArrayProvider(): void - { - $provider = new ArrayProvider(); - $this->assertSame(ArrayProvider::class, $provider::class); - } - public function testAccessors(): void { $provider = new ArrayProvider(); $this->assertFalse($provider->hasItems()); - $provider->setItems(['test']); + $provider->setItems([['options' => ['label' => 'test']]]); $this->assertTrue($provider->hasItems()); - $this->assertSame(['test'], $provider->getItems()); + $this->assertSame([['options' => ['label' => 'test']]], $provider->getItems()); } public function testGetContainer(): void @@ -42,5 +38,44 @@ public function testGetContainer(): void $container = $provider->getContainer(); $this->assertSame(NavigationContainer::class, $container::class); $this->assertCount(2, $container->getChildren()); + $this->assertSame($container, $provider->getContainer()); + } + + /** + * @return array + */ + public static function pageKeyProvider(): array + { + return [ + 'attributes' => ['attributes'], + 'options' => ['options'], + 'pages' => ['pages'], + ]; + } + + #[DataProvider('pageKeyProvider')] + public function testWillNotCreatePageWhenKeyIsNotAnArray(string $key): void + { + $provider = new ArrayProvider([ + 'items' => [ + [$key => 'invalid'], + ], + ]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The navigation page key "' . $key . '" must be an array'); + $provider->getContainer(); + } + + public function testWillNotCreatePageWhenSubPageIsNotAnArray(): void + { + $provider = new ArrayProvider([ + 'items' => [ + ['pages' => ['invalid']], + ], + ]); + + $this->expectException(InvalidArgumentException::class); + $provider->getContainer(); } } diff --git a/test/Provider/FactoryTest.php b/test/Provider/FactoryTest.php index 7a40130..2743f45 100644 --- a/test/Provider/FactoryTest.php +++ b/test/Provider/FactoryTest.php @@ -7,122 +7,71 @@ use Dot\Navigation\Exception\RuntimeException; use Dot\Navigation\Provider\ArrayProvider; use Dot\Navigation\Provider\Factory; -use Dot\Navigation\Provider\ProviderInterface; use Dot\Navigation\Provider\ProviderPluginManager; -use Laminas\ServiceManager\Exception\ServiceNotFoundException; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\Navigation\TestData\Container; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; class FactoryTest extends TestCase { - /** - * @throws Exception - */ - public function testWillCreateFactoryWithoutProviderPluginManager(): void - { - $container = $this->createMock(ContainerInterface::class); - - $factory = new Factory($container); - $this->assertSame(Factory::class, $factory::class); - } - - /** - * @throws Exception - */ - public function testWillCreateFactoryWithProviderPluginManager(): void - { - $container = $this->createMock(ContainerInterface::class); - $manager = $this->createMock(ProviderPluginManager::class); - - $factory = new Factory($container, $manager); - $this->assertSame(Factory::class, $factory::class); - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - */ public function testFactoryWillNotCreateProviderWithoutProviderType(): void { - $container = $this->createMock(ContainerInterface::class); - $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Undefined navigation provider type'); - $factory = new Factory($container); - $factory->create([]); + (new Factory(new Container()))->create([]); } - /** - * @throws ContainerExceptionInterface - * @throws Exception - */ public function testFactoryWillNotCreateProviderWithInvalidProviderType(): void { - $container = $this->createMock(ContainerInterface::class); - - $this->expectException(ServiceNotFoundException::class); - $this->expectExceptionMessage( - 'Unable to resolve service "test" to a factory; are you certain you provided it during configuration?' - ); - $factory = new Factory($container); - $factory->create([ + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Navigation provider "test" is not registered'); + (new Factory(new Container()))->create([ 'type' => 'test', ]); } - /** - * @throws ContainerExceptionInterface - * @throws Exception - */ - public function testFactoryWillCreateProviderWithValidProviderTypeAndNoOptions(): void + public function testFactoryWillNotCreateProviderWithInvalidOptions(): void { - $container = $this->createMock(ContainerInterface::class); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The navigation provider options must be an array'); + (new Factory(new Container()))->create([ + 'type' => ArrayProvider::class, + 'options' => 'invalid', + ]); + } - $factory = new Factory($container); - $provider = $factory->create([ + public function testFactoryWillCreateProviderWithValidProviderTypeAndNoOptions(): void + { + $provider = (new Factory(new Container()))->create([ 'type' => ArrayProvider::class, ]); - $this->assertContainsOnlyInstancesOf(ProviderInterface::class, [$provider]); + $this->assertInstanceOf(ArrayProvider::class, $provider); } - /** - * @throws ContainerExceptionInterface - * @throws Exception - */ public function testFactoryWillCreateProviderWithValidProviderTypeAndOptions(): void { - $container = $this->createMock(ContainerInterface::class); - - $factory = new Factory($container); - $provider = $factory->create([ - 'type' => ArrayProvider::class, - 'options' => [], + $provider = (new Factory(new Container()))->create([ + 'type' => 'Array', + 'options' => [ + 'items' => [ + ['options' => ['label' => 'Home']], + ], + ], ]); - $this->assertContainsOnlyInstancesOf(ProviderInterface::class, [$provider]); + $this->assertInstanceOf(ArrayProvider::class, $provider); + $this->assertTrue($provider->getContainer()->hasPages()); } - /** - * @throws Exception - */ - public function testFactoryWillGetProviderPluginManagerWithoutInitialProviderPluginManager(): void + public function testFactoryWillCreateProviderPluginManagerWhenNoneIsGiven(): void { - $container = $this->createMock(ContainerInterface::class); - - $factory = new Factory($container); + $factory = new Factory(new Container()); $this->assertSame(ProviderPluginManager::class, $factory->getProviderPluginManager()::class); } - /** - * @throws Exception - */ - public function testFactoryWillGetProviderPluginManagerWithInitialProviderPluginManager(): void + public function testFactoryWillUseTheGivenProviderPluginManager(): void { - $container = $this->createMock(ContainerInterface::class); - $manager = $this->createMock(ProviderPluginManager::class); + $manager = new ProviderPluginManager(new Container()); - $factory = new Factory($container, $manager); - $this->assertContainsOnlyInstancesOf(ProviderPluginManager::class, [$factory->getProviderPluginManager()]); + $factory = new Factory(new Container(), $manager); + $this->assertSame($manager, $factory->getProviderPluginManager()); } } diff --git a/test/Provider/ProviderPluginManagerTest.php b/test/Provider/ProviderPluginManagerTest.php new file mode 100644 index 0000000..16b25ba --- /dev/null +++ b/test/Provider/ProviderPluginManagerTest.php @@ -0,0 +1,119 @@ + + */ + public static function builtInNameProvider(): array + { + return [ + 'class name' => [ArrayProvider::class], + 'arrayprovider' => ['arrayprovider'], + 'arrayProvider' => ['arrayProvider'], + 'ArrayProvider' => ['ArrayProvider'], + 'array' => ['array'], + 'Array' => ['Array'], + ]; + } + + #[DataProvider('builtInNameProvider')] + public function testWillBuildArrayProviderFromBuiltInName(string $name): void + { + $manager = new ProviderPluginManager(new Container()); + + $this->assertTrue($manager->has($name)); + $this->assertInstanceOf(ArrayProvider::class, $manager->build($name, ['items' => []])); + } + + public function testWillBuildNewInstanceForEachCall(): void + { + $manager = new ProviderPluginManager(new Container()); + + $this->assertNotSame($manager->build('array'), $manager->build('array')); + } + + public function testWillBuildProviderWithFactoryClassAndAlias(): void + { + $manager = new ProviderPluginManager(new Container(), [ + 'factories' => [ + CustomProvider::class => InvokableProviderFactory::class, + ], + 'aliases' => [ + 'custom' => CustomProvider::class, + ], + ]); + + $this->assertInstanceOf(CustomProvider::class, $manager->build('custom')); + } + + public function testWillPassContainerNameAndOptionsToCallableFactory(): void + { + $container = new Container(); + $received = []; + $manager = new ProviderPluginManager($container, [ + 'factories' => [ + 'closure' => static function ( + ContainerInterface $container, + string $requestedName, + ?array $options = null + ) use (&$received): ProviderInterface { + $received = [$container, $requestedName, $options]; + return new CustomProvider(); + }, + ], + ]); + + $manager->build('closure', ['key' => 'value']); + $this->assertSame([$container, 'closure', ['key' => 'value']], $received); + } + + public function testWillNotBuildUnknownProvider(): void + { + $manager = new ProviderPluginManager(new Container()); + + $this->assertFalse($manager->has(CustomProvider::class)); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Navigation provider "' . CustomProvider::class . '" is not registered'); + $manager->build(CustomProvider::class); + } + + public function testWillNotBuildWhenFactoryReturnsWrongObject(): void + { + $manager = new ProviderPluginManager(new Container(), [ + 'factories' => [ + 'wrong' => static fn (): stdClass => new stdClass(), + ], + ]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage( + 'can only create instances of ' . ProviderInterface::class . '; stdClass is invalid' + ); + $manager->build('wrong'); + } + + public function testInvokableProviderFactoryWillNotCreateClassThatIsNotProvider(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('"' . NavigationContainer::class . '" is not a navigation provider class'); + (new InvokableProviderFactory())(new Container(), NavigationContainer::class); + } +} diff --git a/test/Service/NavigationTest.php b/test/Service/NavigationTest.php index 865fb24..17c90b7 100644 --- a/test/Service/NavigationTest.php +++ b/test/Service/NavigationTest.php @@ -6,341 +6,353 @@ use Dot\Authorization\AuthorizationInterface; use Dot\Helpers\Route\RouteHelper; +use Dot\Navigation\Exception\InvalidArgumentException; use Dot\Navigation\Exception\RuntimeException; -use Dot\Navigation\NavigationContainer; use Dot\Navigation\Options\NavigationOptions; use Dot\Navigation\Page; -use Dot\Navigation\Provider\ArrayProvider; +use Dot\Navigation\Provider\Factory; use Dot\Navigation\Provider\FactoryInterface; use Dot\Navigation\Service\Navigation; -use Dot\Navigation\Service\NavigationInterface; +use DotTest\Navigation\TestData\Container; use Mezzio\Router\Route; use Mezzio\Router\RouteResult; -use PHPUnit\Framework\MockObject\Exception; use PHPUnit\Framework\TestCase; +use Psr\Http\Message\UriInterface; use Psr\Http\Server\MiddlewareInterface; class NavigationTest extends TestCase { - /** - * @throws Exception - */ - public function testNavigationWillInitialize(): void - { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); - - $navigation = new Navigation($factory, $routeHelper, $options); - $this->assertContainsOnlyInstancesOf(NavigationInterface::class, [$navigation]); - } - - /** - * @throws Exception - */ public function testAccessors(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); + $navigation = $this->getNavigation(); $routeResult = RouteResult::fromRouteFailure([]); - $navigation = new Navigation($factory, $routeHelper, $options); $this->assertNull($navigation->getRouteResult()); $navigation->setRouteResult($routeResult); - $this->assertInstanceOf(RouteResult::class, $navigation->getRouteResult()); + $this->assertSame($routeResult, $navigation->getRouteResult()); $this->assertTrue($navigation->getIsActiveRecursion()); $navigation->setIsActiveRecursion(false); $this->assertFalse($navigation->getIsActiveRecursion()); } - /** - * @throws Exception - */ public function testNavigationWillNotGetInvalidContainer(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); - $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Container `test` is not defined'); - $navigation = new Navigation($factory, $routeHelper, $options); - $navigation->getContainer('test'); + $this->getNavigation()->getContainer('test'); } - /** - * @throws Exception - */ - public function testNavigationWillGetValidContainer(): void + public function testNavigationWillGetValidContainerOnce(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - - $options = new NavigationOptions([ - 'containers' => [ - 'default' => [ - 'type' => ArrayProvider::class, + $navigation = new Navigation( + new Factory(new Container()), + $this->createStub(RouteHelper::class), + new NavigationOptions([ + 'containers' => [ + 'default' => [ + 'type' => 'array', + 'options' => ['items' => [['options' => ['label' => 'Home']]]], + ], ], - ], - ]); + ]) + ); - $navigation = new Navigation($factory, $routeHelper, $options); - $this->assertContainsOnlyInstancesOf(NavigationContainer::class, [$navigation->getContainer('default')]); + $container = $navigation->getContainer('default'); + $this->assertSame('Home', $container->current()->getLabel()); + $this->assertSame($container, $navigation->getContainer('default')); } - /** - * @throws Exception - */ public function testIsAllowedWillReturnTrueWithoutAuthorization(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); + $page = new Page(); + $page->setOption('permission', 'test'); - $navigation = new Navigation($factory, $routeHelper, $options); - $this->assertTrue($navigation->isAllowed(new Page())); + $this->assertTrue($this->getNavigation()->isAllowed($page)); } - /** - * @throws Exception - */ - public function testIsAllowedWillReturnTrueWithAuthorizationWhenPageHasNoPermission(): void + public function testIsAllowedWillReturnTrueWhenPageHasNoPermission(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); $authorization = $this->createMock(AuthorizationInterface::class); + $authorization->expects($this->never())->method('isGranted'); - $navigation = new Navigation($factory, $routeHelper, $options, $authorization); - $this->assertTrue($navigation->isAllowed(new Page())); + $this->assertTrue($this->getNavigation($authorization)->isAllowed(new Page())); } - /** - * @throws Exception - */ - public function testIsAllowedWillReturnTrueWithAuthorizationWhenPageHasNoRoles(): void + public function testIsAllowedWillCheckPermissionWithoutRoles(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); $authorization = $this->createMock(AuthorizationInterface::class); + $authorization->expects($this->once())->method('isGranted')->with('view')->willReturn(false); + + $page = new Page(); + $page->setOption('permission', 'view'); + $this->assertFalse($this->getNavigation($authorization)->isAllowed($page)); + } - $authorization->expects($this->once())->method('isGranted')->willReturn(true); + public function testIsAllowedWillCheckPermissionWithRoles(): void + { + $authorization = $this->createMock(AuthorizationInterface::class); + $authorization->expects($this->once())->method('isGranted')->with('view', ['admin'])->willReturn(true); $page = new Page(); - $page->setOption('permission', ''); - $navigation = new Navigation($factory, $routeHelper, $options, $authorization); - $this->assertTrue($navigation->isAllowed($page)); + $page->setOptions(['permission' => 'view', 'roles' => ['admin']]); + $this->assertTrue($this->getNavigation($authorization)->isAllowed($page)); } - /** - * @throws Exception - */ - public function testIsAllowedWillReturnTrueWithAuthorizationWhenPageHasPermissionsAndRoles(): void + public function testIsAllowedWillAcceptRolesAsString(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); $authorization = $this->createMock(AuthorizationInterface::class); + $authorization->expects($this->once())->method('isGranted')->with('view', ['admin'])->willReturn(true); - $authorization->expects($this->once())->method('isGranted')->willReturn(true); + $page = new Page(); + $page->setOptions(['permission' => 'view', 'roles' => 'admin']); + $this->assertTrue($this->getNavigation($authorization)->isAllowed($page)); + } + public function testIsAllowedWillNotAcceptInvalidRoles(): void + { $page = new Page(); - $page->setOption('permission', ''); - $page->setOption('roles', []); - $navigation = new Navigation($factory, $routeHelper, $options, $authorization); - $this->assertTrue($navigation->isAllowed($page)); + $page->setOptions(['permission' => 'view', 'roles' => 1]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The navigation page option "roles" must be a string or an array'); + $this->getNavigation($this->createStub(AuthorizationInterface::class))->isAllowed($page); } - /** - * @throws Exception - */ public function testIsActiveWillCacheResults(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); - - $navigation = new Navigation($factory, $routeHelper, $options); - $this->assertIsArray($navigation->getIsActiveCache()); - $this->assertEmpty($navigation->getIsActiveCache()); + $navigation = $this->getNavigation(); + $this->assertSame([], $navigation->getIsActiveCache()); $navigation->isActive(new Page()); - $this->assertIsArray($navigation->getIsActiveCache()); $this->assertCount(1, $navigation->getIsActiveCache()); } - /** - * @throws Exception - */ public function testIsActiveWillReturnFalseWithoutRouteResult(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); - - $navigation = new Navigation($factory, $routeHelper, $options); - $this->assertFalse($navigation->isActive(new Page())); + $this->assertFalse($this->getNavigation()->isActive($this->getRoutePage('test'))); } - /** - * @throws Exception - */ public function testIsActiveWillReturnFalseWithoutSuccessfulRouteResult(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); - $routeResult = RouteResult::fromRouteFailure([]); + $navigation = $this->getNavigation(); + $navigation->setRouteResult(RouteResult::fromRouteFailure([])); - $navigation = new Navigation($factory, $routeHelper, $options); - $navigation->setRouteResult($routeResult); - $this->assertFalse($navigation->isActive(new Page())); + $this->assertFalse($navigation->isActive($this->getRoutePage('test'))); } - /** - * @throws Exception - */ public function testIsActiveWillReturnFalseWhenPageHasNoRoute(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); - $routeResult = RouteResult::fromRoute( - new Route( - 'path', - $this->createMock(MiddlewareInterface::class), - ) - ); + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('test')); - $navigation = new Navigation($factory, $routeHelper, $options); - $navigation->setRouteResult($routeResult); $this->assertFalse($navigation->isActive(new Page())); } - /** - * @throws Exception - */ public function testIsActiveWillReturnTrueWhenRequestedRouteMatchesPageRoute(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); - $routeResult = RouteResult::fromRoute( - new Route( - 'path', - $this->createMock(MiddlewareInterface::class), - Route::HTTP_METHOD_ANY, - 'test' - ) - ); + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('test')); + $navigation->setIsActiveRecursion(false); - $page = new Page(); - $page->setOption('route', [ - 'route_name' => 'test', - ]); - $navigation = new Navigation($factory, $routeHelper, $options); - $navigation->setRouteResult($routeResult); + $this->assertTrue($navigation->isActive($this->getRoutePage('test'))); + } + + public function testIsActiveWillReturnTrueWhenRequestedRouteMatchesChildPageRoute(): void + { + $parentPage = $this->getRoutePage('parent'); + $parentPage->addPage($this->getRoutePage('child')); + + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('child')); + + $this->assertTrue($navigation->isActive($parentPage)); + } + + public function testIsActiveWillNotCheckChildPagesWithoutRecursion(): void + { + $parentPage = $this->getRoutePage('parent'); + $parentPage->addPage($this->getRoutePage('child')); + + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('child')); $navigation->setIsActiveRecursion(false); + + $this->assertFalse($navigation->isActive($parentPage)); + } + + public function testIsActiveComparesParamKeys(): void + { + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('list', ['page' => '1'])); + + // Keep both pages in variables. The active cache uses spl_object_hash(), which PHP reuses for freed objects. + $otherKey = $this->getRoutePage('list', ['id' => 1]); + $sameKey = $this->getRoutePage('list', ['page' => 1]); + $this->assertFalse($navigation->isActive($otherKey)); + $this->assertTrue($navigation->isActive($sameKey)); + } + + public function testIsActiveRequiresEachRequestParamOnThePage(): void + { + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('list', ['id' => '1'])); + + $this->assertFalse($navigation->isActive($this->getRoutePage('list'))); + } + + public function testIsActiveSkipsIgnoredParams(): void + { + $page = new Page(); + $page->setOption('route', ['route_name' => 'list', 'ignore_params' => ['id']]); + + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('list', ['id' => '1'])); + $this->assertTrue($navigation->isActive($page)); } - /** - * @throws Exception - */ - public function testIsActiveWillReturnTrueWhenRequestedRouteMatchesChildPageRoute(): void + public function testIsActiveUsesQueryParamsAndNotGlobalGet(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); - $routeResult = RouteResult::fromRoute( - new Route( - 'path', - $this->createMock(MiddlewareInterface::class), - Route::HTTP_METHOD_ANY, - 'child' - ) - ); + $_GET['tab'] = 'other'; + + $page = new Page(); + $page->setOption('route', ['route_name' => 'list', 'query_params' => ['tab' => 'main']]); + + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('list')); + $navigation->setQueryParams(['tab' => 'main']); + $this->assertTrue($navigation->isActive($page)); + + $navigation->setQueryParams(['tab' => 'other']); + $this->assertFalse($navigation->isActive($page)); - $childPage = new Page(); - $childPage->setOption('route', [ - 'route_name' => 'child', - ]); + unset($_GET['tab']); + } + + public function testIsActiveAcceptsArrayQueryValue(): void + { + $page = new Page(); + $page->setOption('route', ['route_name' => 'list', 'query_params' => ['tags' => ['a', 'b']]]); + + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('list')); + $navigation->setQueryParams(['tags' => ['a', 'b']]); + + $this->assertTrue($navigation->isActive($page)); + } + + public function testIsActiveCacheIsClearedByNewRouteResult(): void + { + $page = $this->getRoutePage('first'); + $navigation = $this->getNavigation(); + + $navigation->setRouteResult($this->getRouteResult('first')); + $this->assertTrue($navigation->isActive($page)); + + $navigation->setRouteResult($this->getRouteResult('second')); + $this->assertFalse($navigation->isActive($page)); + } + + public function testParentWithoutRouteIsActiveWhenChildIsActive(): void + { $parentPage = new Page(); - $parentPage->setOption('route', [ - 'route_name' => 'parent', - ]); - $parentPage->addPage($childPage); - $navigation = new Navigation($factory, $routeHelper, $options); - $navigation->setRouteResult($routeResult); - $navigation->setIsActiveRecursion(true); + $parentPage->setOption('uri', '#'); + $parentPage->addPage($this->getRoutePage('child')); + + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('child')); + $this->assertTrue($navigation->isActive($parentPage)); } - /** - * @throws Exception - */ - public function testGetHrefWillCacheResults(): void + public function testRouteOptionWithoutRouteNameIsNotActive(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); + $page = new Page(); + $page->setOption('route', ['route_params' => []]); - $navigation = new Navigation($factory, $routeHelper, $options); - $this->assertIsArray($navigation->getHrefCache()); - $this->assertEmpty($navigation->getHrefCache()); + $navigation = $this->getNavigation(); + $navigation->setRouteResult($this->getRouteResult('test')); + + $this->assertFalse($navigation->isActive($page)); + } + + public function testGetHrefWillCacheResults(): void + { + $navigation = $this->getNavigation(); + $this->assertSame([], $navigation->getHrefCache()); $page = new Page(); $page->setOption('uri', 'page1'); $navigation->getHref($page); - $this->assertIsArray($navigation->getHrefCache()); $this->assertCount(1, $navigation->getHrefCache()); - $page = new Page(); - $page->setOption('route', [ - 'route_name' => 'page2', - ]); - $navigation->getHref($page); - $this->assertIsArray($navigation->getHrefCache()); + $navigation->getHref($this->getRoutePage('page2')); $this->assertCount(2, $navigation->getHrefCache()); } - /** - * @throws Exception - */ - public function testWillNotGetHrefForInvalidPage(): void + public function testWillGetHrefForValidPage(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); + $navigation = $this->getNavigation(); - $navigation = new Navigation($factory, $routeHelper, $options); - - $this->expectException(RuntimeException::class); - $this->expectExceptionMessageMatches('/^Unable to assemble href for navigation page.*/'); $page = new Page(); - $navigation->getHref($page); + $page->setOption('uri', 'page1'); + $this->assertSame('page1', $navigation->getHref($page)); + + $this->assertSame('/generated', $navigation->getHref($this->getRoutePage('page2'))); } - /** - * @throws Exception - */ - public function testWillGetHrefForValidPage(): void + public function testWillGetHrefForUriZero(): void { - $factory = $this->createMock(FactoryInterface::class); - $routeHelper = $this->createMock(RouteHelper::class); - $options = $this->createMock(NavigationOptions::class); + $page = new Page(); + $page->setOption('uri', '0'); - $navigation = new Navigation($factory, $routeHelper, $options); + $this->assertSame('0', $this->getNavigation()->getHref($page)); + } + public function testWillNotGetHrefForInvalidPage(): void + { $page = new Page(); - $page->setOption('uri', 'page1'); - $this->assertSame('page1', $navigation->getHref($page)); + $page->setOption('name', 7); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Unable to assemble href for navigation page "7"'); + $this->getNavigation()->getHref($page); + } + + private function getNavigation(?AuthorizationInterface $authorization = null): Navigation + { + $uri = $this->createStub(UriInterface::class); + $uri->method('__toString')->willReturn('/generated'); + + $routeHelper = $this->createStub(RouteHelper::class); + $routeHelper->method('generateUri')->willReturn($uri); + + return new Navigation( + $this->createStub(FactoryInterface::class), + $routeHelper, + new NavigationOptions(), + $authorization + ); + } + + /** + * @param array $routeParams + */ + private function getRoutePage(string $routeName, array $routeParams = []): Page + { $page = new Page(); - $page->setOption('route', [ - 'route_name' => 'page2', - ]); - $this->assertIsString($navigation->getHref($page)); + $page->setOption('route', ['route_name' => $routeName, 'route_params' => $routeParams]); + + return $page; + } + + /** + * @param array $params + */ + private function getRouteResult(string $routeName, array $params = []): RouteResult + { + return RouteResult::fromRoute( + new Route('/path', $this->createStub(MiddlewareInterface::class), Route::HTTP_METHOD_ANY, $routeName), + $params + ); } } diff --git a/test/TestData/Container.php b/test/TestData/Container.php new file mode 100644 index 0000000..39f1c8f --- /dev/null +++ b/test/TestData/Container.php @@ -0,0 +1,38 @@ + $services + */ + public function __construct( + private array $services = [], + ) { + } + + public function get(string $id): mixed + { + if (! $this->has($id)) { + throw new ServiceNotFoundException(sprintf('Service "%s" is not in the container', $id)); + } + + return $this->services[$id]; + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services); + } +} diff --git a/test/TestData/CustomProvider.php b/test/TestData/CustomProvider.php new file mode 100644 index 0000000..f7dad7a --- /dev/null +++ b/test/TestData/CustomProvider.php @@ -0,0 +1,19 @@ +createStub(NavigationInterface::class); + $container = new NavigationContainer(); + + $template = $this->createMock(TemplateRendererInterface::class); + $template->expects($this->once()) + ->method('render') + ->with('partial::menu', ['container' => $container, 'navigation' => $navigation, 'extra' => 'value']) + ->willReturn('
    '); + + $renderer = new NavigationRenderer($navigation, $template, new NavigationOptions()); + $this->assertSame('
      ', $renderer->renderPartial($container, 'partial::menu', ['extra' => 'value'])); + } + + public function testWillRenderTemplateWithContainerFromNavigation(): void + { + $container = new NavigationContainer(); + $navigation = $this->createStub(NavigationInterface::class); + $navigation->method('getContainer')->willReturn($container); + + $template = $this->createMock(TemplateRendererInterface::class); + $template->expects($this->once()) + ->method('render') + ->with('app::menu', ['container' => $container, 'navigation' => $navigation]) + ->willReturn(''); + + $renderer = new NavigationRenderer($navigation, $template, new NavigationOptions()); + $this->assertSame('', $renderer->render('default', 'app::menu')); + } + + public function testWillNotRenderEmptyTemplateName(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The template name must not be empty'); + $this->getRenderer()->render(new NavigationContainer(), ''); + } + + public function testWillNotRenderEmptyPartialName(): void { - $navigation = $this->createMock(NavigationInterface::class); - $template = $this->createMock(TemplateRendererInterface::class); - $options = $this->createMock(NavigationOptions::class); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The partial name must not be empty'); + $this->getRenderer()->renderPartial(new NavigationContainer(), ''); + } - $renderer = new NavigationRenderer($navigation, $template, $options); - $this->assertSame(NavigationRenderer::class, $renderer::class); + public function testPartialAccessors(): void + { + $renderer = $this->getRenderer(); + $this->assertNull($renderer->getPartial()); + $renderer->setPartial('partial::menu'); + $this->assertSame('partial::menu', $renderer->getPartial()); } /** - * @throws Exception + * @return array, string}> */ - public function testWillRenderPartial(): void + public static function htmlAttributesProvider(): array { - $navigation = $this->createMock(NavigationInterface::class); - $template = $this->createMock(TemplateRendererInterface::class); - $options = $this->createMock(NavigationOptions::class); - - $renderer = new NavigationRenderer($navigation, $template, $options); - $html = $renderer->renderPartial(new NavigationContainer(), 'partial'); - $this->assertIsString($html); + return [ + 'no attributes' => [[], ''], + 'string' => [['class' => 'nav-link', 'target' => '_blank'], ' class="nav-link" target="_blank"'], + 'escaped string' => [['href' => '#', 'title' => 'a"b'], ' href="#" title="a"b"'], + 'list of strings' => [['class' => ['nav-link', 'active']], ' class="nav-link active"'], + 'event as JSON' => [['onclick' => ['a' => 1]], ' onclick="{"a":1}"'], + 'boolean as name' => [['hidden' => 'hidden'], ' hidden="hidden"'], + ]; } /** - * @throws Exception + * @param array $attributes */ - public function testWillRenderTemplate(): void + #[DataProvider('htmlAttributesProvider')] + public function testHtmlAttributes(array $attributes, string $expected): void { - $navigation = $this->createMock(NavigationInterface::class); - $template = $this->createMock(TemplateRendererInterface::class); - $options = $this->createMock(NavigationOptions::class); + $this->assertSame($expected, $this->getRenderer()->htmlAttributes($attributes)); + } - $renderer = new NavigationRenderer($navigation, $template, $options); - $html = $renderer->render(new NavigationContainer(), 'template'); - $this->assertIsString($html); + private function getRenderer(): NavigationRenderer + { + return new NavigationRenderer( + $this->createStub(NavigationInterface::class), + $this->createStub(TemplateRendererInterface::class), + new NavigationOptions() + ); } }