├── src ├── Cache │ ├── CacheAdapterInterface.php │ └── Psr16Adapter.php ├── Adapters │ ├── MessageAdapterInterface.php │ └── HttpFoundationAdapter.php ├── Exceptions │ └── ValidationException.php ├── ValidatorBuilderInterface.php ├── ValidatorInterface.php ├── Validator.php └── ValidatorBuilder.php ├── LICENSE.md ├── composer.json └── README.md /src/Cache/CacheAdapterInterface.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/ValidatorBuilderInterface.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 ValidationException 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 ValidationException 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 ValidationException 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 ValidationException 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 ValidationException 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 ValidationException 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 ValidationException 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 ValidationException 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 | */ 21 | private string $adapter = HttpFoundationAdapter::class; 22 | 23 | /** @var class-string */ 24 | private string $cacheAdapter = Psr16Adapter::class; 25 | 26 | public function __construct(private BaseValidatorBuilder $validatorBuilder) 27 | { 28 | } 29 | 30 | /** 31 | * @inheritDoc 32 | * 33 | * @param string $definition the OpenAPI definition 34 | */ 35 | public static function fromYaml(string $definition): ValidatorBuilderInterface 36 | { 37 | return match (true) { 38 | self::isUrl($definition) => self::fromYamlUrl($definition), 39 | is_file($definition) => self::fromYamlFile($definition), 40 | default => self::fromYamlString($definition), 41 | }; 42 | } 43 | 44 | /** 45 | * @inheritDoc 46 | * 47 | * @param string $definition the OpenAPI definition 48 | */ 49 | public static function fromJson(string $definition): ValidatorBuilderInterface 50 | { 51 | return match (true) { 52 | self::isUrl($definition) => self::fromJsonUrl($definition), 53 | is_file($definition) => self::fromJsonFile($definition), 54 | default => self::fromJsonString($definition), 55 | }; 56 | } 57 | 58 | private static function isUrl(string $value): bool 59 | { 60 | if (! filter_var($value, FILTER_VALIDATE_URL)) { 61 | return false; 62 | } 63 | 64 | $scheme = parse_url($value, PHP_URL_SCHEME); 65 | 66 | return in_array($scheme, ['http', 'https'], true); 67 | } 68 | 69 | /** 70 | * @inheritDoc 71 | * 72 | * @param string $definition the OpenAPI definition's file 73 | */ 74 | public static function fromYamlFile(string $definition): ValidatorBuilderInterface 75 | { 76 | return self::fromMethod('fromYamlFile', $definition); 77 | } 78 | 79 | /** 80 | * @inheritDoc 81 | * 82 | * @param string $definition the OpenAPI definition's file 83 | */ 84 | public static function fromJsonFile(string $definition): ValidatorBuilderInterface 85 | { 86 | return self::fromMethod('fromJsonFile', $definition); 87 | } 88 | 89 | /** 90 | * @inheritDoc 91 | * 92 | * @param string $definition the OpenAPI definition as YAML text 93 | */ 94 | public static function fromYamlString(string $definition): ValidatorBuilderInterface 95 | { 96 | return self::fromMethod('fromYaml', $definition); 97 | } 98 | 99 | /** 100 | * @inheritDoc 101 | * 102 | * @param string $definition the OpenAPI definition as JSON text 103 | */ 104 | public static function fromJsonString(string $definition): ValidatorBuilderInterface 105 | { 106 | return self::fromMethod('fromJson', $definition); 107 | } 108 | 109 | /** 110 | * @inheritDoc 111 | * 112 | * @param string $definition the OpenAPI definition's URL 113 | * 114 | * @throws InvalidArgumentException if the URL is invalid 115 | * @throws RuntimeException if the content of the URL cannot be read 116 | */ 117 | public static function fromYamlUrl(string $definition): ValidatorBuilderInterface 118 | { 119 | return self::fromMethod('fromYaml', self::getUrlContent($definition)); 120 | } 121 | 122 | /** 123 | * @inheritDoc 124 | * 125 | * @param string $definition the OpenAPI definition's URL 126 | * 127 | * @throws InvalidArgumentException if the URL is invalid 128 | * @throws RuntimeException if the content of the URL cannot be read 129 | */ 130 | public static function fromJsonUrl(string $definition): ValidatorBuilderInterface 131 | { 132 | return self::fromMethod('fromJson', self::getUrlContent($definition)); 133 | } 134 | 135 | /** 136 | * @throws InvalidArgumentException if the URL is invalid 137 | * @throws RuntimeException if the content of the URL cannot be read 138 | */ 139 | private static function getUrlContent(string $url): string 140 | { 141 | self::isUrl($url) || throw new InvalidArgumentException(sprintf('Invalid URL: %s', $url)); 142 | 143 | if (($content = file_get_contents($url)) === false) { 144 | throw new RuntimeException(sprintf('Failed to read URL %s', $url)); 145 | } 146 | 147 | return $content; 148 | } 149 | 150 | /** 151 | * Create a Validator object based on an OpenAPI definition. 152 | * 153 | * @param string $method the ValidatorBuilder object's method to use 154 | * @param string $definition the OpenAPI definition 155 | */ 156 | private static function fromMethod(string $method, string $definition): ValidatorBuilderInterface 157 | { 158 | $builder = (new BaseValidatorBuilder())->{$method}($definition); 159 | 160 | return new ValidatorBuilder($builder); 161 | } 162 | 163 | /** @inheritDoc */ 164 | public function setCache(object $cache): ValidatorBuilderInterface 165 | { 166 | $adapter = new $this->cacheAdapter(); 167 | 168 | $this->validatorBuilder->setCache($adapter->convert($cache)); 169 | 170 | return $this; 171 | } 172 | 173 | /** @inheritDoc */ 174 | public function getValidator(): ValidatorInterface 175 | { 176 | return new Validator( 177 | $this->validatorBuilder->getRoutedRequestValidator(), 178 | $this->validatorBuilder->getResponseValidator(), 179 | new $this->adapter() 180 | ); 181 | } 182 | 183 | /** 184 | * Change the adapter to use. The provided class must implement \Osteel\OpenApi\Testing\Adapters\AdapterInterface. 185 | * 186 | * @param string $class the adapter's class 187 | * 188 | * @throws InvalidArgumentException 189 | */ 190 | public function setMessageAdapter(string $class): ValidatorBuilder 191 | { 192 | if (is_subclass_of($class, MessageAdapterInterface::class)) { 193 | $this->adapter = $class; 194 | 195 | return $this; 196 | } 197 | 198 | throw new InvalidArgumentException( 199 | sprintf('Class %s does not implement the %s interface', $class, MessageAdapterInterface::class), 200 | ); 201 | } 202 | 203 | /** 204 | * Change the cache adapter to use. The provided class must implement \Osteel\OpenApi\Testing\Cache\AdapterInterface. 205 | * 206 | * @param string $class the cache adapter's class 207 | * 208 | * @throws InvalidArgumentException 209 | */ 210 | public function setCacheAdapter(string $class): ValidatorBuilder 211 | { 212 | if (is_subclass_of($class, CacheAdapterInterface::class)) { 213 | $this->cacheAdapter = $class; 214 | 215 | return $this; 216 | } 217 | 218 | throw new InvalidArgumentException( 219 | sprintf('Class %s does not implement the %s interface', $class, CacheAdapterInterface::class), 220 | ); 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /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 supports PHP 8.0 and above. 34 | 35 | Via Composer: 36 | 37 | ```bash 38 | composer require --dev osteel/openapi-httpfoundation-testing 39 | ``` 40 | 41 | ## Usage 42 | 43 | > [!NOTE] 44 | > This package is mostly intended to be used as part of an API test suite. 45 | 46 | Import the builder class: 47 | 48 | ```php 49 | use Osteel\OpenApi\Testing\ValidatorBuilder; 50 | ``` 51 | 52 | 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: 53 | 54 | ```php 55 | // From a local file: 56 | 57 | $validator = ValidatorBuilder::fromYamlFile($yamlFile)->getValidator(); 58 | $validator = ValidatorBuilder::fromJsonFile($jsonFile)->getValidator(); 59 | 60 | // From a string: 61 | 62 | $validator = ValidatorBuilder::fromYamlString($yamlString)->getValidator(); 63 | $validator = ValidatorBuilder::fromJsonString($jsonString)->getValidator(); 64 | 65 | // From a URL: 66 | 67 | $validator = ValidatorBuilder::fromYamlUrl($yamlUrl)->getValidator(); 68 | $validator = ValidatorBuilder::fromJsonUrl($jsonUrl)->getValidator(); 69 | 70 | // Automatic detection (slower): 71 | 72 | $validator = ValidatorBuilder::fromYaml($yamlFileOrStringOrUrl)->getValidator(); 73 | $validator = ValidatorBuilder::fromJson($jsonFileOrStringOrUrl)->getValidator(); 74 | ``` 75 | 76 | > [!TIP] 77 | > 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. 78 | 79 | 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: 80 | 81 | ```php 82 | $validator->validate($response, '/users', 'post'); 83 | ``` 84 | 85 | > [!TIP] 86 | > For convenience, objects implementing `\Psr\Http\Message\ServerRequestInterface` or `\Psr\Http\Message\ResponseInterface` are also accepted. 87 | 88 | In the example above, we check that the response matches the OpenAPI definition for a `POST` request on the `/users` path. 89 | 90 | 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: 91 | 92 | ```php 93 | $validator->post($response, '/users'); 94 | ``` 95 | 96 | Validating a request object works exactly the same way: 97 | 98 | ```php 99 | $validator->post($request, '/users'); 100 | ``` 101 | 102 | In the example above, we check that the request matches the OpenAPI definition for a `POST` request on the `/users` path. 103 | 104 | 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. 105 | 106 | ## Caching 107 | 108 | 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. 109 | 110 | 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"): 111 | 112 | ```php 113 | use Osteel\OpenApi\Testing\ValidatorBuilder; 114 | use Symfony\Component\Cache\Adapter\ArrayAdapter; 115 | 116 | $cache = new ArrayAdapter(); 117 | $validator = ValidatorBuilder::fromYamlFile($yamlFile)->setCache($cache)->getValidator(); 118 | ``` 119 | 120 | ## Extending the package 121 | 122 | There are two main extension points – message adapters and cache adapters. 123 | 124 | ### Message adapters 125 | 126 | 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. 127 | 128 | 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: 129 | 130 | ```php 131 | $validator = ValidatorBuilder::fromYamlFile($yamlFile) 132 | ->setMessageAdapter($yourAdapter) 133 | ->getValidator(); 134 | ``` 135 | 136 | ### Cache adapters 137 | 138 | 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. 139 | 140 | 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: 141 | 142 | ```php 143 | $validator = ValidatorBuilder::fromYamlFile($yamlFile) 144 | ->setCacheAdapter($yourAdapter) 145 | ->getValidator(); 146 | ``` 147 | 148 | ### Other interfaces 149 | 150 | 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. 151 | 152 | ## Change log 153 | 154 | Please see the [Releases section](../../releases) for details. 155 | 156 | ## Contributing 157 | 158 | Please see [CONTRIBUTING](/.github/CONTRIBUTING.md) for details. 159 | 160 | ## Credits 161 | 162 | **People** 163 | 164 | - [Yannick Chenot](https://github.com/osteel) 165 | - [Patrick Rodacker](https://github.com/lordrhodos) 166 | - [Johnathan Michael Dell](https://github.com/johnathanmdell) 167 | - [Paul Mitchum](https://github.com/paul-m) 168 | - [All Contributors](../../contributors) 169 | 170 | Special thanks to [Pavel Batanov](https://github.com/scaytrase) for his advice on structuring the package. 171 | 172 | **Packages** 173 | 174 | - [OpenAPI PSR-7 Message Validator](https://github.com/thephpleague/openapi-psr7-validator) 175 | - [The PSR-7 Bridge](https://symfony.com/doc/current/components/psr7.html) 176 | - [PSR-7 implementation](https://github.com/Nyholm/psr7) 177 | 178 | ## License 179 | 180 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 181 | --------------------------------------------------------------------------------