### Create Validators using ValidatorBuilder from OpenAPI Specs Source: https://context7.com/thephpleague/openapi-psr7-validator/llms.txt Demonstrates how to use the ValidatorBuilder to create validators from various OpenAPI specification sources. It shows loading from YAML files, JSON files, raw YAML strings, and raw JSON strings. The examples also illustrate how to obtain either a Server Request Validator or a Response Validator. Optional PSR-6 caching can be enabled for performance optimization. ```php fromYamlFile('api.yaml') ->getServerRequestValidator(); // Create validator from JSON file $validator = (new ValidatorBuilder()) ->fromJsonFile('api.json') ->getServerRequestValidator(); // Create validator from raw YAML string $yamlSpec = <<fromYaml($yamlSpec) ->getServerRequestValidator(); // Create validator from raw JSON string $jsonSpec = json_encode([ 'openapi' => '3.0.0', 'info' => ['title' => 'Sample API', 'version' => '1.0.0'], 'paths' => ['/users' => ['get' => ['responses' => ['200' => ['description' => 'Success']]]]] ]); $validator = (new ValidatorBuilder()) ->fromJson($jsonSpec) ->getResponseValidator(); // Enable PSR-6 caching for better performance $cachePool = new ArrayAdapter(); $validator = (new ValidatorBuilder()) ->fromYamlFile('api.yaml') ->setCache($cachePool, 3600) // TTL in seconds ->overrideCacheKey('my_api_schema') // Optional custom cache key ->getServerRequestValidator(); ``` -------------------------------- ### Install OpenAPI PSR-7 Validator via Composer Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md Installs the OpenAPI PSR-7 Validator package using Composer. This is the primary method for adding the library to your PHP project. ```bash composer require league/openapi-psr7-validator ``` -------------------------------- ### Standalone OpenAPI Schema Validation Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md This example shows how to use the standalone validator to validate arbitrary data against an OpenAPI schema defined in YAML. It covers reading the schema, resolving references, creating a `Schema` object, and then using `SchemaValidator` to validate the data. It also includes a `try-catch` block to handle `KeywordMismatch` exceptions, allowing inspection of validation failures. ```php $spec = <<<'SPEC' schema: type: string enum: - a - b SPEC; $data = "c"; $spec = cebeopenapiReader::readFromYaml($spec); # (optional) reference resolving $spec->resolveReferences(new ReferenceContext($spec, "/")); $schema = new cebeopenapispecSchema($spec->schema); try { (new LeagueOpenAPIValidationSchemaSchemaValidator())->validate($data, $schema); } catch(LeagueOpenAPIValidationSchemaExceptionKeywordMismatch $e) { // you can evaluate failure details // $e->keyword() == "enum" // $e->data() == "c" // $e->dataBreadCrumb()->buildChain() -- only for nested data } ``` -------------------------------- ### Validate PSR-7 Request with Pre-matched Operation (PHP) Source: https://context7.com/thephpleague/openapi-psr7-validator/llms.txt Demonstrates how to use RoutedServerRequestValidator to validate a PSR-7 ServerRequest against a specific OpenAPI operation. It requires an OpenAPI specification, a ValidatorBuilder, and an OperationAddress object. The example shows validation for both a valid and an invalid request body. ```php fromYaml($spec) ->getRoutedRequestValidator(); // When you know the operation from your router $operationAddress = new OperationAddress('/products/{productId}', 'put'); $request = (new ServerRequest('PUT', 'https://api.example.com/products/42')) ->withHeader('Content-Type', 'application/json') ->withBody(Utils::streamFor(json_encode([ 'name' => 'Updated Product', 'price' => 29.99 ]))); try { // No operation matching needed - we specify the operation directly $validator->validate($operationAddress, $request); echo "Request is valid for PUT /products/{productId}"; } catch (InvalidBody $e) { echo "Invalid body: " . $e->getMessage(); } // Invalid request - negative price $invalidRequest = (new ServerRequest('PUT', 'https://api.example.com/products/42')) ->withHeader('Content-Type', 'application/json') ->withBody(Utils::streamFor(json_encode([ 'name' => 'Product', 'price' => -10 // Violates minimum: 0 ]))); try { $validator->validate($operationAddress, $invalidRequest); } catch (InvalidBody $e) { echo $e->getMessage(); // Body does not match schema for content-type "application/json" for Request [put /products/{productId}] } ``` -------------------------------- ### SlimAdapter - Slim Framework Integration Source: https://context7.com/thephpleague/openapi-psr7-validator/llms.txt The `SlimAdapter` wraps PSR-15 middleware, such as the `ValidationMiddleware`, for seamless integration with Slim Framework's double-pass middleware interface. This allows you to apply OpenAPI validation to routes within a Slim application. ```php fromYaml($spec) ->getValidationMiddleware(); // Wrap in Slim adapter $slimMiddleware = new SlimAdapter($psr15Middleware); // Add to Slim application $app = AppFactory::create(); $app->add($slimMiddleware); $app->get('/hello/{name}', function ($request, $response, $args) { $payload = json_encode(['message' => 'Hello, ' . $args['name'] . '!']); $response->getBody()->write($payload); return $response->withHeader('Content-Type', 'application/json'); }); $app->run(); ``` -------------------------------- ### Reference API Operations with OperationAddress (PHP) Source: https://context7.com/thephpleague/openapi-psr7-validator/llms.txt Explains the use of the `OperationAddress` class in PHP for representing specific API operations defined by their path and HTTP method. It covers creating instances, accessing path and method details, string representation, checking for and counting path placeholders, parsing URL parameters against a path template, and verifying if a given path matches a specification pattern. ```php path(); // Output: /users/{id} echo $getUserOp->method(); // Output: get // String representation echo (string) $createUserOp; // Output: Request [post /users] // Check if path has placeholders var_dump($getUserOp->hasPlaceholders()); // Output: bool(true) var_dump($createUserOp->hasPlaceholders()); // Output: bool(false) // Count placeholders echo $getUserOp->countPlaceholders(); // Output: 1 // Parse actual URL values against path template $parsedParams = $getUserOp->parseParams('/users/123'); print_r($parsedParams); // Output: Array ( [id] => 123 ) // Complex path with multiple parameters $complexOp = new OperationAddress('/orgs/{orgId}/repos/{repoId}/issues/{issueId}', 'get'); $params = $complexOp->parseParams('/orgs/acme/repos/api/issues/42'); print_r($params); // Output: Array ( [orgId] => acme, [repoId] => api, [issueId] => 42 ) // Check if path matches specification pattern $matches = OperationAddress::isPathMatchesSpec('/users/{id}', '/users/123'); var_dump($matches); // Output: bool(true) $matches = OperationAddress::isPathMatchesSpec('/users/{id}', '/users/123/profile'); var_dump($matches); // Output: bool(false) ``` -------------------------------- ### Running Package Tests Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md This command provides instructions on how to execute the test suite for the OpenAPI PSR-7 Validator package. It specifies the command to be run from the project's root directory using the PHPUnit test runner. ```bash vendor/bin/phpunit ``` -------------------------------- ### Adapt PSR-15 Middleware for Slim Framework Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md Provides an adapter to use the PSR-15 validation middleware with the Slim Framework. It demonstrates creating the middleware and then wrapping it with the SlimAdapter for integration into a Slim application's middleware stack. ```php $yamlFile = 'api.yaml'; $jsonFile = 'api.json'; $psr15Middleware = (new \League\OpenAPIValidation\PSR15\ValidationMiddlewareBuilder)->fromYamlFile($yamlFile)->getValidationMiddleware(); #or $psr15Middleware = (new \League\OpenAPIValidation\PSR15\ValidationMiddlewareBuilder)->fromYaml(file_get_contents($yamlFile))->getValidationMiddleware(); #or $psr15Middleware = (new \League\OpenAPIValidation\PSR15\ValidationMiddlewareBuilder)->fromJsonFile($jsonFile)->getValidationMiddleware(); #or $psr15Middleware = (new \League\OpenAPIValidation\PSR15\ValidationMiddlewareBuilder)->fromJson(file_get_contents($jsonFile))->getValidationMiddleware(); #or $schema = new \cebe\openapi\spec\OpenApi(); // generate schema object by hand $validator = (new \League\OpenAPIValidation\PSR7\ValidationMiddlewareBuilder)->fromSchema($schema)->getValidationMiddleware(); $slimMiddleware = new \League\OpenAPIValidation\PSR15\SlimAdapter($psr15Middleware); /** @var \Slim\App $app */ $app->add($slimMiddleware); ``` -------------------------------- ### Configure PSR-15 Validation Middleware Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md This snippet demonstrates how to build and configure a PSR-15 validation middleware using the `ValidationMiddlewareBuilder`. It shows how to load the OpenAPI specification from a YAML file, set a cache pool for schema validation, and retrieve the configured middleware. The cache can be configured with expiration TTLs and custom cache keys. ```php $psr15Middleware = (new OpenAPIValidationPSR15ValidationMiddlewareBuilder) ->fromYamlFile($yamlFile) ->setCache($cachePool) ->getValidationMiddleware(); ``` -------------------------------- ### Access and Inspect OpenAPI Schema After Validation (PHP) Source: https://context7.com/thephpleague/openapi-psr7-validator/llms.txt This snippet shows how to obtain the parsed OpenAPI schema object after performing validation using League\OpenAPIValidation\PSR7\ValidatorBuilder. It demonstrates accessing schema details like API title, version, and path information. This is useful for inspecting the API contract or performing custom logic based on the schema. ```php fromYaml($spec) ->getServerRequestValidator(); // After validation, access the underlying OpenAPI schema $openApiSchema = $validator->getSchema(); // Inspect schema details echo "API Title: " . $openApiSchema->info->title; // Output: API echo "API Version: " . $openApiSchema->info->version; // Output: 1.0.0 // Access paths foreach ($openApiSchema->paths as $path => $pathItem) { echo "Path: " . $path; // Output: /items if (isset($pathItem->get)) { echo "GET operation ID: " . $pathItem->get->operationId; // Output: listItems } } // Reuse same schema for both request and response validators $builder = (new ValidatorBuilder())->fromYaml($spec); $requestValidator = $builder->getServerRequestValidator(); $responseValidator = $builder->getResponseValidator(); // Both validators share the same parsed schema $schema1 = $requestValidator->getSchema(); $schema2 = $responseValidator->getSchema(); ``` -------------------------------- ### Validate Data Against OpenAPI Schema with PHP Source: https://context7.com/thephpleague/openapi-psr7-validator/llms.txt This snippet demonstrates how to use the SchemaValidator to validate arbitrary PHP data against an OpenAPI schema defined in YAML. It covers successful validation and various failure scenarios like keyword mismatches (pattern, enum), type mismatches, and format mismatches. Dependencies include the 'cebe/openapi' and 'league/openapi-psr7-validator' libraries. ```php resolveReferences(new ReferenceContext($spec, '/')); $schema = new Schema($spec->schema); // Validate data $validator = new SchemaValidator(SchemaValidator::VALIDATE_AS_REQUEST); // Valid data $validData = [ 'username' => 'john_doe', 'email' => 'john@example.com', 'age' => 25, 'role' => 'user' ]; try { $validator->validate($validData, $schema); echo "Data is valid!"; } catch (KeywordMismatch $e) { echo "Validation failed on keyword: " . $e->keyword(); } // Invalid data - pattern mismatch $invalidUsername = [ 'username' => 'john doe', // Contains space, violates pattern 'email' => 'john@example.com', 'age' => 25 ]; try { $validator->validate($invalidUsername, $schema); } catch (KeywordMismatch $e) { echo "Failed keyword: " . $e->keyword(); // Output: pattern echo "Invalid data: " . json_encode($e->data()); // Output: "john doe" } // Invalid data - type mismatch $invalidAge = [ 'username' => 'john_doe', 'email' => 'john@example.com', 'age' => 'twenty-five' // Should be integer ]; try { $validator->validate($invalidAge, $schema); } catch (TypeMismatch $e) { echo "Type mismatch: expected integer"; } // Invalid data - enum violation $invalidRole = [ 'username' => 'john_doe', 'email' => 'john@example.com', 'age' => 25, 'role' => 'superadmin' // Not in enum ]; try { $validator->validate($invalidRole, $schema); } catch (KeywordMismatch $e) { echo "Failed keyword: " . $e->keyword(); // Output: enum } ``` -------------------------------- ### Implement PSR-15 Validation Middleware Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md Shows how to build and obtain a PSR-15 compliant middleware for validating requests or responses against an OpenAPI specification. It supports loading the specification from YAML or JSON files, or directly from a schema object. ```php $yamlFile = 'api.yaml'; $jsonFile = 'api.json'; $psr15Middleware = (new \League\OpenAPIValidation\PSR15\ValidationMiddlewareBuilder)->fromYamlFile($yamlFile)->getValidationMiddleware(); #or $psr15Middleware = (new \League\OpenAPIValidation\PSR15\ValidationMiddlewareBuilder)->fromYaml(file_get_contents($yamlFile))->getValidationMiddleware(); #or $psr15Middleware = (new \League\OpenAPIValidation\PSR15\ValidationMiddlewareBuilder)->fromJsonFile($jsonFile)->getValidationMiddleware(); #or $psr15Middleware = (new \League\OpenAPIValidation\PSR15\ValidationMiddlewareBuilder)->fromJson(file_get_contents($jsonFile))->getValidationMiddleware(); #or $schema = new \cebe\openapi\spec\OpenApi(); // generate schema object by hand $validator = (new \League\OpenAPIValidation\PSR7\ValidationMiddlewareBuilder)->fromSchema($schema)->getValidationMiddleware(); ``` -------------------------------- ### Validate Server Requests with OpenAPI Spec (PHP) Source: https://context7.com/thephpleague/openapi-psr7-validator/llms.txt This snippet demonstrates how to use the ServerRequestValidator to validate an incoming PSR-7 ServerRequest against an OpenAPI 3.0 specification defined in YAML. It covers setting up the validator, creating a valid and an invalid request, and handling various validation exceptions. ```php fromYaml($spec) ->getServerRequestValidator(); // Valid request $request = (new ServerRequest('POST', 'https://api.example.com/users')) ->withHeader('Content-Type', 'application/json') ->withHeader('X-Request-ID', '550e8400-e29b-41d4-a716-446655440000') ->withBody(Utils::streamFor(json_encode([ 'name' => 'John Doe', 'email' => 'john@example.com' ]))); try { $matchedOperation = $validator->validate($request); echo "Request valid! Matched operation: " . $matchedOperation->path() . " " . $matchedOperation->method(); // Output: Request valid! Matched operation: /users post } catch (InvalidBody $e) { echo "Invalid body: " . $e->getMessage(); } catch (InvalidHeaders $e) { echo "Invalid headers: " . $e->getMessage(); } catch (InvalidQueryArgs $e) { echo "Invalid query args: " . $e->getMessage(); } catch (NoOperation $e) { echo "No matching operation found: " . $e->getMessage(); } catch (ValidationFailed $e) { echo "Validation failed: " . $e->getMessage(); } // Invalid request - missing required header $invalidRequest = (new ServerRequest('POST', 'https://api.example.com/users')) ->withHeader('Content-Type', 'application/json') ->withBody(Utils::streamFor(json_encode(['name' => 'John', 'email' => 'john@example.com']))); try { $validator->validate($invalidRequest); } catch (InvalidHeaders $e) { echo $e->getMessage(); // Output: Missing required header "X-Request-ID" for Request [post /users] } ``` -------------------------------- ### RoutedServerRequestValidator Usage Source: https://context7.com/thephpleague/openapi-psr7-validator/llms.txt Demonstrates how to use the RoutedServerRequestValidator to validate a PSR-7 ServerRequest against a specific OpenAPI operation, bypassing the need for operation matching. ```APIDOC ## POST /products/{productId} ### Description Validates a request against a pre-defined OpenAPI operation, useful when a router has already identified the target operation. ### Method PUT ### Endpoint /products/{productId} ### Parameters #### Path Parameters - **productId** (integer) - Required - The ID of the product to update. #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the product. - **price** (number) - Required - The price of the product. Must be 0 or greater. ### Request Example ```json { "name": "Updated Product", "price": 29.99 } ``` ### Response #### Success Response (200) - **description** (string) - Indicates that the product was successfully updated. #### Response Example ```json { "message": "Product updated" } ``` ### Error Handling - **InvalidBody**: Thrown if the request body does not conform to the specified schema for the given content type. ``` -------------------------------- ### PSR-15 ValidationMiddleware - Automatic Request/Response Validation Source: https://context7.com/thephpleague/openapi-psr7-validator/llms.txt The `ValidationMiddleware` implements `PsrHttpServerMiddlewareInterface` for automatic validation of both incoming requests and outgoing responses in a PSR-15 middleware stack. It takes an OpenAPI specification and a request handler, returning a validated response or throwing an exception on validation failure. ```php fromYaml($spec) ->getValidationMiddleware(); // Example handler that processes the request $handler = new class implements RequestHandlerInterface { public function handle(ServerRequestInterface $request): ResponseInterface { // Process the validated request return (new Response(201)) ->withHeader('Content-Type', 'application/json') ->withBody(Utils::streamFor(json_encode([ 'orderId' => '550e8400-e29b-41d4-a716-446655440000' ]))); } }; // Valid request through middleware $request = (new ServerRequest('POST', 'https://api.example.com/orders')) ->withHeader('Content-Type', 'application/json') ->withBody(Utils::streamFor(json_encode([ 'items' => [ ['productId' => 1, 'quantity' => 2], ['productId' => 5, 'quantity' => 1] ] ]))); try { $response = $middleware->process($request, $handler); echo "Order created successfully!"; } catch (InvalidServerRequestMessage $e) { // Request failed validation echo "Invalid request: " . $e->getPrevious()->getMessage(); } catch (InvalidResponseMessage $e) { // Response failed validation echo "Invalid response: " . $e->getPrevious()->getMessage(); } ``` -------------------------------- ### Validate PSR-7 Response with OpenAPI Specification Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md Demonstrates how to create a response validator using ValidatorBuilder from various sources like YAML files, JSON files, or a manually created schema object. It then shows how to validate a PSR-7 response against an OpenAPI operation. ```php $yamlFile = "api.yaml"; $jsonFile = "api.json"; $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromYamlFile($yamlFile)->getResponseValidator(); #or $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromYaml(file_get_contents($yamlFile))->getResponseValidator(); #or $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromJson(file_get_contents($jsonFile))->getResponseValidator(); #or $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromJsonFile($jsonFile)->getResponseValidator(); #or $schema = new \cebe\openapi\spec\OpenApi(); // generate schema object by hand $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromSchema($schema)->getResponseValidator(); $operation = new \League\OpenAPIValidation\PSR7\OperationAddress('/password/gen', 'get') ; $validator->validate($operation, $response); ``` -------------------------------- ### Enable PSR-6 Caching for OpenAPI Specs Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md Demonstrates how to configure and enable a PSR-6 compliant caching layer for the OpenAPI schema parsing process. This is done by passing a configured Cache Pool object to the ValidatorBuilder's setCache method, which can significantly improve performance by avoiding repeated parsing. ```php // Configure a PSR-6 Cache Pool $cachePool = new ArrayCachePool(); // Pass it as a 2nd argument $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder) ->fromYamlFile($yamlFile) ->setCache($cachePool) ->getResponseValidator(); ``` -------------------------------- ### Register Custom Type Formats for Validation Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md This code illustrates how to register custom format validators for OpenAPI schema types. It shows how to define a custom format validator as either a class with an `__invoke` method or a simple closure. The `FormatsContainer::registerFormat` method is then used to associate the custom validator with a specific type (e.g., 'string') and format name (e.g., 'custom'). ```php # A format validator must be a callable # It must return bool value (true if format matched the data, false otherwise) # A callable class: $customFormat = new class() { function __invoke($value): bool { return $value === "good value"; } }; # Or just a closure: $customFormat = function ($value): bool { return $value === "good value"; }; # Register your callable like this before validating your data LeagueOpenAPIValidationSchemaTypeFormatsFormatsContainer::registerFormat('string', 'custom', $customFormat); ``` -------------------------------- ### Validate Server Request with OpenAPI Specification Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md Validates a PSR-7 ServerRequestInterface against an OpenAPI specification. The specification can be loaded from a YAML file, a JSON file, a YAML string, a JSON string, or a pre-built schema object. It returns an OperationAddress if a match is found. ```php $yamlFile = "api.yaml"; $jsonFile = "api.json"; $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromYamlFile($yamlFile)->getServerRequestValidator(); #or $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromYaml(file_get_contents($yamlFile))->getServerRequestValidator(); #or $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromJson(file_get_contents($jsonFile))->getServerRequestValidator(); #or $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromJsonFile($jsonFile)->getServerRequestValidator(); #or $schema = new \cebe\openapi\spec\OpenApi(); // generate schema object by hand $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromSchema($schema)->getServerRequestValidator(); $match = $validator->validate($request); ``` -------------------------------- ### Validate PSR-7 Response against OpenAPI Spec (PHP) Source: https://context7.com/thephpleague/openapi-psr7-validator/llms.txt This snippet shows how to use the ResponseValidator to validate a PSR-7 Response object against an OpenAPI specification defined in YAML. It covers setting up the validator, defining the operation, and handling validation exceptions for both valid and invalid responses. ```php fromYaml($spec) ->getResponseValidator(); $operation = new OperationAddress('/users/{id}', 'get'); // Valid response $response = (new Response(200)) ->withHeader('Content-Type', 'application/json') ->withHeader('X-Rate-Limit', '100') ->withBody(Utils::streamFor(json_encode([ 'id' => 123, 'name' => 'John Doe', 'email' => 'john@example.com' ]))); try { $validator->validate($operation, $response); echo "Response is valid!"; } catch (InvalidBody $e) { echo "Invalid response body: " . $e->getMessage(); } catch (InvalidHeaders $e) { echo "Invalid response headers: " . $e->getMessage(); } // Invalid response - body schema mismatch (id should be integer) $invalidResponse = (new Response(200)) ->withHeader('Content-Type', 'application/json') ->withHeader('X-Rate-Limit', '100') ->withBody(Utils::streamFor(json_encode([ 'id' => 'not-an-integer', // Wrong type! 'name' => 'John Doe' ]))); try { $validator->validate($operation, $invalidResponse); } catch (InvalidBody $e) { echo $e->getMessage(); // Output: Body does not match schema for content-type "application/json" for Response [get /users/{id} 200] } ``` -------------------------------- ### Reuse OpenAPI Schema Object After Validation Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md Illustrates how to obtain the parsed OpenAPI schema object (an instance of \cebe\openapi\spec\OpenApi) after creating a validator. This allows for reusing the schema for other purposes without re-parsing. ```php $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromYamlFile($yamlFile)->getServerRequestValidator(); # or $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromYamlFile($yamlFile)->getResponseValidator(); /** @var \cebe\openapi\spec\OpenApi */ $openApi = $validator->getSchema(); ``` -------------------------------- ### Validate Request with OpenAPI Specification Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md Validates a PSR-7 RequestInterface against an OpenAPI specification. Similar to Server Request validation, it supports loading the specification from various sources (files, strings, schema objects) and returns an OperationAddress upon successful validation. ```php $yamlFile = "api.yaml"; $jsonFile = "api.json"; $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromYamlFile($yamlFile)->getRequestValidator(); #or $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromYaml(file_get_contents($yamlFile))->getRequestValidator(); #or $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromJson(file_get_contents($jsonFile))->getRequestValidator(); #or $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromJsonFile($jsonFile)->getRequestValidator(); #or $schema = new \cebe\openapi\spec\OpenApi(); // generate schema object by hand $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromSchema($schema)->getRequestValidator(); $match = $validator->validate($request); ``` -------------------------------- ### Validate Routed Server Request with OpenAPI Specification Source: https://github.com/thephpleague/openapi-psr7-validator/blob/master/README.md Validates a PSR-7 ServerRequestInterface against a specific operation within an OpenAPI specification, identified by a path and method. This method is more performant if the operation is already known. ```php $address = new \League\OpenAPIValidation\PSR7\OperationAddress('/some/operation', 'post'); $validator = (new \League\OpenAPIValidation\PSR7\ValidatorBuilder)->fromSchema($schema)->getRoutedRequestValidator(); $validator->validate($address, $request); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.