Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Openapi Psr7 Validator Laravel Package

league/openapi-psr7-validator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require league/openapi-psr7-validator
    
  2. Basic Validation (Request):

    use League\OpenAPIValidation\PSR7\ValidatorBuilder;
    
    $validator = (new ValidatorBuilder())
        ->fromYamlFile(__DIR__.'/api.yaml')
        ->getServerRequestValidator();
    
    $match = $validator->validate($request); // $request is PSR-7 ServerRequestInterface
    
  3. First Use Case: Validate incoming API requests against your OpenAPI spec in a Laravel middleware or controller.


Implementation Patterns

Middleware Integration (PSR-15)

use League\OpenAPIValidation\PSR15\ValidationMiddlewareBuilder;

$middleware = (new ValidationMiddlewareBuilder())
    ->fromYamlFile(__DIR__.'/api.yaml')
    ->getValidationMiddleware();

$app->pipe($middleware); // Laravel's PSR-15 middleware support

Controller Validation

use League\OpenAPIValidation\PSR7\OperationAddress;

public function store(Request $request)
{
    $validator = app(ValidatorBuilder::class)
        ->fromYamlFile(__DIR__.'/api.yaml')
        ->getRoutedRequestValidator();

    $address = new OperationAddress('/users', 'post');
    $validator->validate($address, $request);

    // Proceed with business logic
}

Response Validation

use League\OpenAPIValidation\PSR7\OperationAddress;

public function show(Request $request, User $user)
{
    $response = new Response(200, [], json_encode($user));
    $validator = app(ValidatorBuilder::class)
        ->fromYamlFile(__DIR__.'/api.yaml')
        ->getResponseValidator();

    $address = new OperationAddress('/users/{id}', 'get');
    $validator->validate($address, $response);
}

Caching Schema (PSR-6)

use League\OpenAPIValidation\PSR7\ValidatorBuilder;
use Symfony\Contracts\Cache\CacheInterface;

public function validator(CacheInterface $cache)
{
    return (new ValidatorBuilder())
        ->fromYamlFile(__DIR__.'/api.yaml')
        ->setCache($cache, 3600) // 1 hour TTL
        ->getServerRequestValidator();
}

Custom Format Validation

use League\OpenAPIValidation\Schema\TypeFormats\FormatsContainer;

FormatsContainer::registerFormat('string', 'custom', function($value) {
    return preg_match('/^custom-.*$/', $value);
});

Gotchas and Tips

Common Pitfalls

  1. Missing Content-Type Header: Always ensure requests/responses include Content-Type headers. Catch NoContentType exceptions.

  2. Path/Operation Mismatch: Use getRoutedRequestValidator() when you know the exact endpoint to avoid performance overhead.

  3. Schema Caching: Cache keys are auto-generated. Override with overrideCacheKey() if needed:

    ->setCache($cache, 3600)
    ->overrideCacheKey('api_v1')
    
  4. Nested Validation Errors: Use ValidationFailed exceptions to access detailed error paths:

    try {
        $validator->validate($address, $request);
    } catch (ValidationFailed $e) {
        $errors = $e->getErrors(); // Array of error details
    }
    

Debugging Tips

  1. Schema Validation: Validate your OpenAPI spec first using Swagger Editor to catch syntax errors early.

  2. Middleware Debugging: Wrap middleware in a try-catch to log validation failures:

    try {
        $middleware->process($request, $handler);
    } catch (ValidationFailed $e) {
        Log::error('Validation failed', ['errors' => $e->getErrors()]);
        throw new HttpException(400, 'Invalid request');
    }
    
  3. Performance: Reuse validators and schemas across requests. Avoid rebuilding validators in hot paths.

Extension Points

  1. Custom Error Responses: Extend ValidationFailed to add custom error formatting:

    class CustomValidationFailed extends ValidationFailed {
        public function toArray(): array {
            return ['errors' => $this->getErrors()];
        }
    }
    
  2. Schema Modification: Modify the OpenAPI schema before validation:

    $schema = Reader::readFromYaml(file_get_contents('api.yaml'));
    $schema->paths->addPath('/custom', new PathItem(...));
    $validator = (new ValidatorBuilder())->fromSchema($schema)->getValidator();
    
  3. Security Schemes: Add custom security validation logic by extending SecurityValidator:

    class CustomSecurityValidator extends SecurityValidator {
        protected function validateSecurity($securityRequirements, $request) {
            // Custom logic
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata