### Install Behat OpenAPI PSR-7 Validator with Composer Source: https://github.com/macpaw/behat-openapi-psr7-validator/blob/develop/README.md This command installs the behat-openapi-psr7-validator package as a development dependency using Composer. This is the primary method for adding the validator to your Symfony project. ```bash composer require --dev macpaw/behat-openapi-psr7-validator ``` -------------------------------- ### Install HTTP Client for GitHub Schema Loading Source: https://github.com/macpaw/behat-openapi-psr7-validator/blob/develop/README.md If you intend to load OpenAPI specifications from remote GitHub repositories, you need to install a PSR-18 compatible HTTP client. Symfony's http-client is a common choice. This is an optional step if you only use local OpenAPI files. ```bash composer require symfony/http-client ``` -------------------------------- ### Skip OpenAPI Validation using Gherkin Tags Source: https://github.com/macpaw/behat-openapi-psr7-validator/blob/develop/README.md These Gherkin examples demonstrate how to use tags to control OpenAPI validation within your Behat scenarios. `@skipOpenApiValidation` skips all validation, `@skipOpenApiRequestValidation` skips only request validation, and `@skipOpenApiResponseValidation` skips only response validation. ```gherkin @skipOpenApiValidation Scenario: Skip all validation When I send "GET" request to "some_route" route @skipOpenApiRequestValidation Scenario: Skip only request validation When I send "POST" request to "invalid_request_route" route @skipOpenApiResponseValidation Scenario: Skip only response validation When I send "GET" request to "route_with_custom_response" route ``` -------------------------------- ### Control OpenAPI Validation using Gherkin Steps Source: https://github.com/macpaw/behat-openapi-psr7-validator/blob/develop/README.md These Gherkin examples show how to use specific steps to disable OpenAPI validation during a scenario. 'Given OpenAPI validation is disabled' disables both request and response validation, while 'Given OpenAPI request validation is disabled' and 'Given OpenAPI response validation is disabled' offer granular control. ```gherkin Scenario: Disable validation via step Given OpenAPI validation is disabled When I send "GET" request to "some_route" route Scenario: Disable only request validation Given OpenAPI request validation is disabled When I send "POST" request to "some_route" route Scenario: Disable only response validation Given OpenAPI response validation is disabled When I send "GET" request to "some_route" route ``` -------------------------------- ### Load Schemas from GitHub Repositories with GithubSchemaLoader Source: https://context7.com/macpaw/behat-openapi-psr7-validator/llms.txt The GithubSchemaLoader fetches OpenAPI schemas from GitHub repository directories. It supports both public and private repositories, using token authentication for private ones. It requires HTTP client and PSR-17 factory implementations. ```php 'https://github.com/my-org/api-specs/tree/main/openapi', 'token_env' => null, ], [ // Private repository - token from environment variable 'url' => 'https://github.com/my-org/private-api/tree/develop/docs/schemas', 'token_env' => 'GITHUB_TOKEN', // Reads from $_ENV['GITHUB_TOKEN'] or getenv() ], ]; $loader = new GithubSchemaLoader($sources, $httpClient, $requestFactory); // Fetch all YAML files from configured GitHub directories (recursive) $schemas = $loader->loadSchemas(); // Returns associative array: GitHub path => YAML content // Example output: // [ // 'openapi/users.yaml' => 'openapi: "3.0.0"...', // 'openapi/nested/products.yaml' => 'openapi: "3.0.0"...', // 'docs/schemas/orders.yml' => 'openapi: "3.0.0"...', // ] ``` -------------------------------- ### Load OpenAPI Schemas with LocalSchemaLoader Source: https://context7.com/macpaw/behat-openapi-psr7-validator/llms.txt The LocalSchemaLoader scans specified directories recursively for `.yaml` and `.yml` files, loading them as OpenAPI schemas. It takes an array of directory paths during initialization and returns an associative array mapping file paths to their YAML content. ```php loadSchemas(); // Returns associative array: file path => YAML content // Example output: // [ // '/app/docs/openapi/users.yaml' => 'openapi: "3.0.0"...', // '/app/docs/openapi/products.yaml' => 'openapi: "3.0.0"...', // '/app/vendor/shared-api/schemas/common.yml' => 'openapi: "3.0.0"...', // ] foreach ($schemas as $filePath => $yamlContent) { echo "Loaded schema: {$filePath}\n"; } ``` -------------------------------- ### Configure Behat OpenAPI Validator in Symfony Source: https://github.com/macpaw/behat-openapi-psr7-validator/blob/develop/README.md This YAML configuration file (`config/packages/behat_openapi_validator.yaml`) enables the validator, configures skipping request validation for 4xx responses, specifies local paths for OpenAPI schemas, and optionally configures GitHub sources with a token environment variable. It also registers the `ApiContextListener` as a kernel event subscriber. ```yaml when@test: behat_openapi_validator: is_enabled: true should_request_on_4xx_be_skipped: true local_paths: - '%kernel.project_dir%/docs/openapi' github_sources: - url: 'https://github.com/Owner/Repo/tree/main/docs/openapi' token_env: 'GITHUB_TOKEN' services: BehatOpenApiValidator\EventListener\ApiContextListener: tags: ['kernel.event_subscriber'] ``` -------------------------------- ### Add OpenApiValidatorContext to behat.yml Source: https://github.com/macpaw/behat-openapi-psr7-validator/blob/develop/README.md This YAML configuration for `behat.yml` adds the `OpenApiValidatorContext` to your Behat suite. This context provides the necessary steps for performing OpenAPI validation within your Behat scenarios. ```yaml default: suites: default: contexts: - BehatOpenApiValidator\Context\OpenApiValidatorContext ``` -------------------------------- ### Combine Multiple Schema Sources with CompositeSchemaLoader Source: https://context7.com/macpaw/behat-openapi-psr7-validator/llms.txt The CompositeSchemaLoader aggregates schemas from multiple schema loaders, allowing for the combination of local and remote schema sources. It takes an array of schema loader instances as input. ```php 'https://github.com/my-org/shared-schemas/tree/main/openapi', 'token_env' => null], ], $httpClient, $requestFactory ); // Combine loaders $compositeLoader = new CompositeSchemaLoader([$localLoader, $githubLoader]); // Load from all sources - schemas are merged $allSchemas = $compositeLoader->loadSchemas(); // Contains schemas from both local filesystem and GitHub // Later loaders can override earlier ones if paths conflict ``` -------------------------------- ### Register BehatOpenApiValidatorBundle in Symfony Source: https://github.com/macpaw/behat-openapi-psr7-validator/blob/develop/README.md This PHP code snippet shows how to register the BehatOpenApiValidatorBundle within your Symfony application's `config/bundles.php` file. This enables the extension's functionality for your Behat tests. ```php // config/bundles.php return [ // ... other bundles BehatOpenApiValidator\BehatOpenApiValidatorBundle::class => ['test' => true], ]; ``` -------------------------------- ### Behat Feature: Dynamic Validation Control Steps Source: https://context7.com/macpaw/behat-openapi-psr7-validator/llms.txt Provides Gherkin step definitions for dynamically controlling OpenAPI validation within Behat scenarios. These steps allow you to enable or disable request and response validation on a per-scenario or per-step basis. ```gherkin # features/dynamic_validation.feature Feature: Dynamic Validation Control Scenario: Disable all validation mid-scenario Given OpenAPI validation is disabled When I send "POST" request to "unvalidated_route" route Then the response status code should be 200 Scenario: Disable only request validation Given OpenAPI request validation is disabled When I send "POST" request to "create_resource" route with invalid body Then the response status code should be 422 # Response validation still runs Scenario: Disable only response validation Given OpenAPI response validation is disabled When I send "GET" request to "resource_route" route Then the response should contain custom fields not in schema ``` -------------------------------- ### Configure Behat OpenAPI PSR-7 Validator in Symfony Source: https://context7.com/macpaw/behat-openapi-psr7-validator/llms.txt Configures the Behat OpenAPI PSR-7 Validator, enabling the bundle, controlling request validation on 4xx errors, and specifying OpenAPI schema source locations (local directories or GitHub repositories). ```yaml # config/packages/behat_openapi_validator.yaml when@test: behat_openapi_validator: is_enabled: true should_request_on_4xx_be_skipped: true local_paths: - '%kernel.project_dir%/docs/openapi' github_sources: - url: 'https://github.com/Owner/Repo/tree/main/docs/openapi' token_env: 'GITHUB_TOKEN' services: BehatOpenApiValidator\EventListener\ApiContextListener: tags: ['kernel.event_subscriber'] ``` -------------------------------- ### Capture Request/Response for Validation with ApiContextListener Source: https://context7.com/macpaw/behat-openapi-psr7-validator/llms.txt The ApiContextListener is a Symfony event subscriber that captures HTTP requests and responses, storing them in RequestResponseHolder for the Behat context to access during validation. It is typically registered as a service with the 'kernel.event_subscriber' tag. ```php 'application/json'] ); // Validate request against OpenAPI schema $requestResult = $validator->validateRequest($request); if ($requestResult->isValid()) { echo "Request is valid\n"; echo "Schema: " . $requestResult->getSchemaPath() . "\n"; // OperationAddress can be used for response validation $operationAddress = $requestResult->getOperationAddress(); } else { echo "Request validation failed: " . $requestResult->getErrorMessage() . "\n"; } // Create sample response $response = new Response( content: json_encode(['id' => 123, 'name' => 'John Doe', 'email' => 'john@example.com']), status: 200, headers: ['Content-Type' => 'application/json'] ); // Validate response (pass operation address from request validation for efficiency) $responseResult = $validator->validateResponse( $request, $response, $requestResult->getOperationAddress(), $requestResult->getSchemaPath() ); if ($responseResult->isValid()) { echo "Response is valid\n"; } else { echo "Response validation failed: " . $responseResult->getErrorMessage() . "\n"; // Detailed error includes field path information // Example: "Field: data.users.0.email | Value expected to be 'string' | Body does not match schema" } ``` -------------------------------- ### Understand ValidationResult Object Source: https://context7.com/macpaw/behat-openapi-psr7-validator/llms.txt The ValidationResult class is returned by OpenApiValidator methods and encapsulates validation outcomes. It provides methods to check validity, retrieve detailed error messages, the matched operation address, and the schema path used during validation. ```php validateRequest($request); // Check if validation passed if ($result->isValid()) { // Get the matched OpenAPI operation $operationAddress = $result->getOperationAddress(); // OperationAddress contains path pattern and HTTP method // e.g., "/users/{id}" and "get" // Get the schema file path that matched $schemaPath = $result->getSchemaPath(); // e.g., "/app/docs/openapi/users.yaml" } else { // Get detailed error message with field paths $error = $result->getErrorMessage(); // Example output: // "Field: email | Value expected to be 'string' | Keyword validation failed: type" // Schema path is still available even on failure $schemaPath = $result->getSchemaPath(); } ``` -------------------------------- ### Configure OpenApiValidatorContext in Behat Source: https://context7.com/macpaw/behat-openapi-psr7-validator/llms.txt Configures Behat to use the `OpenApiValidatorContext` for API validation. This step definition class is essential for enabling automatic request and response validation against OpenAPI schemas during your Behat tests. ```yaml # behat.yml default: suites: default: contexts: - BehatOpenApiValidator\Context\OpenApiValidatorContext ``` -------------------------------- ### Behat Feature: Automatic OpenAPI Validation Source: https://context7.com/macpaw/behat-openapi-psr7-validator/llms.txt Demonstrates automatic OpenAPI validation in Behat scenarios. By default, `OpenApiValidatorContext` validates requests and responses. Gherkin tags like `@skipOpenApiValidation`, `@skipOpenApiRequestValidation`, and `@skipOpenApiResponseValidation` allow for granular control over this process. ```gherkin # features/api.feature Feature: User API # Automatic validation - no extra steps needed Scenario: Get user by ID When I send "GET" request to "get_user" route with parameters: | id | 123 | Then the response status code should be 200 # Request and response are automatically validated against OpenAPI schema # Skip all OpenAPI validation for this scenario @skipOpenApiValidation Scenario: Custom endpoint not in OpenAPI spec When I send "GET" request to "custom_route" route Then the response status code should be 200 # Skip only request validation (useful for testing invalid requests) @skipOpenApiRequestValidation Scenario: Test invalid request handling When I send "POST" request to "create_user" route with body: | invalid_field | value | Then the response status code should be 400 # Response is still validated to ensure proper error format # Skip only response validation @skipOpenApiResponseValidation Scenario: Response has extra undocumented fields When I send "GET" request to "legacy_endpoint" route Then the response status code should be 200 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.