1. Go to this page and download the library: Download duyler/openapi 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/ */
use Duyler\OpenApi\Builder\OpenApiValidatorBuilder;
// From YAML file
$validator = OpenApiValidatorBuilder::create()
->fromYamlFile('openapi.yaml')
->build();
// From JSON file
$validator = OpenApiValidatorBuilder::create()
->fromJsonFile('openapi.json')
->build();
// From YAML string
$yaml = file_get_contents('openapi.yaml');
$validator = OpenApiValidatorBuilder::create()
->fromYamlString($yaml)
->build();
// From JSON string
$json = file_get_contents('openapi.json');
$validator = OpenApiValidatorBuilder::create()
->fromJsonString($json)
->build();
use Nyholm\Psr7\Factory\Psr17Factory;
use Duyler\OpenApi\Builder\OpenApiValidatorBuilder;
$factory = new Psr17Factory();
$request = $factory->createServerRequest('POST', '/users')
->withHeader('Content-Type', 'application/json')
->withBody($factory->createStream('{"name": "John"}'));
$validator = OpenApiValidatorBuilder::create()
->fromYamlFile('openapi.yaml')
->build();
$operation = $validator->validateRequest($request);
// $operation contains the matched path and method
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Duyler\OpenApi\Cache\SchemaCache;
use Duyler\OpenApi\Builder\OpenApiValidatorBuilder;
$cachePool = new FilesystemAdapter();
$schemaCache = new SchemaCache($cachePool, 3600);
$validator = OpenApiValidatorBuilder::create()
->fromYamlFile('openapi.yaml')
->withCache($schemaCache)
->build();
use Duyler\OpenApi\Event\ArrayDispatcher;
use Duyler\OpenApi\Event\ValidationStartedEvent;
use Duyler\OpenApi\Builder\OpenApiValidatorBuilder;
$dispatcher = new ArrayDispatcher([
ValidationStartedEvent::class => [
function (ValidationStartedEvent $event) {
printf("Validating: %s %s\n", $event->method, $event->path);
},
],
]);
use Duyler\OpenApi\Validator\Webhook\WebhookValidator;
use Duyler\OpenApi\Validator\Request\RequestValidator;
$webhookValidator = new WebhookValidator($requestValidator);
$webhookValidator->validate($request, 'payment.webhook', $document);
use Duyler\OpenApi\Validator\Format\FormatValidatorInterface;
use Duyler\OpenApi\Validator\Exception\InvalidFormatException;
// Create a custom validator
class PhoneNumberValidator implements FormatValidatorInterface
{
public function validate(mixed $data): void
{
if (!is_string($data) || !preg_match('/^\+?[1-9]\d{1,14}$/', $data)) {
throw new InvalidFormatException(
'phone',
$data,
'Value must be a valid E.164 phone number'
);
}
}
}
// Register with the builder
$validator = OpenApiValidatorBuilder::create()
->fromYamlFile('openapi.yaml')
->withFormat('string', 'phone', new PhoneNumberValidator())
->build();
use Duyler\OpenApi\Event\ValidationStartedEvent;
use Duyler\OpenApi\Event\ValidationFinishedEvent;
use Duyler\OpenApi\Event\ValidationErrorEvent;
use Duyler\OpenApi\Event\ArrayDispatcher;
$dispatcher = new ArrayDispatcher([
ValidationStartedEvent::class => [
function (ValidationStartedEvent $event) {
error_log(sprintf(
"Validation started: %s %s",
$event->method,
$event->path
));
},
],
ValidationFinishedEvent::class => [
function (ValidationFinishedEvent $event) {
if ($event->success) {
error_log(sprintf(
"Validation completed in %.3f seconds",
$event->duration
));
}
},
],
ValidationErrorEvent::class => [
function (ValidationErrorEvent $event) {
error_log(sprintf(
"Validation failed for %s %s: %s",
$event->method,
$event->path,
$event->exception->getMessage()
));
},
],
]);
$validator = OpenApiValidatorBuilder::create()
->fromYamlFile('openapi.yaml')
->withEventDispatcher($dispatcher)
->build();
use Duyler\OpenApi\Builder\OpenApiValidatorBuilder;
use Duyler\OpenApi\Registry\SchemaRegistry;
// Load multiple versions
$documentV1 = OpenApiValidatorBuilder::create()
->fromYamlFile('api-v1.yaml')
->build()
->document;
$documentV2 = OpenApiValidatorBuilder::create()
->fromYamlFile('api-v2.yaml')
->build()
->document;
// Register schemas
$registry = new SchemaRegistry();
$registry = $registry
->register('api', '1.0.0', $documentV1)
->register('api', '2.0.0', $documentV2);
// Get specific version
$schema = $registry->get('api', '1.0.0');
// Get latest version
$schema = $registry->get('api');
// List all versions
$versions = $registry->getVersions('api');
// ['1.0.0', '2.0.0']
use Duyler\OpenApi\Validator\ValidatorPool;
$pool = new ValidatorPool();
// Validators are automatically reused
$validator = OpenApiValidatorBuilder::create()
->fromYamlFile('openapi.yaml')
->withValidatorPool($pool)
->build();
use Duyler\OpenApi\Compiler\ValidatorCompiler;
use Duyler\OpenApi\Schema\Model\Schema;
$schema = new Schema(
type: 'object',
properties: [
'name' => new Schema(type: 'string'),
'age' => new Schema(type: 'integer'),
],
UserValidator();
$validator->validate(['name' => 'John', 'age' => 30]);
use Duyler\OpenApi\Builder\OpenApiValidatorBuilder;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Duyler\OpenApi\Cache\SchemaCache;
use Duyler\OpenApi\Validator\Error\Formatter\DetailedFormatter;
$cachePool = new FilesystemAdapter();
$schemaCache = new SchemaCache($cachePool, 3600);
$validator = OpenApiValidatorBuilder::create()
->fromYamlFile('openapi.yaml')
->withCache($schemaCache) // Cache parsed specs
->withErrorFormatter(new DetailedFormatter()) // Detailed errors
->enableCoercion() // Auto type conversion
->build();
// Without delimiters (recommended)
new Schema(pattern: '^test$')
// With delimiters
new Schema(pattern: '/^test$/')
// This will throw InvalidPatternException:
// Invalid regex pattern "/[invalid/": preg_match(): No ending matching delimiter ']' found
new Schema(pattern: '[invalid')
use Duyler\OpenApi\Validator\Exception\ValidationException;
try {
$operation = $validator->validateRequest($request);
} catch (ValidationException $e) {
// Get array of validation errors
$errors = $e->getErrors();
foreach ($errors as $error) {
printf(
"Path: %s\nMessage: %s\nType: %s\n\n",
$error->dataPath(),
$error->getMessage(),
$error->getType()
);
}
// Get formatted errors
$formatted = $validator->getFormattedErrors($e);
echo $formatted;
}
// Simple formatter (default)
use Duyler\OpenApi\Validator\Error\Formatter\SimpleFormatter;
// Detailed formatter with suggestions
use Duyler\OpenApi\Validator\Error\Formatter\DetailedFormatter;
// JSON formatter for API responses
use Duyler\OpenApi\Validator\Error\Formatter\JsonFormatter;
$customEmailValidator = new class implements FormatValidatorInterface {
public function validate(mixed $data): void
{
// Custom email validation logic
if (!filter_var($data, FILTER_VALIDATE_EMAIL)) {
throw new InvalidFormatException('email', $data, 'Invalid email');
}
}
};
$validator = OpenApiValidatorBuilder::create()
->fromYamlFile('openapi.yaml')
->withFormat('string', 'email', $customEmailValidator)
->build();