定制 mmal/openapi-validator 二次开发

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

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

mmal/openapi-validator

Composer 安装命令:

composer require mmal/openapi-validator

包简介

Validates data against provide openapi spec

README 文档

README

This project is abandoned. Reasons: 1. there are more mature and better developed libraries similar to this one 2. I don't have time anymore to maintain this. If You believe that this project should be still expanded then feel free to fork.

What is this?

Validate data against openapi v3 spec

Features

  1. Checks for required fields
  2. Checks types
  3. Supports nested structures
  4. Supports discriminator
  5. Supports allOf, anyOf
  6. Supports nullable
  7. Resolves local references (components)

Unlike Dredd it does not require examples and does not check that data matches examples

Installation

composer req --dev mmal/openapi-validator

Requirements

Your openapi spec has to be valid, You can use Speccy to check Your schema first

This library assumes that each operation has operationId

Examples

Given we have api described by following OpenAPI specification

openapi: 3.0.2
info:
  title: Cards
  description: Cards and decks api
  contact:
    name: Mieszko Malawski
  license:
    name: GNU AGPLv3
    url: https://www.gnu.org/licenses/agpl.txt
  version: 1.0.0
tags:
  -
    name: Cards
paths:
  /cards:
    summary: Path used to manage the list of cards.
    description: The REST endpoint/path used to list and create zero or more card entities.  This path contains a GET and POST operation to perform the list and create tasks, respectively.
    get:
      tags:
        - Cards
      summary: List All cards
      description: Gets a list of all card entities.
      operationId: getcards
      responses:
        200:
          description: Successful response - returns an array of card entities.
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/card'
components:
  schemas:
    card:
      title: Root Type for card
      description: The root of the card type's schema.
      required:
      - id
      - name
      - power
      type: object
      properties:
        id:
          description: "unique id"
          type: string
          format: int64
          readOnly: true
        name:
          type: string
        power:
          description: "how powerfull card is on the board"
          format: int32
          type: integer
      example:
        id: "23423423"
        name: "Geralt"
        power: 10
        

We have server implementation (this is of course example - normally You would fetch data from some storage)

<?php
declare(strict_types=1);


namespace AppBundle\Controller;


use GOG\Common\OAuthSecurityBundle\Controller\OAuthController;
use Symfony\Component\HttpFoundation\JsonResponse;

class CardsController extends OAuthController
{
    public function getCardsAction()
    {
        return new JsonResponse(
            [
                [
                    'id' => '123123',
                    'name' => 'Geralt',
                    'power' => 10,
                ],
                [
                    'id' => '45653',
                    'name' => 'Vernon Roche',
                    'power' => 10,
                ]
            ]
        );
    }
}


How to verify that server implementation works as described? Use openapi-validator with any http client:

<?php
declare(strict_types=1);


namespace AppBundle\Tests\Controller;


use Mmal\OpenapiValidator\Validator;
use Symfony\Component\Yaml\Yaml;

class CardsControllerTest extends BaseControllerTest
{
    const SPEC_PATH = __DIR__.'/../../../../docs/api.yml';
    
    /** @var Validator */
    static $openaApiValidator;

    static public function setUpBeforeClass()
    {
        parent::setUpBeforeClass();
        self::$openaApiValidator = new Validator(Yaml::parse(self::SPEC_PATH));
    }

    public function testGetCards()
    {
        $this->makeRequest('GET', '/cards');
    }

    protected function makeRequest($method, $uri, $content = '')
    {
        $client = $this->getTestClient();
        $client->request(
            $method,
            $uri
        );
        $response = $client->getResponse();

        $result = self::$openaApiValidator->validateBasedOnRequest(
            $uri,
            $method,
            $response->getStatusCode(),
            json_decode($response->getContent(), true)
        );
        self::assertFalse($result->hasErrors(), $result);

        return RESTResponse::fromHTTPResponse($response);
    }
}


  1. Load Your spec to validator
  2. Make request with any http client
  3. Pass request uri, request method, response code and response body to validator (and optionally media type, default is application/json)
  4. Validator will find figure out that for method 'GET', path '/cards' and response code 200, required response schema is:
card:
  title: Root Type for card
  description: The root of the card type's schema.
  required:
  - id
  - name
  - power
  type: object
  properties:
	id:
	  description: "unique id"
	  type: string
	  format: int64
	  readOnly: true
	name:
	  type: string
	power:
	  description: "how powerfull card is on the board"
	  format: int32
	  type: integer
  example:
	id: "23423423"
	name: "Geralt"
	power: 10



  1. Actual response body is validated against that schema
  2. Result object is produced, if response is invalid then result object will contain errors

In this case response is valid:

image info

Lets now introduce some errors:

 public function getCardsAction()
    {
        return new JsonResponse(
            [
                [
                    'id' => '123123',
                    'name' => 'Geralt',
                    'power' => 10,
                ],
                [
                 //   'id' => '45653',
                    'name' => 'Vernon Roche',
                    'power' => 10,
                ]
            ]
        );
    }
    

Required id field for second item is missing:

image info

Lets break something else

public function getCardsAction()
    {
        return new JsonResponse(
            [
                [
                    'id' => '123123',
                    'name' => 'Geralt',
                    'power' => 10,
                ],
                [
                    'id' => '45653',
                    'name' => 'Vernon Roche',
                    'power' => '10',
                ]
            ]
        );
    }
    

power field should be integer (second item):

image info

Other libraries

  1. Dredd - currently supports only swagger/openapi v2, support for v3 is not yet there
  2. Swagger - support for v2 only

TODO

  1. Support all openapi formats
  2. Support for not keyword

How this works?

Transform openapi spec into json schema and then uses justinrainbow/json-schema to validate it

mmal/openapi-validator 适用场景与选型建议

mmal/openapi-validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 660.01k 次下载、GitHub Stars 达 14, 最近一次更新时间为 2018 年 12 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「swagger」 「openapi」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 660.01k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 14
  • 点击次数: 25
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 14
  • Watchers: 0
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: proprietary
  • 更新时间: 2018-12-10