定制 twentytwo-labs/api-validator 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

twentytwo-labs/api-validator

Composer 安装命令:

composer require twentytwo-labs/api-validator

包简介

Validate PSR-7 Requests against an OpenAPI/Swagger2 Schema

README 文档

README

Build Status Code Coverage Scrutinizer Quality Score

This library provides a set of classes suited to describe a WebService based on the HTTP protocol.

It can validate PSR-7 Requests against a schema.

It's design is heavily inspired by the OpenAPI/Swagger2.0 specifications.

As of now, it only support the OpenAPi/Swagger2.0 specifications but we plan to support RAML 1.0 and API Elements (API Blueprint) in the future.

Dependencies

We rely on the justinrainbow/json-schema library to parse specification files and to validate requests and responses:

  • Request's headers, query, uri and body parts.
  • Response headers and body parts.

Usage

Before you start

You will need to write a valid Swagger 2.0 file in order to use this library. Ensure that this file is valid using the Swagger Editor.

You can also validate your specifications using the Swagger 2.0 JSONSchema.

Validate a request

You can validate any PSR-7:

  • Request implementing the Psr\Http\Message\RequestInterface interface.
  • Response implementing the Psr\Http\Message\ResponseInterface interface.
<?php

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);

// ...

Working with Symfony HTTPFoundation Requests

You will need an adapter in order to validate symfony requests.

We recommend you to use the symfony/psr-http-message-bridge

Using the schema

You can navigate the TwentytwoLabs\ApiValidator\Schema to meet other use cases.

Example:

<?php
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();

twentytwo-labs/api-validator 适用场景与选型建议

twentytwo-labs/api-validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 50.04k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 05 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 twentytwo-labs/api-validator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 twentytwo-labs/api-validator 我们能提供哪些服务?
定制开发 / 二次开发

基于 twentytwo-labs/api-validator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 50.04k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 18
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: Unknown
  • 更新时间: 2022-05-16