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..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 948af93..bf3f030 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ composer.phar .phpcs-cache .idea composer.lock +.phpunit.cache .phpunit.result.cache 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 d3870ad..d09f5df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,34 +1,334 @@ -## 3.0.0 - 2021-05-14 +# Changelog + +## 4.0.0 - TBD + +### Changed + +- PHP requirement is now `~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0` +- `mezzio/mezzio-router` requirement is now `^3.16 || ^4.0` +- The header configuration is validated when the middleware is created; a wrong type throws `Dot\ResponseHeader\Exception\InvalidConfigException` naming the key +- `overwrite` must be a `bool`; `value` must be a string, a number or a non-empty list of strings +- `ResponseHeaderMiddlewareFactory` throws `InvalidConfigException` instead of `Exception` (the messages are unchanged) +- `ConfigProvider` and `ResponseHeaderMiddlewareFactory` are now `final` +- PHPUnit `^12.5`, PHPStan level 8, PHPUnit fails on deprecations, notices, warnings and risky tests +- Tests use real PSR-7 objects and fixtures instead of mocks +- CI: GitHub Actions bumped to `actions/checkout@v7`, `actions/cache@v6`, `codecov/codecov-action@v7`; coverage runs on PHP 8.5 only + +### Added + +- Support for PHP 8.6 +- Support for `mezzio/mezzio-router` 4 +- `Dot\ResponseHeader\Exception\InvalidConfigException` +- Explicit `psr/container`, `psr/http-server-handler` and `psr/http-server-middleware` requirements +- `v4` documentation and the "Upgrading to 4.x" guide + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 8.2 +- `psr/http-client` requirement (it was never used) + +### Fixed + +- An empty `dot_response_headers` array no longer throws in the factory +- A `config` service that is not an array no longer throws a `TypeError` +- Invalid header entries no longer raise PHP warnings or errors on every request + +## 3.6.0 - 2025-10-30 + +### Changed + +- Nothing + +### Added + +- Support for PHP 8.4 and 8.5 + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 8.1 + +### Fixed + +- Nothing + +## 3.5.0 - 2025-03-12 ### Changed -* Nothing + +- Replaced Psalm with PHPStan ### Added -* Everything + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- `vimeo/psalm` ### Fixed -* Nothing -## 3.0.1 - 2021-01-18 +- Nothing + +## 3.4.1 - 2025-01-28 ### Changed -* README.md -* src/Middleware/ResponseHeaderMiddleware.php + +- Bumped `vimeo/psalm` to `^6.0` +- "DotKernel" spelled "Dotkernel" in `composer.json` ### Added -* CHANGELOG.md + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing + +## 3.4.0 - 2024-10-22 + +### Changed + +- Bumped `laminas/laminas-coding-standard` to `^3.0` + +### Added + +- Support for PHP 8.4 + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.3.1 - 2024-05-27 + +### Changed + +- `psr/http-message` requirement back to `^1.0 || ^2.0` + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.3.0 - 2024-05-03 + +### Changed + +- `psr/http-message` requirement is now `^2.0` + +### Added + +- Documentation for v3 +- Unsupported versions in `SECURITY.md` + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- `mkdocs.yml` navigation and README examples + +## 3.2.3 - 2023-11-30 + +### Changed + +- Nothing + +### Added + +- Support for PHP 8.3 + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.2.2 - 2023-08-22 + +### Changed + +- README badges + +### Added + +- Codecov workflow and badge + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.2.1 - 2023-08-16 + +### Changed + +- `psr/http-message` requirement is now `^1.0 || ^2.0` +- `laminas/laminas-diactoros` dev requirement is now `^3.1` + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.2.0 - 2023-07-28 + +### Changed + +- PHP requirement is now `~8.1.0 || ~8.2.0` +- Directory structure and namespaces +- PHPUnit `^10.2` + +### Added + +- Support for PHP 8.2 +- Explicit `mezzio/mezzio-router`, `psr/http-client` and `psr/http-message` requirements +- Unit tests, `laminas/laminas-coding-standard` and Psalm static analysis +- `composer check` script + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 7.4 and 8.0 + +### Fixed + +- Nothing + +## 3.1.0 - 2022-04-06 + +### Changed + +- PHP requirement is now `~7.4.0 || ~8.0.0 || ~8.1.0` +- PHPUnit `^9.5.20` + +### Added + +- Support for PHP 8.0 and 8.1 + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.0.1 - 2021-05-18 + +### Changed + +- README.md +- src/Middleware/ResponseHeaderMiddleware.php + +### Added + +- CHANGELOG.md + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 3.0.0 - 2021-05-14 + +### Changed + +- Nothing + +### Added + +- Everything + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing diff --git a/README.md b/README.md index f70b795..a22f07e 100644 --- a/README.md +++ b/README.md @@ -6,23 +6,33 @@ Documentation is available at: https://docs.dotkernel.org/dot-response-header/. +## Versions + +| Version | Supported | PHP | +| --- | --- | --- | +| 4.x | :white_check_mark: | 8.3 to 8.6 | +| 3.x | Security fixes only | 8.2 to 8.5 | +| <= 2.x | :x: | | + +Upgrading from 3.x? See [Upgrading to 4.x](https://docs.dotkernel.org/dot-response-header/v4/upgrading/). + ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-response-header) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/3.6.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/4.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/blob/3.0/LICENSE) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/blob/4.0/LICENSE) -[![Build Static](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-response-header/graph/badge.svg?token=NNRZN0FBF2)](https://codecov.io/gh/dotkernel/dot-response-header) -[![PHPStan](https://github.com/dotkernel/dot-response-header/actions/workflows/static-analysis.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-response-header/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-response-header/actions/workflows/static-analysis.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-response-header/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 ## Installation @@ -72,7 +82,7 @@ return [ 'login' => [ 'LoginHeader' => [ 'value' => 'LoginHeader-Value', - 'overwrite' => false + 'overwrite' => false, ], ], ], @@ -83,7 +93,7 @@ Because headers are matched with route names, we can have custom response header All headers under `*` will be set for every response. -To add response headers for a specific set of routes, define a new array using the route name as the array key. +To add response headers for a specific route, define a new array using the exact route name as the array key. Example: @@ -93,11 +103,13 @@ Example: 'UserCustomHeader' => [ 'value' => 'UserCustomHeader-Value', 'overwrite' => false, - ] + ], ], -] +], -// This will set a new header named UserCustomHeader with the UserCustomHeader-Value value for any route name matching 'user' +// This will set a new header named UserCustomHeader with the UserCustomHeader-Value value for the route named 'user' ``` -To overwrite an existing header use `overwrite => true`. +To overwrite an existing header use `overwrite => true`. The `*` headers are applied before the route headers, so a route header replaces a `*` header with the same name only when it sets `overwrite => true`. + +An invalid configuration throws `Dot\ResponseHeader\Exception\InvalidConfigException` when the middleware is created, with a message naming the key. diff --git a/SECURITY.md b/SECURITY.md index 197e900..96b6390 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,10 +2,11 @@ ## Supported Versions -| Version | Supported | PHP Version | -|---------|--------------------|---------------------------------------------------------------------------------------------------------------------| -| 3.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/3.6.0) | -| <= 2.x | :x: | | +| Version | Supported | PHP Version | +|---------|---------------------|---------------------------------------------------------------------------------------------------------------------| +| 4.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/4.0.0) | +| 3.x | Security fixes only | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/3.6.0) | +| <= 2.x | :x: | | ## Reporting Potential Security Issues @@ -20,12 +21,11 @@ When reporting issues, please provide the following information: - A summary of the security vulnerability and impact We request that you contact us via the email address above and give the -project contributors a chance to resolve the vulnerability and issue a newc +project contributors a chance to resolve the vulnerability and issue a new 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 0ad6170..b35f7b2 100644 --- a/composer.json +++ b/composer.json @@ -19,17 +19,19 @@ "mezzio" ], "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", - "mezzio/mezzio-router": "^3.16", - "psr/http-client": "^1.0", - "psr/http-message": "^1.0 || ^2.0" + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", + "mezzio/mezzio-router": "^3.16 || ^4.0", + "psr/container": "^1.1 || ^2.0", + "psr/http-message": "^1.0 || ^2.0", + "psr/http-server-handler": "^1.0", + "psr/http-server-middleware": "^1.0" }, "require-dev": { "laminas/laminas-coding-standard": "^3.0", - "laminas/laminas-diactoros": "^3.1", + "laminas/laminas-diactoros": "^3.10", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.2" + "phpunit/phpunit": "^12.5" }, "autoload": { "psr-4": { diff --git a/docs/book/v4/configuration.md b/docs/book/v4/configuration.md new file mode 100644 index 0000000..7881160 --- /dev/null +++ b/docs/book/v4/configuration.md @@ -0,0 +1,79 @@ +# Configuration + +## Requirements + +- **PHP**: 8.3, 8.4, 8.5 or 8.6 +- **mezzio/mezzio-router**: 3.x or 4.x (PHP 8.6 needs 4.3 or newer) + +## Register ConfigProvider + +Next, register the package's `ConfigProvider` to your application config. + +```php +Dot\ResponseHeader\ConfigProvider::class, +``` + +> Make sure to register the package under the `// DK packages` section. + +## Add the package to the middleware stack + +After registering the package, add it to the middleware stack in `config/pipeline.php` after `$app->pipe(RouteMiddleware::class);` + +```php +$app->pipe(RouteMiddleware::class); +$app->pipe(\Dot\ResponseHeader\Middleware\ResponseHeaderMiddleware::class); +``` + +> If the middleware is piped before `RouteMiddleware`, no route is known yet and only the `*` headers are added. + +## Add configuration in autoload + +Create a new file `response-header.global.php` in `config/autoload` with the below configuration array: + +```php + [ + '*' => [ + 'CustomHeader1' => [ + 'value' => 'CustomHeader1-Value', + 'overwrite' => true, + ], + 'CustomHeader2' => [ + 'value' => 'CustomHeader2-Value', + 'overwrite' => false, + ], + ], + 'home' => [ + 'CustomHeader' => [ + 'value' => 'header3', + ], + ], + 'login' => [ + 'LoginHeader' => [ + 'value' => 'LoginHeader-Value', + 'overwrite' => false, + ], + ], + ], +]; +``` + +## Configuration keys + +| Key | Type | Default | Meaning | +| --- | --- | --- | --- | +| `dot_response_headers` | array | required | Route name (or `*`) to headers. An empty array is allowed and adds no headers | +| `.
.value` | string, int, float or a non-empty list of strings | none | Header value. Numbers are sent as strings; a list sends one header with several values. An entry without `value` is skipped | +| `.
.overwrite` | bool | `false` | Replace the header if the response already has it | + +## Invalid configuration + +The configuration is checked once, when the container creates the middleware. A wrong type throws `Dot\ResponseHeader\Exception\InvalidConfigException` with a message naming the key, for example: + +```text +dot_response_headers.*.X-Frame-Options.overwrite must be a bool, int given. +``` + +A missing `config` service or a missing `dot_response_headers` key also throws `InvalidConfigException`. diff --git a/docs/book/v4/installation.md b/docs/book/v4/installation.md new file mode 100644 index 0000000..0d6bf2c --- /dev/null +++ b/docs/book/v4/installation.md @@ -0,0 +1,9 @@ +# Installation + +Install dotkernel/dot-response-header by executing the following Composer command in your project directory: + +```shell +composer require dotkernel/dot-response-header:^4.0 +``` + +Upgrading from 3.x? Read [Upgrading to 4.x](upgrading.md) first. diff --git a/docs/book/v4/overview.md b/docs/book/v4/overview.md new file mode 100644 index 0000000..a839362 --- /dev/null +++ b/docs/book/v4/overview.md @@ -0,0 +1,19 @@ +# Overview + +`dot-response-header` is Dotkernel's middleware for setting and overwriting custom response headers. + +Headers are configured per route name, plus a `*` group that applies to every response. + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-response-header) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-response-header/4.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-response-header)](https://github.com/dotkernel/dot-response-header/blob/4.0/LICENSE) + +[![Build Static](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-response-header/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-response-header/graph/badge.svg?token=NNRZN0FBF2)](https://codecov.io/gh/dotkernel/dot-response-header) +[![PHPStan](https://github.com/dotkernel/dot-response-header/actions/workflows/static-analysis.yml/badge.svg?branch=4.0)](https://github.com/dotkernel/dot-response-header/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..b423a37 --- /dev/null +++ b/docs/book/v4/upgrading.md @@ -0,0 +1,28 @@ +# Upgrading to 4.x + +`dot-response-header` 4.x keeps the 3.x configuration format. A valid 3.x configuration sends the same headers in 4.x. Most applications only need to bump the version constraint. + +```shell +composer require dotkernel/dot-response-header:^4.0 +``` + +## Changes that can break your code + +| Change | Symptom | Fix | +| --- | --- | --- | +| PHP 8.2 support dropped | Composer refuses to install | Upgrade to PHP 8.3 or newer | +| `overwrite` must be a `bool` | `InvalidConfigException: dot_response_headers..
.overwrite must be a bool, int given.` | Use `true` or `false`. In 3.x, `1` or `'true'` were silently treated as `false` | +| Route and header entries must be arrays | `InvalidConfigException` naming the key | In 3.x a string route entry was ignored with a PHP warning, and a string header entry threw a `TypeError` on every request | +| `value` must be a string, a number or a non-empty list of strings | `InvalidConfigException` naming the key | In 3.x `null` threw from the PSR-7 implementation on every request | +| The factory throws `Dot\ResponseHeader\Exception\InvalidConfigException` instead of `Exception` | Code that catches `Exception` still works; code that compares the exact class does not | Catch `InvalidArgumentException` or `InvalidConfigException` | +| `ConfigProvider` and `ResponseHeaderMiddlewareFactory` are `final` | `Class ... cannot extend final class` | Decorate them or write your own factory. `ResponseHeaderMiddleware` is not `final` | + +## Changes in behaviour + +| Change | Effect | What to do | +| --- | --- | --- | +| Configuration is checked when the middleware is created | Errors appear once, with the key in the message, instead of on each request | Nothing | +| `'dot_response_headers' => []` is allowed | In 3.x it threw `Unable to find dot-response-header config.`; now no headers are added | Nothing | +| A `config` service that implements `ArrayAccess` is accepted | In 3.x it threw a `TypeError` | Nothing | +| Numeric values are sent as strings | `3600` becomes `"3600"`, as before with Laminas Diactoros | Nothing | +| `mezzio/mezzio-router` 4.x is allowed | PHP 8.6 installs router 4.3 or newer | Nothing | diff --git a/docs/book/v4/usage.md b/docs/book/v4/usage.md new file mode 100644 index 0000000..73e7df4 --- /dev/null +++ b/docs/book/v4/usage.md @@ -0,0 +1,69 @@ +# Usage + +Because headers are matched with route names, we can have custom response headers for every request, by defining new headers under the `*` key, in the configuration file `response-header.global.php`. + +All headers under `*` will be set for every response, including 404 and 405 responses. + +To add response headers for a specific route, define a new array using the route name as the array key. The key must be the exact route name; it is not a pattern. + +## Example + +```php +'dot_response_headers' => [ + 'user' => [ + 'UserCustomHeader' => [ + 'value' => 'UserCustomHeader-Value', + 'overwrite' => false, + ], + ], +], + +// This will set a new header named UserCustomHeader with the UserCustomHeader-Value value for the route named 'user' +``` + +## Overwriting headers + +Headers are applied in this order: + +1. The response returned by the handler. +2. The `*` headers. +3. The headers of the matched route. + +A header that already exists is only replaced when its entry has `'overwrite' => true`. This also applies between steps 2 and 3: a route header replaces a `*` header with the same name only when it sets `'overwrite' => true`. + +```php +'dot_response_headers' => [ + '*' => [ + 'Cache-Control' => [ + 'value' => 'no-store', + ], + ], + 'image' => [ + 'Cache-Control' => [ + 'value' => 'public, max-age=86400', + 'overwrite' => true, + ], + ], +], + +// The 'image' route gets "Cache-Control: public, max-age=86400", every other route gets "Cache-Control: no-store" +``` + +Header names are case-insensitive, so `x-custom` set by a handler counts as an existing `X-Custom` header. + +## Header values + +A value can be a string, a number or a list of strings: + +```php +'dot_response_headers' => [ + '*' => [ + 'Access-Control-Max-Age' => [ + 'value' => 3600, + ], + 'Vary' => [ + 'value' => ['Accept', 'Origin'], + ], + ], +], +``` diff --git a/mkdocs.yml b/mkdocs.yml index 346f66c..485fe96 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 cf5ba32..85a997a 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,14 +1,28 @@ - + - - ./test + + test - - + - ./src + src diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index aa45e00..f36a711 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -7,8 +7,11 @@ use Dot\ResponseHeader\Factory\ResponseHeaderMiddlewareFactory; use Dot\ResponseHeader\Middleware\ResponseHeaderMiddleware; -class ConfigProvider +final 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 getDependencies(): array { return [ diff --git a/src/Exception/InvalidConfigException.php b/src/Exception/InvalidConfigException.php new file mode 100644 index 0000000..f0cbfdd --- /dev/null +++ b/src/Exception/InvalidConfigException.php @@ -0,0 +1,52 @@ +has('config')) { - throw new Exception(self::MESSAGE_MISSING_CONFIG); + throw new InvalidConfigException(self::MESSAGE_MISSING_CONFIG); } + $config = $container->get('config'); + if (! is_array($config) && ! $config instanceof ArrayAccess) { + throw new InvalidConfigException(self::MESSAGE_MISSING_CONFIG); + } - if ( - ! array_key_exists('dot_response_headers', $config) - || ! is_array($config['dot_response_headers']) - || empty($config['dot_response_headers']) - ) { - throw new Exception(self::MESSAGE_MISSING_PACKAGE_CONFIG); + $headers = $config['dot_response_headers'] ?? null; + if (! is_array($headers)) { + throw new InvalidConfigException(self::MESSAGE_MISSING_PACKAGE_CONFIG); } - return new ResponseHeaderMiddleware($container->get('config')['dot_response_headers'] ?? []); + return new ResponseHeaderMiddleware($headers); } } diff --git a/src/Middleware/ResponseHeaderMiddleware.php b/src/Middleware/ResponseHeaderMiddleware.php index 3f3d6ca..687e6b0 100644 --- a/src/Middleware/ResponseHeaderMiddleware.php +++ b/src/Middleware/ResponseHeaderMiddleware.php @@ -4,56 +4,132 @@ namespace Dot\ResponseHeader\Middleware; +use Dot\ResponseHeader\Exception\InvalidConfigException; use Mezzio\Router\RouteResult; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; +use function array_is_list; use function array_key_exists; +use function is_array; +use function is_bool; +use function is_float; +use function is_int; +use function is_string; +/** + * @phpstan-type HeaderConfig array{value: string|non-empty-list, overwrite: bool} + * @phpstan-type ResponseHeadersConfig array> + */ class ResponseHeaderMiddleware implements MiddlewareInterface { private const ALL_ROUTES = '*'; - private array $config; + /** @var ResponseHeadersConfig */ + private readonly array $config; + /** + * @param array $config + * @throws InvalidConfigException + */ public function __construct(array $config) { - $this->config = $config; + $this->config = self::normalize($config); } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $response = $handler->handle($request); - if (empty($this->config)) { + if ($this->config === []) { return $response; } $response = $this->addHeaders($response, self::ALL_ROUTES); $routeResult = $request->getAttribute(RouteResult::class); - if ($routeResult instanceof RouteResult && $routeResult->isSuccess()) { - $response = $this->addHeaders($response, $routeResult->getMatchedRouteName()); + if (! $routeResult instanceof RouteResult) { + return $response; } - return $response; + + $routeName = $routeResult->getMatchedRouteName(); + if ($routeName === false) { + return $response; + } + + return $this->addHeaders($response, $routeName); } public function addHeaders(ResponseInterface $response, string $route): ResponseInterface { - if (array_key_exists($route, $this->config)) { - foreach ($this->config[$route] as $header => $data) { + foreach ($this->config[$route] ?? [] as $header => $data) { + if ($response->hasHeader($header) && ! $data['overwrite']) { + continue; + } + $response = $response->withHeader($header, $data['value']); + } + + return $response; + } + + /** + * @param array $config + * @return ResponseHeadersConfig + * @throws InvalidConfigException + */ + private function normalize(array $config): array + { + $normalized = []; + foreach ($config as $route => $headers) { + if (! is_array($headers)) { + throw InvalidConfigException::routeNotArray($route, $headers); + } + foreach ($headers as $header => $data) { + if (! is_array($data)) { + throw InvalidConfigException::headerNotArray($route, $header, $data); + } if (! array_key_exists('value', $data)) { continue; } - $addHeader = true; - if ($response->hasHeader($header)) { - $addHeader = isset($data['overwrite']) && $data['overwrite'] === true; - } - if ($addHeader === true) { - $response = $response->withHeader($header, $data['value']); + $overwrite = $data['overwrite'] ?? false; + if (! is_bool($overwrite)) { + throw InvalidConfigException::invalidOverwrite($route, $header, $overwrite); } + + $normalized[(string) $route][(string) $header] = [ + 'value' => self::normalizeValue($route, $header, $data['value']), + 'overwrite' => $overwrite, + ]; } } - return $response; + + return $normalized; + } + + /** + * @return string|non-empty-list + * @throws InvalidConfigException + */ + private function normalizeValue(int|string $route, int|string $header, mixed $value): string|array + { + if (is_string($value)) { + return $value; + } + if (is_int($value) || is_float($value)) { + return (string) $value; + } + if (! is_array($value) || $value === [] || ! array_is_list($value)) { + throw InvalidConfigException::invalidValue($route, $header, $value); + } + + $values = []; + foreach ($value as $item) { + if (! is_string($item)) { + throw InvalidConfigException::invalidValue($route, $header, $value); + } + $values[] = $item; + } + + return $values; } } diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index c0d57d4..480385d 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -5,28 +5,26 @@ namespace DotTest\ResponseHeader; use Dot\ResponseHeader\ConfigProvider; +use Dot\ResponseHeader\Factory\ResponseHeaderMiddlewareFactory; +use Dot\ResponseHeader\Middleware\ResponseHeaderMiddleware; use PHPUnit\Framework\TestCase; -class ConfigProviderTest extends TestCase +final class ConfigProviderTest extends TestCase { - private ConfigProvider $configProvider; - - public function setUp(): void - { - $this->configProvider = new ConfigProvider(); - } - - public function testInvoke(): void + public function testInvokeReturnsDependencies(): void { - $data = $this->configProvider->__invoke(); + $config = (new ConfigProvider())(); - $this->assertIsArray($data); + $this->assertSame(['dependencies' => (new ConfigProvider())->getDependencies()], $config); } - public function testGetDependencies(): void + public function testMiddlewareIsRegisteredWithItsFactory(): void { - $data = $this->configProvider->getDependencies(); + $dependencies = (new ConfigProvider())->getDependencies(); - $this->assertIsArray($data); + $this->assertSame( + [ResponseHeaderMiddleware::class => ResponseHeaderMiddlewareFactory::class], + $dependencies['factories'] + ); } } diff --git a/test/Factory/ResponseHeaderMiddlewareFactoryTest.php b/test/Factory/ResponseHeaderMiddlewareFactoryTest.php index 7995468..3a7c9be 100644 --- a/test/Factory/ResponseHeaderMiddlewareFactoryTest.php +++ b/test/Factory/ResponseHeaderMiddlewareFactoryTest.php @@ -4,57 +4,83 @@ namespace DotTest\ResponseHeader\Factory; +use ArrayObject; +use Dot\ResponseHeader\Exception\InvalidConfigException; use Dot\ResponseHeader\Factory\ResponseHeaderMiddlewareFactory; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\ResponseHeader\Fixture\ArrayContainer; +use DotTest\ResponseHeader\Fixture\FixedResponseHandler; +use Laminas\Diactoros\ServerRequest; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; -class ResponseHeaderMiddlewareFactoryTest extends TestCase +final class ResponseHeaderMiddlewareFactoryTest extends TestCase { - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundExceptionInterface - */ - public function testWillNotCreateApplicationWithoutConfig(): void + public function testThrowsWhenConfigServiceIsMissing(): void { - $container = $this->createMock(ContainerInterface::class); + $this->expectException(InvalidConfigException::class); + $this->expectExceptionMessage(ResponseHeaderMiddlewareFactory::MESSAGE_MISSING_CONFIG); - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(false); + (new ResponseHeaderMiddlewareFactory())(new ArrayContainer()); + } - $this->expectException(\Exception::class); + public function testThrowsWhenConfigServiceIsNotAnArray(): void + { + $this->expectException(InvalidConfigException::class); $this->expectExceptionMessage(ResponseHeaderMiddlewareFactory::MESSAGE_MISSING_CONFIG); - (new ResponseHeaderMiddlewareFactory())($container); + + (new ResponseHeaderMiddlewareFactory())(new ArrayContainer(['config' => null])); } /** - * @throws Exception - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface + * @return iterable}> */ - public function testWillNotCreateApplicationWithoutPackageConfig(): void + public static function missingPackageConfigProvider(): iterable { - $container = $this->createMock(ContainerInterface::class); + yield 'key missing' => [['other' => []]]; + yield 'key is a string' => [['dot_response_headers' => 'X-Header']]; + yield 'key is null' => [['dot_response_headers' => null]]; + } - $container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); + /** + * @param array $config + */ + #[DataProvider('missingPackageConfigProvider')] + public function testThrowsWhenPackageConfigIsMissing(array $config): void + { + $this->expectException(InvalidConfigException::class); + $this->expectExceptionMessage(ResponseHeaderMiddlewareFactory::MESSAGE_MISSING_PACKAGE_CONFIG); - $container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn([ - 'test', - ]); + (new ResponseHeaderMiddlewareFactory())(new ArrayContainer(['config' => $config])); + } - $this->expectException(\Exception::class); - $this->expectExceptionMessage(ResponseHeaderMiddlewareFactory::MESSAGE_MISSING_PACKAGE_CONFIG); - (new ResponseHeaderMiddlewareFactory())($container); + public function testEmptyPackageConfigCreatesMiddlewareThatAddsNothing(): void + { + $middleware = (new ResponseHeaderMiddlewareFactory())( + new ArrayContainer(['config' => ['dot_response_headers' => []]]) + ); + + $response = $middleware->process(new ServerRequest(), new FixedResponseHandler()); + + $this->assertSame([], $response->getHeaders()); + } + + public function testAcceptsArrayAccessConfig(): void + { + $config = new ArrayObject(['dot_response_headers' => ['*' => ['X-All' => ['value' => 'all']]]]); + $middleware = (new ResponseHeaderMiddlewareFactory())(new ArrayContainer(['config' => $config])); + + $response = $middleware->process(new ServerRequest(), new FixedResponseHandler()); + + $this->assertSame('all', $response->getHeaderLine('X-All')); + } + + public function testInvalidPackageConfigFailsWhenTheMiddlewareIsCreated(): void + { + $this->expectException(InvalidConfigException::class); + $this->expectExceptionMessage('dot_response_headers.* must be an array of headers, string given.'); + + (new ResponseHeaderMiddlewareFactory())( + new ArrayContainer(['config' => ['dot_response_headers' => ['*' => 'X-All']]]) + ); } } diff --git a/test/Fixture/ArrayContainer.php b/test/Fixture/ArrayContainer.php new file mode 100644 index 0000000..bfa608c --- /dev/null +++ b/test/Fixture/ArrayContainer.php @@ -0,0 +1,37 @@ + $services + */ + public function __construct( + private array $services = [], + ) { + } + + public function get(string $id): mixed + { + if (! $this->has($id)) { + throw new ServiceNotFoundException('Service not found: ' . $id); + } + + return $this->services[$id]; + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services); + } +} diff --git a/test/Fixture/FixedResponseHandler.php b/test/Fixture/FixedResponseHandler.php new file mode 100644 index 0000000..0241a24 --- /dev/null +++ b/test/Fixture/FixedResponseHandler.php @@ -0,0 +1,35 @@ + $headers + */ + public function __construct(array $headers = []) + { + $response = new Response(); + foreach ($headers as $name => $value) { + $response = $response->withHeader($name, $value); + } + $this->response = $response; + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + return $this->response; + } +} diff --git a/test/Fixture/ServiceNotFoundException.php b/test/Fixture/ServiceNotFoundException.php new file mode 100644 index 0000000..d00bc33 --- /dev/null +++ b/test/Fixture/ServiceNotFoundException.php @@ -0,0 +1,12 @@ + [ + 'X-All' => ['value' => 'all', 'overwrite' => false], + 'X-Overwrite' => ['value' => 'all', 'overwrite' => true], + ], + 'home' => [ + 'X-Home' => ['value' => 'home'], + 'X-All' => ['value' => 'home', 'overwrite' => true], + 'X-Overwrite' => ['value' => 'home', 'overwrite' => false], + ], + ]; + + public function testEmptyConfigReturnsTheHandlerResponseUnchanged(): void { - $this->responseHeader = new ResponseHeaderMiddleware([]); - $this->serverRequest = $this->createMock(ServerRequestInterface::class); - $this->requestHandler = $this->createMock(RequestHandlerInterface::class); + $handler = new FixedResponseHandler(['X-Existing' => 'kept']); + $response = (new ResponseHeaderMiddleware([]))->process(new ServerRequest(), $handler); + + $this->assertSame($handler->handle(new ServerRequest()), $response); } - public function testProcess(): void + public function testWithoutRouteResultOnlyCommonHeadersAreAdded(): void { - $data = $this->responseHeader->process($this->serverRequest, $this->requestHandler); + $response = (new ResponseHeaderMiddleware(self::CONFIG)) + ->process(new ServerRequest(), new FixedResponseHandler()); - $this->assertContainsOnlyInstancesOf(ResponseInterface::class, [$data]); + $this->assertSame(['X-All' => ['all'], 'X-Overwrite' => ['all']], $response->getHeaders()); } - public function testWillNotAddHeadersWithoutCommonWithoutRouteSpecificHeadersConfigured(): void + public function testRouteFailureOnlyAddsCommonHeaders(): void { - $responseHeader = new ResponseHeaderMiddleware([]); + $request = (new ServerRequest())->withAttribute(RouteResult::class, RouteResult::fromRouteFailure(null)); + $response = (new ResponseHeaderMiddleware(self::CONFIG))->process($request, new FixedResponseHandler()); - $response = new Response(); - $response = $responseHeader->addHeaders($response, 'test'); + $this->assertSame(['X-All' => ['all'], 'X-Overwrite' => ['all']], $response->getHeaders()); + } - $this->assertEmpty($response->getHeaders()); + public function testMatchedRouteAddsRouteHeadersAfterCommonHeaders(): void + { + $response = (new ResponseHeaderMiddleware(self::CONFIG)) + ->process($this->requestForRoute('home'), new FixedResponseHandler()); + + $this->assertSame('home', $response->getHeaderLine('X-Home')); + $this->assertSame('home', $response->getHeaderLine('X-All'), 'route header with overwrite replaces *'); + $this->assertSame('all', $response->getHeaderLine('X-Overwrite'), 'route header without overwrite keeps *'); } - public function testWillAddHeadersWithCommonWithoutRouteSpecificHeadersConfigured(): void + public function testRouteWithoutConfigOnlyAddsCommonHeaders(): void { - $config = [ - '*' => [ - 'CustomHeader1' => [ - 'value' => 'CustomHeader1-Value', - 'overwrite' => true, - ], - 'CustomHeader2' => [ - 'value' => 'CustomHeader2-Value', - 'overwrite' => false, - ], - ], - ]; - $responseHeader = new ResponseHeaderMiddleware($config); + $response = (new ResponseHeaderMiddleware(self::CONFIG)) + ->process($this->requestForRoute('login'), new FixedResponseHandler()); - $response = new Response(); + $this->assertSame(['X-All' => ['all'], 'X-Overwrite' => ['all']], $response->getHeaders()); + } - $response = $responseHeader->addHeaders($response, 'test'); - $this->assertEmpty($response->getHeaders()); - $this->assertFalse($response->hasHeader('CustomHeader1')); - $this->assertFalse($response->hasHeader('CustomHeader2')); + public function testHeaderSetByTheHandlerIsKeptUnlessOverwriteIsTrue(): void + { + $handler = new FixedResponseHandler(['x-all' => 'handler', 'x-overwrite' => 'handler']); + $response = (new ResponseHeaderMiddleware(self::CONFIG))->process(new ServerRequest(), $handler); - $response = $responseHeader->addHeaders($response, '*'); - $this->assertCount(2, $response->getHeaders()); - $this->assertTrue($response->hasHeader('CustomHeader1')); - $this->assertTrue($response->hasHeader('CustomHeader2')); - $this->assertSame($config['*']['CustomHeader1']['value'], $response->getHeaderLine('CustomHeader1')); - $this->assertSame($config['*']['CustomHeader2']['value'], $response->getHeaderLine('CustomHeader2')); + $this->assertSame('handler', $response->getHeaderLine('X-All')); + $this->assertSame('all', $response->getHeaderLine('X-Overwrite')); } - public function testWillAddHeadersWithCommonWithRouteSpecificHeadersConfiguredWhenNoRouteMatched(): void + public function testHeaderWithoutValueIsSkipped(): void { - $config = [ - '*' => [ - 'CustomHeader1' => [ - 'value' => 'CustomHeader1-Value', - 'overwrite' => true, - ], - 'CustomHeader2' => [ - 'value' => 'CustomHeader2-Value', - 'overwrite' => false, - ], - ], - 'home' => [ - 'CustomHeader' => [ - 'value' => 'header3', - ], - ], - ]; - $responseHeader = new ResponseHeaderMiddleware($config); + $response = (new ResponseHeaderMiddleware(['*' => ['X-Empty' => ['overwrite' => true]]])) + ->process(new ServerRequest(), new FixedResponseHandler()); - $response = new Response(); + $this->assertFalse($response->hasHeader('X-Empty')); + } - $response = $responseHeader->addHeaders($response, 'test'); - $this->assertFalse($response->hasHeader('CustomHeader')); - $this->assertEmpty($response->getHeaders()); + /** + * @return iterable}> + */ + public static function validValueProvider(): iterable + { + yield 'string' => ['text', ['text']]; + yield 'int' => [3600, ['3600']]; + yield 'float' => [1.5, ['1.5']]; + yield 'list of strings' => [['Accept', 'Origin'], ['Accept', 'Origin']]; + } + + /** + * @param list $expected + */ + #[DataProvider('validValueProvider')] + public function testAcceptedValueTypes(mixed $value, array $expected): void + { + $response = (new ResponseHeaderMiddleware(['*' => ['X-Value' => ['value' => $value]]])) + ->addHeaders(new Response(), '*'); - $response = $responseHeader->addHeaders($response, '*'); - $this->assertCount(2, $response->getHeaders()); - $this->assertTrue($response->hasHeader('CustomHeader1')); - $this->assertTrue($response->hasHeader('CustomHeader2')); - $this->assertSame($config['*']['CustomHeader1']['value'], $response->getHeaderLine('CustomHeader1')); - $this->assertSame($config['*']['CustomHeader2']['value'], $response->getHeaderLine('CustomHeader2')); + $this->assertSame($expected, $response->getHeader('X-Value')); } - public function testWillAddHeadersWithCommonWithRouteSpecificHeadersConfiguredWhenRouteMatched(): void + /** + * @return iterable, string}> + */ + public static function invalidConfigProvider(): iterable { - $config = [ - '*' => [ - 'CustomHeader1' => [ - 'value' => 'CustomHeader1-Value', - 'overwrite' => true, - ], - 'CustomHeader2' => [ - 'value' => 'CustomHeader2-Value', - 'overwrite' => true, - ], - ], - 'home' => [ - 'CustomHeader' => [ - 'value' => 'header3', - ], - 'CustomHeader1' => [ - 'value' => 'CustomHeader1-Overwritten-Value', - 'overwrite' => true, - ], - 'CustomHeader2' => [ - 'value' => 'CustomHeader2-Overwritten-Value', - 'overwrite' => false, - ], - ], + yield 'route is a string' => [ + ['*' => 'X-All'], + 'dot_response_headers.* must be an array of headers, string given.', + ]; + yield 'header is a string' => [ + ['home' => ['X-Home' => 'home']], + 'dot_response_headers.home.X-Home must be an array with a "value" key, string given.', + ]; + yield 'value is null' => [ + ['*' => ['X-All' => ['value' => null]]], + 'dot_response_headers.*.X-All.value must be a string, a number or a list of strings, null given.', + ]; + yield 'value is an empty array' => [ + ['*' => ['X-All' => ['value' => []]]], + 'dot_response_headers.*.X-All.value must be a string, a number or a list of strings, array given.', + ]; + yield 'value list holds a non-string' => [ + ['*' => ['X-All' => ['value' => ['a', 1]]]], + 'dot_response_headers.*.X-All.value must be a string, a number or a list of strings, array given.', + ]; + yield 'overwrite is an int' => [ + ['*' => ['X-All' => ['value' => 'a', 'overwrite' => 1]]], + 'dot_response_headers.*.X-All.overwrite must be a bool, int given.', ]; - $responseHeader = new ResponseHeaderMiddleware($config); - - $response = new Response(); - - $this->assertFalse($response->hasHeader('CustomHeader1')); - $this->assertFalse($response->hasHeader('CustomHeader2')); - $this->assertFalse($response->hasHeader('CustomHeader')); - $this->assertEmpty($response->getHeaders()); - - $response = $responseHeader->addHeaders($response, '*'); - $this->assertCount(2, $response->getHeaders()); - $this->assertTrue($response->hasHeader('CustomHeader1')); - $this->assertTrue($response->hasHeader('CustomHeader2')); - $this->assertSame($config['*']['CustomHeader1']['value'], $response->getHeaderLine('CustomHeader1')); - $this->assertSame($config['*']['CustomHeader2']['value'], $response->getHeaderLine('CustomHeader2')); - - $response = $responseHeader->addHeaders($response, 'home'); - $this->assertCount(3, $response->getHeaders()); - $this->assertTrue($response->hasHeader('CustomHeader')); - $this->assertTrue($response->hasHeader('CustomHeader1')); - $this->assertTrue($response->hasHeader('CustomHeader2')); - $this->assertSame($config['home']['CustomHeader']['value'], $response->getHeaderLine('CustomHeader')); - $this->assertSame($config['home']['CustomHeader1']['value'], $response->getHeaderLine('CustomHeader1')); - $this->assertSame($config['*']['CustomHeader2']['value'], $response->getHeaderLine('CustomHeader2')); - $this->assertNotSame($config['home']['CustomHeader2']['value'], $response->getHeaderLine('CustomHeader2')); + } + + /** + * @param array $config + */ + #[DataProvider('invalidConfigProvider')] + public function testInvalidConfigIsRejectedOnConstruction(array $config, string $message): void + { + $this->expectException(InvalidConfigException::class); + $this->expectExceptionMessage($message); + + new ResponseHeaderMiddleware($config); + } + + private function requestForRoute(string $name): ServerRequestInterface + { + $middleware = new class implements MiddlewareInterface { + public function process( + ServerRequestInterface $request, + RequestHandlerInterface $handler + ): ResponseInterface { + return $handler->handle($request); + } + }; + + return (new ServerRequest())->withAttribute( + RouteResult::class, + RouteResult::fromRoute(new Route('/' . $name, $middleware, ['GET'], $name)) + ); } }