diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index 89e83df..5cd87b3 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v3 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -49,6 +49,6 @@ jobs: run: vendor/bin/phpunit --colors=always --coverage-clover clover.xml - name: Send code coverage report to Codecov.io - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v7 with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 9976515..b428224 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -4,7 +4,7 @@ on: name: Run PHPStan checks jobs: - mutation: + static-analysis: name: PHPStan ${{ matrix.php }}-${{ matrix.os }} runs-on: ${{ matrix.os }} @@ -15,20 +15,20 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 with: php-version: "${{ matrix.php }}" - coverage: pcov + coverage: none ini-values: assert.exception=1, zend.assertions=1, error_reporting=-1, log_errors_max_len=0, display_errors=On tools: composer:v2, cs2pr @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} diff --git a/.gitignore b/.gitignore index a069e11..e390e21 100644 --- a/.gitignore +++ b/.gitignore @@ -33,6 +33,7 @@ fabric.properties composer.phar /vendor/ .phpcs-cache +.phpunit.cache .phpunit.result.cache # Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file 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 2226af0..c160bb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,124 +1,515 @@ +# Changelog + +## 4.0.0 - TBD + +### Changed + +* Requires PHP 8.3, 8.4, 8.5 or 8.6. +* `RouteHelperFactory` throws `Dot\Helpers\Exception\RuntimeException` when the container returns a service of the wrong type. +* Requires `mezzio/mezzio-helpers` 5.21.0 or later and `laminas/laminas-diactoros` 3.10.0 or later. +* Requires `psr/container` directly. +* Uses PHPUnit 12 and PHPStan level 8. +* Uses `actions/checkout@v7`, `actions/cache@v6` and `codecov/codecov-action@v7` in the workflows. + +### Added + +* `Dot\Helpers\Exception\ExceptionInterface` and `Dot\Helpers\Exception\RuntimeException`. +* Array shape types for `RouteHelper::generateUri()` and `ConfigProvider`. +* Usage and upgrade pages in the v4 documentation. + +### Deprecated + +* Nothing + +### Removed + +* PHP 8.2 support. +* The requirement `laminas/laminas-servicemanager`. The factories work with any PSR-11 container. + +### Fixed + +* `RouteHelper::appendQueryParam()` encoded the value two times. +* `RouteHelper::appendQueryParam()` changed the names of other query parameters and removed the query `0`. + +## 3.9.0 - 2025-10-31 + +### Changed + +* Nothing + +### Added + +* PHP 8.4 and 8.5 support (#36). + +### Deprecated + +* Nothing + +### Removed + +* PHP 8.1 support (#36). + +### Fixed + +* Nothing + +## 3.8.0 - 2025-03-07 + +### Changed + +* Replaced Psalm with PHPStan (#34). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.7.1 - 2025-01-28 + +### Changed + +* Psalm 6.x (#32). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.7.0 - 2025-01-20 + +### Changed + +* Nothing + +### Added + +* Support for `laminas/laminas-servicemanager` 4.x (#30). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.6.0 - 2024-10-28 + +### Changed + +* Documentation linting, fixed `index.md`, removed a badge that did not work (#28). + +### Added + +* PHP 8.4 support (#28). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.5.1 - 2024-06-29 + +### Changed + +* README note that the package is a wrapper of `mezzio/mezzio-helpers` (#26). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.5.0 - 2024-05-03 + +### Changed + +* Nothing + +### Added + +* Documentation (#24). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.3 - 2024-01-23 + +### Changed + +* Updated dependencies (#22). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.2 - 2023-11-29 + +### Changed + +* Nothing + +### Added + +* PHP 8.3 support (#20). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.1 - 2023-08-24 + +### Changed + +* `psr/http-message` 2.x allowed (#16). + +### Added + +* Codecov and its badge (#16, #18). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.0 - 2023-07-25 + +### Changed + +* A return type (#13). + +### Added + +* Coding standard check, unit tests, Psalm and static analysis (#13). + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.3.0 - 2023-03-29 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* `laminas/laminas-dependency-plugin` (#12). + +### Fixed + +* Nothing + +## 3.2.0 - 2022-04-14 + +### Changed + +* Updated package versions (#10). + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + ## 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. ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed + * bump min version of laminas/laminas-dependency-plugin +## 3.0.1 - 2020-04-23 + +### Changed + +* Dependencies at their latest versions, keywords, license file. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.0.0 - 2020-04-16 + +### Changed + +* Requires PHP `^7.4`. + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + ## 2.0.0 - 2020-01-30 ### Changed + * Laminas and Mezzio migration. ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Support ### Fixed -* Nothing +* Nothing ## 1.0.0 - 2018-04-12 ### Changed + * updated to dependency expressive helpers > 5.0 ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 0.2.1 - 2017-03-18 ### Changed + * updated to dependency expressive helpers > 4.0 ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 0.2.0 - 2017-03-15 ### Changed + * Updated factories to PSR11 container typehint ### Added + * RouteHelper class, derived from previous RouteOptionHelper class and updated * RouteHelper `uriEquals` and `appendQueryParam` methods ### Deprecated + * Nothing ### Removed + * RouteOptionsHelper class(moved to RouteHelper) * UriHelperTrait class(its functionality was moved to RouteHelper) ### Fixed -* Nothing +* Nothing ## 0.1.1 - 2017-03-11 Updated php file headers doc blocks ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 0.1.0 - 2017-03-07 Initial tagged release ### Added + * Everything ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed + * Nothing diff --git a/README.md b/README.md index 1c4f7ab..c18f1ff 100644 --- a/README.md +++ b/README.md @@ -11,20 +11,26 @@ Documentation is available at: https://docs.dotkernel.org/dot-helpers/. ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-helpers) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-helpers/3.9.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-helpers/4.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-helpers)](https://github.com/dotkernel/dot-helpers/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-helpers)](https://github.com/dotkernel/dot-helpers/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-helpers)](https://github.com/dotkernel/dot-helpers/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-helpers)](https://github.com/dotkernel/dot-helpers/blob/3.0/LICENSE.md) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-helpers)](https://github.com/dotkernel/dot-helpers/blob/4.0/LICENSE.md) -[![Build Static](https://github.com/dotkernel/dot-helpers/actions/workflows/continuous-integration.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-helpers/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-helpers/actions/workflows/continuous-integration.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-helpers/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-helpers/graph/badge.svg?token=LIN5FVL5QP)](https://codecov.io/gh/dotkernel/dot-helpers) -[![PHPStan](https://github.com/dotkernel/dot-helpers/actions/workflows/static-analysis.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-helpers/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-helpers/actions/workflows/static-analysis.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-helpers/actions/workflows/static-analysis.yml) ## Requirements -- **PHP**: 8.2, 8.3, 8.4, or 8.5 +- **PHP**: 8.3, 8.4, 8.5, or 8.6 + +The factories work with any PSR-11 container that accepts a factory for each service key. This package does not install `laminas/laminas-servicemanager`. + +## Upgrading from 3.x + +Version 4.0 changes the output of `appendQueryParam()` and removes PHP 8.2 support. Read the [upgrade guide](https://docs.dotkernel.org/dot-helpers/v4/upgrading/) before you update. ## Install diff --git a/SECURITY.md b/SECURITY.md index 5831406..d971beb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,9 +2,9 @@ ## Supported Versions - | Version | Supported | PHP Version | |---------|--------------------|-------------------------------------------------------------------------------------------------------------| +| 4.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-helpers/4.0.0) | | 3.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-helpers/3.9.0) | | <= 2.x | :x: | | @@ -26,7 +26,6 @@ release prior to any public exposure; this helps protect the project's users, and provides them with a chance to upgrade and/or update in order to protect their applications. - ## Policy If we verify a reported security vulnerability, our policy is: diff --git a/composer.json b/composer.json index d1817ec..4ace35d 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "dotkernel/dot-helpers", "type": "library", - "description": "Dotkernel helper component providing various helper structures and classes", + "description": "Dotkernel helper component that generates and compares route URIs, for any PSR-11 container", "license": "MIT", "homepage": "https://github.com/dotkernel/dot-helpers", "keywords": [ @@ -22,17 +22,17 @@ } }, "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", - "laminas/laminas-diactoros": "^3.3.0", - "laminas/laminas-servicemanager": "^3.22.1 || ^4.0", - "mezzio/mezzio-helpers": "^5.16.0", - "psr/http-message": "^1.0 || ^2.0" + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", + "laminas/laminas-diactoros": "^3.10.0", + "mezzio/mezzio-helpers": "^5.21.0", + "psr/container": "^1.1 || ^2.0", + "psr/http-message": "^1.1 || ^2.0" }, "require-dev": { "laminas/laminas-coding-standard": "^3.0", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.5.9" + "phpunit/phpunit": "^12.5.22" }, "autoload": { "psr-4": { diff --git a/docs/book/v4/configuration.md b/docs/book/v4/configuration.md new file mode 100644 index 0000000..f46a272 --- /dev/null +++ b/docs/book/v4/configuration.md @@ -0,0 +1,33 @@ +# Configuration + +## Requirements + +- **PHP**: 8.3, 8.4, 8.5, or 8.6 + +## Register ConfigProvider + +Next, register the package's `ConfigProvider` to your application config. + +```php +Dot\Helpers\ConfigProvider::class, +``` + +> Make sure to register the package under the `// DK packages` section. + +## Container + +The `ConfigProvider` registers one factory: + +```php +'dependencies' => [ + 'factories' => [ + Dot\Helpers\Route\RouteHelper::class => Dot\Helpers\Factory\RouteHelperFactory::class, + ], +], +``` + +`RouteHelperFactory` works with any PSR-11 container that accepts a factory for each service key. The container must also supply `Mezzio\Helper\UrlHelper` and `Mezzio\Helper\ServerUrlHelper`. The `ConfigProvider` of `mezzio/mezzio-helpers` registers both. + +This package does not install `laminas/laminas-servicemanager`. If your application uses Laminas Service Manager, require it in your application. + +If the container returns a service of the wrong type, the factory throws `Dot\Helpers\Exception\RuntimeException`. diff --git a/docs/book/v4/installation.md b/docs/book/v4/installation.md new file mode 100644 index 0000000..3480171 --- /dev/null +++ b/docs/book/v4/installation.md @@ -0,0 +1,7 @@ +# Installation + +Install dotkernel/dot-helpers by executing the following Composer command in your project directory: + +```shell +composer require dotkernel/dot-helpers +``` diff --git a/docs/book/v4/overview.md b/docs/book/v4/overview.md new file mode 100644 index 0000000..a91e144 --- /dev/null +++ b/docs/book/v4/overview.md @@ -0,0 +1,21 @@ +# Overview + +Dotkernel's helper component, used to handle urls. + +> dot-helpers is a wrapper on top of [mezzio/mezzio-helpers](https://packagist.org/packages/mezzio/mezzio-helpers) + +The factories work with any PSR-11 container that accepts a factory for each service key. + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-helpers) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-helpers/4.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-helpers)](https://github.com/dotkernel/dot-helpers/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-helpers)](https://github.com/dotkernel/dot-helpers/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-helpers)](https://github.com/dotkernel/dot-helpers/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-helpers)](https://github.com/dotkernel/dot-helpers/blob/4.0/LICENSE.md) + +[![Build Static](https://github.com/dotkernel/dot-helpers/actions/workflows/continuous-integration.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-helpers/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-helpers/graph/badge.svg?token=LIN5FVL5QP)](https://codecov.io/gh/dotkernel/dot-helpers) +[![PHPStan](https://github.com/dotkernel/dot-helpers/actions/workflows/static-analysis.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-helpers/actions/workflows/static-analysis.yml) diff --git a/docs/book/v4/upgrading.md b/docs/book/v4/upgrading.md new file mode 100644 index 0000000..594223b --- /dev/null +++ b/docs/book/v4/upgrading.md @@ -0,0 +1,26 @@ +# Upgrading from 3.x to 4.0 + +Read this table before you update `dotkernel/dot-helpers` to 4.0. + +| Change | Symptom | Fix | +| --- | --- | --- | +| PHP 8.2 is not supported | Composer does not install 4.0 on PHP 8.2 | Use PHP 8.3 or later | +| `laminas/laminas-servicemanager` is not installed with this package | `Class "Laminas\ServiceManager\ServiceManager" not found` in an application that did not require it | Run `composer require laminas/laminas-servicemanager`, or use a different PSR-11 container | +| `appendQueryParam()` encodes the value one time, with `%20` for a space | Code that decodes the value two times gets a wrong value. Tests that compare the old string fail | Decode the value one time. Update the expected strings | +| `appendQueryParam()` keeps the other parameters as they are | Names with `.` or a space are no longer changed to `_`. A query `0` is kept | Read the parameter by its real name | +| `RouteHelperFactory` checks the service types | `Dot\Helpers\Exception\RuntimeException` instead of `TypeError` when the container returns a wrong type. The container can wrap it in its own exception | Register `UrlHelper` and `ServerUrlHelper` correctly. Catch the new exception if necessary | +| Minimum versions | Composer installs `mezzio/mezzio-helpers` 5.21 or later and `laminas/laminas-diactoros` 3.10 or later | Update these packages in the application | + +## appendQueryParam() output + +The same call returns a different query in 4.0: + +| Query | Name | Value | 3.x | 4.0 | +| --- | --- | --- | --- | --- | +| empty | `q` | `a b` | `q=a%2Bb` | `q=a%20b` | +| empty | `q` | `x&y=z` | `q=x%2526y%253Dz` | `q=x%26y%3Dz` | +| `a.b=1&c%20d=2` | `q` | `v` | `a_b=1&c_d=2&q=v` | `a.b=1&c%20d=2&q=v` | +| `0` | `q` | `v` | `q=v` | `0&q=v` | +| `q=old&r=1` | `q` | `new` | `q=new&r=1` | `q=new&r=1` | + +In 3.x, `parse_str()` gives back `a+b` for the value `a b`. In 4.0, it gives back `a b`. diff --git a/docs/book/v4/usage.md b/docs/book/v4/usage.md new file mode 100644 index 0000000..38c07d3 --- /dev/null +++ b/docs/book/v4/usage.md @@ -0,0 +1,66 @@ +# Usage + +Get `Dot\Helpers\Route\RouteHelper` from the container and inject it in your class. + +The examples below use a route named `user.view` with the path `/user/{id}`. The current request URI is `https://example.com`. + +## Generate a URI + +`generateUri()` returns a `Psr\Http\Message\UriInterface`. All keys of the array are optional. + +| Key | Type | Description | +| --- | --- | --- | +| `route_name` | `non-empty-string` or `null` | The route name. `null` uses the matched route | +| `route_params` | `array` | The values of the route parameters | +| `query_params` | `array` | The query parameters | +| `fragment_id` | `string` or `null` | The fragment, without `#` | +| `options` | `array` | The options of `Mezzio\Helper\UrlHelper::generate()` | + +```php +$uri = $routeHelper->generateUri([ + 'route_name' => 'user.view', + 'route_params' => ['id' => '5'], + 'query_params' => ['tab' => 'orders'], + 'fragment_id' => 'latest', +]); +// /user/5?tab=orders#latest +``` + +Set the second argument to `true` to get an absolute URI: + +```php +$uri = $routeHelper->generateUri(['route_name' => 'user.view', 'route_params' => ['id' => '5']], true); +// https://example.com/user/5 +``` + +> The absolute URI uses the URI that `Mezzio\Helper\ServerUrlHelper` has. In a Mezzio application, `Mezzio\Helper\ServerUrlMiddleware` sets it. + +## Compare two URIs + +`uriEquals()` compares the scheme, the host, the port and the path. It ignores the query, the fragment and the user info. + +```php +$same = $routeHelper->uriEquals( + new Uri('https://example.com/user/5?tab=orders'), + new Uri('https://example.com/user/5') +); +// true +``` + +## Add a query parameter + +`appendQueryParam()` adds the parameter to the end of the query. The value is encoded one time, as RFC 3986 specifies. + +```php +$uri = $routeHelper->appendQueryParam(new Uri('https://example.com/search?page=2'), 'q', 'red shoes'); +// https://example.com/search?page=2&q=red%20shoes +``` + +If the query has a parameter with the same name, the method replaces the first one in its position and removes the others. The other parameters stay unchanged. + +```php +$uri = $routeHelper->appendQueryParam(new Uri('https://example.com/search?page=2&q=old'), 'page', '3'); +// https://example.com/search?page=3&q=old +``` + +In these examples, `Uri` is `Laminas\Diactoros\Uri`. Any `Psr\Http\Message\UriInterface` implementation works. diff --git a/mkdocs.yml b/mkdocs.yml index ffe4a4b..7b24ebf 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,11 +2,18 @@ docs_dir: docs/book site_dir: docs/html extra: project: Packages - current_version: v3 + current_version: v4 versions: + - v4 - v3 nav: - Home: index.md + - v4: + - Overview: v4/overview.md + - Installation: v4/installation.md + - Configuration: v4/configuration.md + - Usage: v4/usage.md + - Upgrading: v4/upgrading.md - v3: - Overview: v3/overview.md - Installation: v3/installation.md diff --git a/phpstan.neon b/phpstan.neon index 349be25..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,7 +1,7 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test diff --git a/phpunit.xml b/phpunit.xml index 98ad2a3..0b34d7e 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,14 +1,22 @@ + xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" + bootstrap="vendor/autoload.php" + cacheDirectory=".phpunit.cache" + colors="true" + failOnDeprecation="true" + failOnNotice="true" + failOnPhpunitDeprecation="true" + failOnPhpunitNotice="true" + failOnPhpunitWarning="true" + failOnRisky="true" + failOnWarning="true" + displayDetailsOnAllIssues="true"> ./test - ./src diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 3b8809d..e176d8e 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -9,6 +9,9 @@ class ConfigProvider { + /** + * @return array{dependencies: array{factories: array}} + */ public function __invoke(): array { return [ @@ -16,6 +19,9 @@ public function __invoke(): array ]; } + /** + * @return array{factories: array} + */ public function getDependencyConfig(): array { return [ diff --git a/src/Exception/ExceptionInterface.php b/src/Exception/ExceptionInterface.php new file mode 100644 index 0000000..895a450 --- /dev/null +++ b/src/Exception/ExceptionInterface.php @@ -0,0 +1,11 @@ +get(UrlHelper::class); + $urlHelper = $container->get(UrlHelper::class); + if (! $urlHelper instanceof UrlHelper) { + throw RuntimeException::invalidService(UrlHelper::class, UrlHelper::class, get_debug_type($urlHelper)); + } + $serverUrlHelper = $container->get(ServerUrlHelper::class); + if (! $serverUrlHelper instanceof ServerUrlHelper) { + throw RuntimeException::invalidService( + ServerUrlHelper::class, + ServerUrlHelper::class, + get_debug_type($serverUrlHelper) + ); + } return new RouteHelper($urlHelper, $serverUrlHelper); } diff --git a/src/Route/RouteHelper.php b/src/Route/RouteHelper.php index 1e80590..37696eb 100644 --- a/src/Route/RouteHelper.php +++ b/src/Route/RouteHelper.php @@ -9,11 +9,27 @@ use Mezzio\Helper\UrlHelper; use Psr\Http\Message\UriInterface; -use function array_merge; +use function explode; use function http_build_query; -use function parse_str; -use function urlencode; - +use function implode; +use function urldecode; + +use const PHP_QUERY_RFC3986; + +/** + * @phpstan-type RouteOptions array{ + * router?: array, + * reuse_result_params?: bool, + * reuse_query_params?: bool, + * } + * @phpstan-type RouteSpecs array{ + * route_name?: non-empty-string|null, + * route_params?: array, + * query_params?: array, + * fragment_id?: string|null, + * options?: RouteOptions, + * } + */ class RouteHelper { protected UrlHelper $urlHelper; @@ -26,6 +42,9 @@ public function __construct(UrlHelper $urlHelper, ServerUrlHelper $serverUrlHelp $this->serverUrlHelper = $serverUrlHelper; } + /** + * @param RouteSpecs $specs + */ public function generateUri(array $specs, bool $absolute = false): UriInterface { $routeName = $specs['route_name'] ?? null; @@ -42,6 +61,9 @@ public function generateUri(array $specs, bool $absolute = false): UriInterface return new Uri($uri); } + /** + * Compare scheme, host, port and path. The query, the fragment and the user info are ignored. + */ public function uriEquals(UriInterface $uri1, UriInterface $uri2): bool { return $uri1->getScheme() === $uri2->getScheme() @@ -50,20 +72,33 @@ public function uriEquals(UriInterface $uri1, UriInterface $uri2): bool && $uri1->getPort() === $uri2->getPort(); } + /** + * Add the parameter to the end of the query. If the query has parameters with the same name, + * replace the first one in its position and remove the others. Other parameters stay unchanged. + */ public function appendQueryParam(UriInterface $uri, string $name, string $value): UriInterface { - $query = $uri->getQuery(); - $arr = []; - - if (! empty($query)) { - parse_str($query, $arr); + $param = http_build_query([$name => $value], '', '&', PHP_QUERY_RFC3986); + $pairs = []; + $replaced = false; + foreach (explode('&', $uri->getQuery()) as $pair) { + if ($pair === '') { + continue; + } + if (urldecode(explode('=', $pair, 2)[0]) !== $name) { + $pairs[] = $pair; + continue; + } + if (! $replaced) { + $pairs[] = $param; + $replaced = true; + } + } + if (! $replaced) { + $pairs[] = $param; } - $query = http_build_query( - array_merge($arr, [$name => urlencode($value)]) - ); - - return $uri->withQuery($query); + return $uri->withQuery(implode('&', $pairs)); } public function getUrlHelper(): UrlHelper diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index 73f13a2..477f646 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -5,26 +5,24 @@ namespace DotTest\Helpers; use Dot\Helpers\ConfigProvider; +use Dot\Helpers\Factory\RouteHelperFactory; use Dot\Helpers\Route\RouteHelper; use PHPUnit\Framework\TestCase; class ConfigProviderTest extends TestCase { - protected array $config; - - protected function setup(): void + public function testInvokeReturnsDependencyConfig(): void { - $this->config = (new ConfigProvider())(); - } + $configProvider = new ConfigProvider(); - public function testHasDependencies(): void - { - $this->assertArrayHasKey('dependencies', $this->config); + $this->assertSame(['dependencies' => $configProvider->getDependencyConfig()], $configProvider()); } - public function testDependenciesHasFactories(): void + public function testRouteHelperUsesRouteHelperFactory(): void { - $this->assertArrayHasKey('factories', $this->config['dependencies']); - $this->assertArrayHasKey(RouteHelper::class, $this->config['dependencies']['factories']); + $this->assertSame( + ['factories' => [RouteHelper::class => RouteHelperFactory::class]], + (new ConfigProvider())->getDependencyConfig() + ); } } diff --git a/test/Factory/RouteHelperFactoryTest.php b/test/Factory/RouteHelperFactoryTest.php index dcae165..1548406 100644 --- a/test/Factory/RouteHelperFactoryTest.php +++ b/test/Factory/RouteHelperFactoryTest.php @@ -4,60 +4,60 @@ namespace DotTest\Helpers\Factory; +use Dot\Helpers\Exception\RuntimeException; use Dot\Helpers\Factory\RouteHelperFactory; -use Dot\Helpers\Route\RouteHelper; +use DotTest\Helpers\TestData\Container; +use DotTest\Helpers\TestData\Router; +use DotTest\Helpers\TestData\ServiceNotFoundException; use Mezzio\Helper\ServerUrlHelper; use Mezzio\Helper\UrlHelper; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; -use TypeError; +use stdClass; class RouteHelperFactoryTest extends TestCase { - private ContainerInterface|MockObject $containerInterface; - - /** - * @throws Exception - */ - public function setUp(): void + public function testCreatesRouteHelperWithServicesFromContainer(): void { - $this->containerInterface = $this->createMock(ContainerInterface::class); + $urlHelper = new UrlHelper(new Router([])); + $serverUrlHelper = new ServerUrlHelper(); + + $routeHelper = (new RouteHelperFactory())(new Container([ + UrlHelper::class => $urlHelper, + ServerUrlHelper::class => $serverUrlHelper, + ])); + + $this->assertSame($urlHelper, $routeHelper->getUrlHelper()); + $this->assertSame($serverUrlHelper, $routeHelper->getServerUrlHelper()); } - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotCreateWithoutParams(): void + public function testThrowsWhenUrlHelperHasWrongType(): void { - $this->containerInterface->method('get')->willReturnMap([ - [UrlHelper::class, null], - [ServerUrlHelper::class, null], - ]); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage( + 'Service "Mezzio\Helper\UrlHelper" must be an instance of "Mezzio\Helper\UrlHelper", "null" given.' + ); + + (new RouteHelperFactory())(new Container([ + UrlHelper::class => null, + ServerUrlHelper::class => new ServerUrlHelper(), + ])); + } - $this->expectException(TypeError::class); + public function testThrowsWhenServerUrlHelperHasWrongType(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('"stdClass" given.'); - (new RouteHelperFactory())($this->containerInterface); + (new RouteHelperFactory())(new Container([ + UrlHelper::class => new UrlHelper(new Router([])), + ServerUrlHelper::class => new stdClass(), + ])); } - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testWillCreateWithParams(): void + public function testContainerExceptionIsNotCaught(): void { - $this->containerInterface->method('get')->willReturnMap([ - [UrlHelper::class, $this->createMock(UrlHelper::class)], - [ServerUrlHelper::class, $this->createMock(ServerUrlHelper::class)], - ]); - - $routeHelper = (new RouteHelperFactory())($this->containerInterface); + $this->expectException(ServiceNotFoundException::class); - $this->assertSame(RouteHelper::class, $routeHelper::class); + (new RouteHelperFactory())(new Container()); } } diff --git a/test/Route/RouteHelperTest.php b/test/Route/RouteHelperTest.php index 12e06b5..d700404 100644 --- a/test/Route/RouteHelperTest.php +++ b/test/Route/RouteHelperTest.php @@ -5,73 +5,110 @@ namespace DotTest\Helpers\Route; use Dot\Helpers\Route\RouteHelper; +use DotTest\Helpers\TestData\Router; use Laminas\Diactoros\Uri; use Mezzio\Helper\ServerUrlHelper; use Mezzio\Helper\UrlHelper; -use PHPUnit\Framework\MockObject\Exception; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Psr\Http\Message\UriInterface; + +use function parse_str; class RouteHelperTest extends TestCase { private RouteHelper $routeHelper; - /** - * @throws Exception - */ - protected function setup(): void + protected function setUp(): void { + $serverUrlHelper = new ServerUrlHelper(); + $serverUrlHelper->setUri(new Uri('https://example.com:8443/base')); + $this->routeHelper = new RouteHelper( - $this->createMock(UrlHelper::class), - $this->createMock(ServerUrlHelper::class) + new UrlHelper(new Router(['user' => '/user/{id}'])), + $serverUrlHelper ); } - public function testGenerateUri(): void + public function testGenerateUriReturnsRelativeUri(): void + { + $uri = $this->routeHelper->generateUri([ + 'route_name' => 'user', + 'route_params' => ['id' => '5'], + 'query_params' => ['a' => 'b c'], + 'fragment_id' => 'top', + ]); + + $this->assertSame('/user/5?a=b+c#top', (string) $uri); + } + + public function testGenerateUriReturnsAbsoluteUri(): void { - $specs['route_name'] = 'testDotHelpers'; - $specs['route_params'] = ['test']; - $specs['query_params'] = ['test']; - $specs['fragment_id'] = 'test'; - $specs['options'] = ['test']; - - $generateUri = $this->routeHelper->generateUri($specs); - $this->assertContainsOnlyInstancesOf(UriInterface::class, [$generateUri]); - $generateUri = $this->routeHelper->generateUri($specs, true); - $this->assertContainsOnlyInstancesOf(UriInterface::class, [$generateUri]); + $uri = $this->routeHelper->generateUri(['route_name' => 'user', 'route_params' => ['id' => '5']], true); + + $this->assertSame('https://example.com:8443/user/5', (string) $uri); } /** - * @throws Exception + * @return iterable */ - public function testUriEquals(): void + public static function uriEqualsProvider(): iterable { - $uri1 = $this->createMock(UriInterface::class); - $uri2 = $this->createMock(UriInterface::class); + yield 'same uri' => ['https://e.com/p', 'https://e.com/p', true]; + yield 'query is ignored' => ['https://e.com/p?a=1', 'https://e.com/p?a=2', true]; + yield 'fragment is ignored' => ['https://e.com/p#a', 'https://e.com/p#b', true]; + yield 'default port' => ['https://e.com:443/p', 'https://e.com/p', true]; + yield 'other scheme' => ['http://e.com/p', 'https://e.com/p', false]; + yield 'other host' => ['https://a.com/p', 'https://e.com/p', false]; + yield 'other port' => ['https://e.com:8443/p', 'https://e.com/p', false]; + yield 'other path' => ['https://e.com/a', 'https://e.com/p', false]; + yield 'trailing slash' => ['https://e.com/p/', 'https://e.com/p', false]; + } - $uri1->method('getScheme')->willReturn('test'); - $uri2->method('getScheme')->willReturn('test'); + #[DataProvider('uriEqualsProvider')] + public function testUriEquals(string $uri1, string $uri2, bool $expected): void + { + $this->assertSame($expected, $this->routeHelper->uriEquals(new Uri($uri1), new Uri($uri2))); + } - $uri1->method('getHost')->willReturn('test'); - $uri2->method('getHost')->willReturn('test'); + /** + * @return iterable + */ + public static function appendQueryParamProvider(): iterable + { + yield 'empty query' => ['/p', 'test', 'testing', 'test=testing']; + yield 'space is encoded once' => ['/p', 'q', 'a b', 'q=a%20b']; + yield 'reserved characters' => ['/p', 'q', 'x&y=z', 'q=x%26y%3Dz']; + yield 'utf-8' => ['/p', 'q', 'รค', 'q=%C3%A4']; + yield 'dots in keys are kept' => ['/p?a.b=1&c%20d=2', 'q', 'v', 'a.b=1&c%20d=2&q=v']; + yield 'query "0" is kept' => ['/p?0', 'q', 'v', '0&q=v']; + yield 'same name is replaced' => ['/p?q=old&r=1', 'q', 'new', 'q=new&r=1']; + yield 'form-encoded name' => ['/p?my+key=old&q=1', 'my key', 'new', 'my%20key=new&q=1']; + yield 'duplicates removed' => ['/p?q=1&r=2&q=3', 'q', 'v', 'q=v&r=2']; + } - $uri1->method('getPath')->willReturn('test'); - $uri2->method('getPath')->willReturn('test'); + #[DataProvider('appendQueryParamProvider')] + public function testAppendQueryParam(string $uri, string $name, string $value, string $expected): void + { + $this->assertSame($expected, $this->routeHelper->appendQueryParam(new Uri($uri), $name, $value)->getQuery()); + } - $uri1->method('getPort')->willReturn(1); - $uri2->method('getPort')->willReturn(1); + public function testAppendQueryParamValueDecodesToOriginal(): void + { + $query = $this->routeHelper->appendQueryParam(new Uri('/p'), 'q', 'a b&c')->getQuery(); + parse_str($query, $params); - $generateUri = $this->routeHelper->uriEquals($uri1, $uri2); - $this->assertTrue($generateUri); + $this->assertSame(['q' => 'a b&c'], $params); } - public function testAppendQueryParam(): void + public function testSettersReplaceHelpers(): void { - $uri = new Uri(); - $newUri = $this->routeHelper->appendQueryParam($uri, 'test', 'testing'); - $query = $newUri->getQuery(); + $urlHelper = new UrlHelper(new Router([])); + $serverUrlHelper = new ServerUrlHelper(); + + $this->routeHelper->setUrlHelper($urlHelper); + $this->routeHelper->setServerUrlHelper($serverUrlHelper); - $this->assertContainsOnlyInstancesOf(UriInterface::class, [$newUri]); - $this->assertEquals('test=testing', $query); + $this->assertSame($urlHelper, $this->routeHelper->getUrlHelper()); + $this->assertSame($serverUrlHelper, $this->routeHelper->getServerUrlHelper()); } } diff --git a/test/TestData/Container.php b/test/TestData/Container.php new file mode 100644 index 0000000..f731386 --- /dev/null +++ b/test/TestData/Container.php @@ -0,0 +1,33 @@ + $services + */ + public function __construct(private array $services = []) + { + } + + public function get(string $id): mixed + { + if (! array_key_exists($id, $this->services)) { + throw new ServiceNotFoundException($id); + } + + return $this->services[$id]; + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services); + } +} diff --git a/test/TestData/Router.php b/test/TestData/Router.php new file mode 100644 index 0000000..8d8eca6 --- /dev/null +++ b/test/TestData/Router.php @@ -0,0 +1,48 @@ + $patterns + */ + public function __construct(private array $patterns) + { + } + + public function addRoute(Route $route): void + { + } + + public function match(ServerRequestInterface $request): RouteResult + { + return RouteResult::fromRouteFailure(null); + } + + /** + * @param array $substitutions + * @param array $options + */ + public function generateUri(string $name, array $substitutions = [], array $options = []): string + { + $replace = []; + foreach ($substitutions as $key => $value) { + $replace['{' . $key . '}'] = (string) $value; + } + + return strtr($this->patterns[$name], $replace); + } +} diff --git a/test/TestData/ServiceNotFoundException.php b/test/TestData/ServiceNotFoundException.php new file mode 100644 index 0000000..86d38db --- /dev/null +++ b/test/TestData/ServiceNotFoundException.php @@ -0,0 +1,18 @@ +