PHP code example of twentytwo-labs / api-validator

1. Go to this page and download the library: Download twentytwo-labs/api-validator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

twentytwo-labs / api-validator example snippets




use JsonSchema\Validator;
use Symfony\Component\Serializer\Encoder\JsonDecode;
use Symfony\Component\Serializer\Encoder\ChainDecoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use TwentytwoLabs\ApiValidator\Factory\SwaggerSchemaFactory;
use TwentytwoLabs\ApiValidator\Factory\OpenApiSchemaFactory;
use TwentytwoLabs\ApiValidator\Decoder\Adapter\SymfonyDecoderAdapter;
use TwentytwoLabs\ApiValidator\Validator\MessageValidator;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

// Given a $request implementing the `Psr\Http\Message\RequestInterface`
// For this example we are using the PSR7 Guzzle implementation;
$request = new Request(
    'POST', 
    'http://domain.tld/api/pets',
    ['application/json'],
    '{"id": 1, "name": "puppy"}'
);

$validator = new Validator();

// Here we are using decoders provided by the symfony serializer component
// feel free to use yours if you so desire. You just need to create an adapter that 
// implement the `TwentytwoLabs\ApiValidator\Decoder\DecoderInterface` 
$decoder = new SymfonyDecoderAdapter(
    new ChainDecoder([
        new JsonDecode(),
        new XmlEncoder()
    ])  
);

// Load a JSON swagger 2.0 schema using the SwaggerSchemaFactory class.
$schema = (new SwaggerSchemaFactory())->createSchema('file://path/to/your/swagger.json');

// Load a JSON swagger 3.0 schema using the OpenApiSchemaFactory class.
$schema = (new OpenApiSchemaFactory())->createSchema('file://path/to/your/swagger.json');

// Find the Request Definition in the Schema API
$requestDefinition = $schema->getRequestDefinition(
  $schema->findOperationId($request->getMethod(), $request->getUri()->getPath())  
);

// Validate the Request
$messageValidator = new MessageValidator($validator, $decoder);
$messageValidator->validateRequest($request, $requestDefinition);

// Check if the request has violations
if ($messageValidator->hasViolations()) {
    // Get violations and do something with them
    $violations = $messageValidator->getViolations();
}

// Using the message Validator, you can also validate a Response
// It will find the proper ResponseDefinition from a RequestDefinition
$response = new Response(
    200, 
    ['Content-Type' => 'application/json'],
    '{"id": 1}'
);

$messageValidator->validateResponse($response, $requestDefinition);

// ...


use TwentytwoLabs\ApiValidator\Factory\SwaggerSchemaFactory;

$schema = (new SwaggerSchemaFactory())->createSchema('file://path/to/your/swagger.json');

// Find a request definition from an HTTP method and a path.
$requestDefinition = $schema->getOperationDefinition(
    $schema->getOperationDefinition(method: 'GET', path: '/pets/1234')
);

// Get the response definition for the status code 200 (HTTP OK)
$responseDefinition = $requestDefinition->getResponseDefinition(200);

// From here, you can access the JSON Schema describing the expected response
$responseSchema = $responseDefinition->getBodySchema();