├── LICENSE.md ├── README.md ├── composer.json └── src ├── Adapters ├── HttpFoundationAdapter.php └── MessageAdapterInterface.php ├── Cache ├── CacheAdapterInterface.php └── Psr16Adapter.php ├── Exceptions └── ValidationException.php ├── Validator.php ├── ValidatorBuilder.php ├── ValidatorBuilderInterface.php └── ValidatorInterface.php /LICENSE.md: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | 3 | Copyright (c) 2022 Yannick Chenot 4 | 5 | > Permission is hereby granted, free of charge, to any person obtaining a copy 6 | > of this software and associated documentation files (the "Software"), to deal 7 | > in the Software without restriction, including without limitation the rights 8 | > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | > copies of the Software, and to permit persons to whom the Software is 10 | > furnished to do so, subject to the following conditions: 11 | > 12 | > The above copyright notice and this permission notice shall be included in 13 | > all copies or substantial portions of the Software. 14 | > 15 | > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | > THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenAPI HttpFoundation Testing 2 | 3 | [![Build Status](https://github.com/osteel/openapi-httpfoundation-testing/workflows/CI/badge.svg)](https://github.com/osteel/openapi-httpfoundation-testing/actions) 4 | [![Latest Stable Version](https://img.shields.io/packagist/v/osteel/openapi-httpfoundation-testing)](https://packagist.org/packages/osteel/openapi-httpfoundation-testing) 5 | [![License](https://img.shields.io/packagist/l/osteel/openapi-httpfoundation-testing)](https://packagist.org/packages/osteel/openapi-httpfoundation-testing) 6 | [![Downloads](https://img.shields.io/packagist/dt/osteel/openapi-httpfoundation-testing)](https://packagist.org/packages/osteel/openapi-httpfoundation-testing) 7 | 8 | 9 | Validate HttpFoundation requests and responses against OpenAPI (3+) definitions. 10 | 11 | See [this post](https://tech.osteel.me/posts/openapi-backed-api-testing-in-php-projects-a-laravel-example "OpenAPI-backed API testing in PHP projects – a Laravel example") for more details and [this repository](https://github.com/osteel/openapi-httpfoundation-testing-laravel-example) for an example use in a Laravel project. 12 | 13 | > [!IMPORTANT] 14 | > While you can safely use this package for your projects, as long as version `1.0` has not been released "minor" version patches can contain breaking changes. Make sure to check the [release section](../../releases) before you upgrade. 15 | 16 | ## Why? 17 | 18 | [OpenAPI](https://swagger.io/specification/) is a specification intended to describe RESTful APIs in a way that can be understood by both humans and machines. 19 | 20 | By validating an API's requests and responses against the OpenAPI definition that describes it, we guarantee that the API is used correctly and behaves in accordance with the documentation we provide, thus making the OpenAPI definition the single source of truth. 21 | 22 | The [HttpFoundation component](https://symfony.com/doc/current/components/http_foundation.html) is developed and maintained as part of the [Symfony framework](https://symfony.com/). It is used to handle HTTP requests and responses in projects such as Symfony, Laravel, Drupal, and [many others](https://symfony.com/components/HttpFoundation). 23 | 24 | ## How does it work? 25 | 26 | This package is built on top of [OpenAPI PSR-7 Message Validator](https://github.com/thephpleague/openapi-psr7-validator), which validates [PSR-7 messages](https://www.php-fig.org/psr/psr-7/) against OpenAPI definitions. 27 | 28 | It converts HttpFoundation request and response objects to PSR-7 messages using Symfony's [PSR-7 Bridge](https://symfony.com/doc/current/components/psr7.html) and [Tobias Nyholm](https://github.com/Nyholm)'s [PSR-7 implementation](https://github.com/Nyholm/psr7), before passing them on to OpenAPI PSR-7 Message Validator. 29 | 30 | ## Installation 31 | 32 | > [!NOTE] 33 | > This package is mostly intended to be used as part of an API test suite. 34 | 35 | Via Composer: 36 | 37 | ```bash 38 | composer require --dev osteel/openapi-httpfoundation-testing 39 | ``` 40 | 41 | ## Usage 42 | 43 | Import the builder class: 44 | 45 | ```php 46 | use Osteel\OpenApi\Testing\ValidatorBuilder; 47 | ``` 48 | 49 | Use the builder to create a [`\Osteel\OpenApi\Testing\Validator`](/src/Validator.php) object, using one of the available factory methods for YAML or JSON: 50 | 51 | ```php 52 | // From a file: 53 | 54 | $validator = ValidatorBuilder::fromYamlFile($yamlFile)->getValidator(); 55 | $validator = ValidatorBuilder::fromJsonFile($jsonFile)->getValidator(); 56 | 57 | // From a string: 58 | 59 | $validator = ValidatorBuilder::fromYamlString($yamlString)->getValidator(); 60 | $validator = ValidatorBuilder::fromJsonString($jsonString)->getValidator(); 61 | 62 | // Automatic detection (slower): 63 | 64 | $validator = ValidatorBuilder::fromYaml($yamlFileOrString)->getValidator(); 65 | $validator = ValidatorBuilder::fromJson($jsonFileOrString)->getValidator(); 66 | ``` 67 | 68 | > [!TIP] 69 | > You can also use a dependency injection container to bind the `ValidatorBuilder` class to the [`ValidatorBuilderInterface`](/src/ValidatorBuilderInterface.php) interface it implements and inject the interface instead, which would also be useful for testing and mocking. 70 | 71 | You can now validate `\Symfony\Component\HttpFoundation\Request` and `\Symfony\Component\HttpFoundation\Response` objects for a given [path](https://swagger.io/specification/#paths-object) and method: 72 | 73 | ```php 74 | $validator->validate($response, '/users', 'post'); 75 | ``` 76 | 77 | > [!TIP] 78 | > For convenience, objects implementing `\Psr\Http\Message\ServerRequestInterface` or `\Psr\Http\Message\ResponseInterface` are also accepted. 79 | 80 | In the example above, we check that the response matches the OpenAPI definition for a `POST` request on the `/users` path. 81 | 82 | Each of OpenAPI's [supported HTTP methods](https://swagger.io/docs/specification/paths-and-operations/ "Paths and Operations") (`DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST`, `PUT` and `TRACE`) also has a shortcut method that calls `validate` under the hood, meaning the line above could also be written this way: 83 | 84 | ```php 85 | $validator->post($response, '/users'); 86 | ``` 87 | 88 | Validating a request object works exactly the same way: 89 | 90 | ```php 91 | $validator->post($request, '/users'); 92 | ``` 93 | 94 | In the example above, we check that the request matches the OpenAPI definition for a `POST` request on the `/users` path. 95 | 96 | The `validate` method returns `true` in case of success, and throw a [`\Osteel\OpenApi\Testing\Exceptions\ValidationException`](/src/Exceptions/ValidationException.php) exception in case of error. 97 | 98 | ## Caching 99 | 100 | This package supports caching to speed up the parsing of OpenAPI definitions. Simply pass your [PSR-6](https://www.php-fig.org/psr/psr-6/) or [PSR-16](https://www.php-fig.org/psr/psr-16/) cache object to the `setCache` method of the [`ValidatorBuilder`](/src/ValidatorBuilder.php) class. 101 | 102 | Here is an example using Symfony's [Array Cache Adapter](https://symfony.com/doc/current/components/cache/adapters/array_cache_adapter.html "Array Cache Adapter"): 103 | 104 | ```php 105 | use Osteel\OpenApi\Testing\ValidatorBuilder; 106 | use Symfony\Component\Cache\Adapter\ArrayAdapter; 107 | 108 | $cache = new ArrayAdapter(); 109 | $validator = ValidatorBuilder::fromYamlFile($yamlFile)->setCache($cache)->getValidator(); 110 | ``` 111 | 112 | ## Extending the package 113 | 114 | There are two main extension points – message adapters and cache adapters. 115 | 116 | ### Message adapters 117 | 118 | The [`ValidatorBuilder`](/src/ValidatorBuilder.php) class uses the [`HttpFoundationAdapter`](/src/Adapters/HttpFoundationAdapter.php) class as its default HTTP message adapter. This class converts HttpFoundation request and response objects to their PSR-7 counterparts. 119 | 120 | If you need to change the adapter's logic, or if you need a new adapter altogether, create a class implementing the [`MessageAdapterInterface`](/src/Adapters/MessageAdapterInterface.php) interface and pass it to the `setMessageAdapter` method of the [`ValidatorBuilder`](/src/ValidatorBuilder.php) class: 121 | 122 | ```php 123 | $validator = ValidatorBuilder::fromYamlFile($yamlFile) 124 | ->setMessageAdapter($yourAdapter) 125 | ->getValidator(); 126 | ``` 127 | 128 | ### Cache adapters 129 | 130 | The [`ValidatorBuilder`](/src/ValidatorBuilder.php) class uses the [`Psr16Adapter`](/src/Cache/Psr16Adapter.php) class as its default cache adapter. This class converts PSR-16 cache objects to their PSR-6 counterparts. 131 | 132 | If you need to change the adapter's logic, or if you need a new adapter altogether, create a class implementing the [`CacheAdapterInterface`](/src/Cache/CacheAdapterInterface.php) interface and pass it to the `setCacheAdapter` method of the [`ValidatorBuilder`](/src/ValidatorBuilder.php) class: 133 | 134 | ```php 135 | $validator = ValidatorBuilder::fromYamlFile($yamlFile) 136 | ->setCacheAdapter($yourAdapter) 137 | ->getValidator(); 138 | ``` 139 | 140 | ### Other interfaces 141 | 142 | The [`ValidatorBuilder`](/src/ValidatorBuilder.php) and [`Validator`](/src/Validator.php) classes are `final` but they implement the [`ValidatorBuilderInterface`](/src/ValidatorBuilderInterface.php) and [`ValidatorInterface`](/src/ValidatorInterface.php) interfaces respectively for which you can provide your own implementations if you need to. 143 | 144 | ## Change log 145 | 146 | Please see the [Releases section](../../releases) for details. 147 | 148 | ## Contributing 149 | 150 | Please see [CONTRIBUTING](/.github/CONTRIBUTING.md) for details. 151 | 152 | ## Credits 153 | 154 | **People** 155 | 156 | - [Yannick Chenot](https://github.com/osteel) 157 | - [Patrick Rodacker](https://github.com/lordrhodos) 158 | - [Johnathan Michael Dell](https://github.com/johnathanmdell) 159 | - [Paul Mitchum](https://github.com/paul-m) 160 | - [All Contributors](../../contributors) 161 | 162 | Special thanks to [Pavel Batanov](https://github.com/scaytrase) for his advice on structuring the package. 163 | 164 | **Packages** 165 | 166 | - [OpenAPI PSR-7 Message Validator](https://github.com/thephpleague/openapi-psr7-validator) 167 | - [The PSR-7 Bridge](https://symfony.com/doc/current/components/psr7.html) 168 | - [PSR-7 implementation](https://github.com/Nyholm/psr7) 169 | 170 | ## License 171 | 172 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 173 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "osteel/openapi-httpfoundation-testing", 3 | "type": "library", 4 | "description": "Validate HttpFoundation requests and responses against OpenAPI (3+) definitions", 5 | "keywords": [ 6 | "openapi", 7 | "httpfoundation", 8 | "symfony", 9 | "laravel", 10 | "http", 11 | "validation", 12 | "testing", 13 | "api" 14 | ], 15 | "homepage": "https://github.com/osteel/openapi-httpfoundation-testing", 16 | "license": "MIT", 17 | "authors": [ 18 | { 19 | "name": "Yannick Chenot", 20 | "email": "yannick@yellowraincoat.co.uk", 21 | "homepage": "https://github.com/osteel", 22 | "role": "Maintainer" 23 | } 24 | ], 25 | "require": { 26 | "php": "^8.0", 27 | "ext-json": "*", 28 | "league/openapi-psr7-validator": "^0.22", 29 | "nyholm/psr7": "^1.3.1", 30 | "psr/cache": "^1.0 || ^2.0 || ^3.0", 31 | "psr/http-message": "^1.0 || ^2.0", 32 | "psr/simple-cache": "^1.0 || ^2.0 || ^3.0", 33 | "symfony/cache": "^5.0.9 || ^6.0 || ^7.0", 34 | "symfony/http-foundation": "^5.0.9 || ^6.0 || ^7.0", 35 | "symfony/psr-http-message-bridge": "^2.0 || ^6.0 || ^7.0" 36 | }, 37 | "require-dev": { 38 | "friendsofphp/php-cs-fixer": "^3.17", 39 | "phpstan/phpstan": "^1.10", 40 | "phpunit/phpunit": "^9.6", 41 | "rector/rector": "^0.17.1" 42 | }, 43 | "autoload": { 44 | "psr-4": { 45 | "Osteel\\OpenApi\\Testing\\": "src" 46 | } 47 | }, 48 | "autoload-dev": { 49 | "psr-4": { 50 | "Osteel\\OpenApi\\Testing\\Tests\\": "tests" 51 | } 52 | }, 53 | "scripts": { 54 | "fix": "php-cs-fixer fix -v", 55 | "test": "phpunit", 56 | "type": "phpstan", 57 | "all": [ 58 | "@fix", 59 | "@type", 60 | "@test" 61 | ], 62 | "refactor": "rector process" 63 | }, 64 | "extra": { 65 | "branch-alias": { 66 | "dev-master": "1.0-dev" 67 | } 68 | }, 69 | "config": { 70 | "sort-packages": true 71 | }, 72 | "prefer-stable": true 73 | } 74 | -------------------------------------------------------------------------------- /src/Adapters/HttpFoundationAdapter.php: -------------------------------------------------------------------------------- 1 | createResponse($message); 33 | } 34 | 35 | if ($message instanceof Request) { 36 | return $psrHttpFactory->createRequest($message); 37 | } 38 | 39 | throw new InvalidArgumentException(sprintf('Unsupported %s object received', $message::class)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Adapters/MessageAdapterInterface.php: -------------------------------------------------------------------------------- 1 | getMessage(); 18 | 19 | while ($exception = $exception->getPrevious()) { 20 | $message .= sprintf(': %s', $exception->getMessage()); 21 | 22 | if ($exception instanceof SchemaMismatch && ! empty($breadCrumb = $exception->dataBreadCrumb())) { 23 | $message .= sprintf(' Field: %s', implode('.', $breadCrumb->buildChain())); 24 | } 25 | } 26 | 27 | return new ValidationException($message, 0, $previous); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Validator.php: -------------------------------------------------------------------------------- 1 | adapter->convert($message); 36 | $operation = $this->getOperationAddress($path, $method); 37 | $validator = $message instanceof ResponseInterface ? $this->responseValidator : $this->requestValidator; 38 | 39 | try { 40 | $validator->validate($operation, $message); 41 | } catch (ValidationFailed $exception) { 42 | throw ValidationException::fromValidationFailed($exception); 43 | } 44 | 45 | return true; 46 | } 47 | 48 | /** 49 | * Build and return an OperationAddress object from the path and method. 50 | * 51 | * @param string $path the OpenAPI path 52 | * @param string $method the HTTP method 53 | */ 54 | private function getOperationAddress(string $path, string $method): OperationAddress 55 | { 56 | // Make sure the path begins with a forward slash. 57 | $path = sprintf('/%s', ltrim($path, '/')); 58 | 59 | return new OperationAddress($path, strtolower($method)); 60 | } 61 | 62 | /** 63 | * @inheritDoc 64 | * 65 | * @param object $message the HTTP message to validate 66 | * @param string $path the OpenAPI path 67 | * 68 | * @throws ValidationFailed 69 | */ 70 | public function delete(object $message, string $path): bool 71 | { 72 | return $this->validate($message, $path, 'delete'); 73 | } 74 | 75 | /** 76 | * @inheritDoc 77 | * 78 | * @param object $message the HTTP message to validate 79 | * @param string $path the OpenAPI path 80 | * 81 | * @throws ValidationFailed 82 | */ 83 | public function get(object $message, string $path): bool 84 | { 85 | return $this->validate($message, $path, 'get'); 86 | } 87 | 88 | /** 89 | * @inheritDoc 90 | * 91 | * @param object $message the HTTP message to validate 92 | * @param string $path the OpenAPI path 93 | * 94 | * @throws ValidationFailed 95 | */ 96 | public function head(object $message, string $path): bool 97 | { 98 | return $this->validate($message, $path, 'head'); 99 | } 100 | 101 | /** 102 | * @inheritDoc 103 | * 104 | * @param object $message the HTTP message to validate 105 | * @param string $path the OpenAPI path 106 | * 107 | * @throws ValidationFailed 108 | */ 109 | public function options(object $message, string $path): bool 110 | { 111 | return $this->validate($message, $path, 'options'); 112 | } 113 | 114 | /** 115 | * @inheritDoc 116 | * 117 | * @param object $message the HTTP message to validate 118 | * @param string $path the OpenAPI path 119 | * 120 | * @throws ValidationFailed 121 | */ 122 | public function patch(object $message, string $path): bool 123 | { 124 | return $this->validate($message, $path, 'patch'); 125 | } 126 | 127 | /** 128 | * @inheritDoc 129 | * 130 | * @param object $message the HTTP message to validate 131 | * @param string $path the OpenAPI path 132 | * 133 | * @throws ValidationFailed 134 | */ 135 | public function post(object $message, string $path): bool 136 | { 137 | return $this->validate($message, $path, 'post'); 138 | } 139 | 140 | /** 141 | * @inheritDoc 142 | * 143 | * @param object $message the HTTP message to validate 144 | * @param string $path the OpenAPI path 145 | * 146 | * @throws ValidationFailed 147 | */ 148 | public function put(object $message, string $path): bool 149 | { 150 | return $this->validate($message, $path, 'put'); 151 | } 152 | 153 | /** 154 | * @inheritDoc 155 | * 156 | * @param object $message the HTTP message to validate 157 | * @param string $path the OpenAPI path 158 | * 159 | * @throws ValidationFailed 160 | */ 161 | public function trace(object $message, string $path): bool 162 | { 163 | return $this->validate($message, $path, 'trace'); 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /src/ValidatorBuilder.php: -------------------------------------------------------------------------------- 1 | */ 20 | private string $adapter = HttpFoundationAdapter::class; 21 | 22 | /** @var class-string */ 23 | private string $cacheAdapter = Psr16Adapter::class; 24 | 25 | public function __construct(private BaseValidatorBuilder $validatorBuilder) 26 | { 27 | } 28 | 29 | /** 30 | * @inheritDoc 31 | * 32 | * @param string $definition the OpenAPI definition 33 | */ 34 | public static function fromYaml(string $definition): ValidatorBuilderInterface 35 | { 36 | $method = is_file($definition) ? 'fromYamlFile' : 'fromYaml'; 37 | 38 | return self::fromMethod($method, $definition); 39 | } 40 | 41 | /** 42 | * @inheritDoc 43 | * 44 | * @param string $definition the OpenAPI definition 45 | */ 46 | public static function fromJson(string $definition): ValidatorBuilderInterface 47 | { 48 | $method = is_file($definition) ? 'fromJsonFile' : 'fromJson'; 49 | 50 | return self::fromMethod($method, $definition); 51 | } 52 | 53 | /** 54 | * @inheritDoc 55 | * 56 | * @param string $definition the OpenAPI definition's file 57 | */ 58 | public static function fromYamlFile(string $definition): ValidatorBuilderInterface 59 | { 60 | return self::fromMethod('fromYamlFile', $definition); 61 | } 62 | 63 | /** 64 | * @inheritDoc 65 | * 66 | * @param string $definition the OpenAPI definition's file 67 | */ 68 | public static function fromJsonFile(string $definition): ValidatorBuilderInterface 69 | { 70 | return self::fromMethod('fromJsonFile', $definition); 71 | } 72 | 73 | /** 74 | * @inheritDoc 75 | * 76 | * @param string $definition the OpenAPI definition as YAML text 77 | */ 78 | public static function fromYamlString(string $definition): ValidatorBuilderInterface 79 | { 80 | return self::fromMethod('fromYaml', $definition); 81 | } 82 | 83 | /** 84 | * @inheritDoc 85 | * 86 | * @param string $definition the OpenAPI definition as JSON text 87 | */ 88 | public static function fromJsonString(string $definition): ValidatorBuilderInterface 89 | { 90 | return self::fromMethod('fromJson', $definition); 91 | } 92 | 93 | /** 94 | * Create a Validator object based on an OpenAPI definition. 95 | * 96 | * @param string $method the ValidatorBuilder object's method to use 97 | * @param string $definition the OpenAPI definition 98 | */ 99 | private static function fromMethod(string $method, string $definition): ValidatorBuilderInterface 100 | { 101 | $builder = (new BaseValidatorBuilder())->{$method}($definition); 102 | 103 | return new ValidatorBuilder($builder); 104 | } 105 | 106 | /** @inheritDoc */ 107 | public function setCache(object $cache): ValidatorBuilderInterface 108 | { 109 | $adapter = new $this->cacheAdapter(); 110 | 111 | $this->validatorBuilder->setCache($adapter->convert($cache)); 112 | 113 | return $this; 114 | } 115 | 116 | /** @inheritDoc */ 117 | public function getValidator(): ValidatorInterface 118 | { 119 | return new Validator( 120 | $this->validatorBuilder->getRoutedRequestValidator(), 121 | $this->validatorBuilder->getResponseValidator(), 122 | new $this->adapter() 123 | ); 124 | } 125 | 126 | /** 127 | * Change the adapter to use. The provided class must implement \Osteel\OpenApi\Testing\Adapters\AdapterInterface. 128 | * 129 | * @param string $class the adapter's class 130 | * 131 | * @throws InvalidArgumentException 132 | */ 133 | public function setMessageAdapter(string $class): ValidatorBuilder 134 | { 135 | if (is_subclass_of($class, MessageAdapterInterface::class)) { 136 | $this->adapter = $class; 137 | 138 | return $this; 139 | } 140 | 141 | throw new InvalidArgumentException( 142 | sprintf('Class %s does not implement the %s interface', $class, MessageAdapterInterface::class), 143 | ); 144 | } 145 | 146 | /** 147 | * Change the cache adapter to use. The provided class must implement \Osteel\OpenApi\Testing\Cache\AdapterInterface. 148 | * 149 | * @param string $class the cache adapter's class 150 | * 151 | * @throws InvalidArgumentException 152 | */ 153 | public function setCacheAdapter(string $class): ValidatorBuilder 154 | { 155 | if (is_subclass_of($class, CacheAdapterInterface::class)) { 156 | $this->cacheAdapter = $class; 157 | 158 | return $this; 159 | } 160 | 161 | throw new InvalidArgumentException( 162 | sprintf('Class %s does not implement the %s interface', $class, CacheAdapterInterface::class), 163 | ); 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /src/ValidatorBuilderInterface.php: -------------------------------------------------------------------------------- 1 |