wakeonweb/swagger 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

wakeonweb/swagger

Composer 安装命令:

composer require wakeonweb/swagger

包简介

README 文档

README

The WakeOnWeb Swagger Validation Component is an extensible component for validating API data using the Swagger - OpenAPI specification. The component supports both YAML and JSON Open API file formats. The component has very a small dependency set in order to be usable in different PHP frameworks.

The component uses:

  • PSR-6: For caching your OpenApi specification files
  • PSR-7: For processing HTTP messages (requests and responses)

Installation

The component can easily be installed using

composer require wakeonweb/swagger

The component uses a JSON Schema validator, by default, the justinrainbow/json-schema is in the dev dependencies. If you intend to use the component in production you need to execute:

composer require justinrainbow/json-schema

Loading an OpenAPI specification file

The component supports both YAML and JSON OpenAPI format. Swagger files are loaded by the SwaggerFactory. The factory accepts a PSR-6 CacheItemPoolInterface. If none provided it will use the ArrayCachePool provided by cache/array-adapter.

$factory = new SwaggerFactory();

// Register a YAML loader to load YAML Swagger files.
$factory->addLoader(new YamlLoader());

// Load the Swagger definition.
$swagger = $factory->buildFrom('/path/to/swagger/file.yml');

Executing this code will result in retrieving a tree representation of the specification into an instance of a Swagger document. At the moment, the cache contains the instance of the Swagger document.

Creating the a content validator

Content validation in the component is based on JSON Schema Validation. The OpenAPI Specification handles much more than this. For example it allows to define query string parameters or the format of any HTTP Headers. The component supports all kind of validation.

Content validators are used to validate the content of a request or a response. Any content validator must implement the ContentValidatorInterface and should be registered into an instance of a ContentValidator. The resulting instance can be used into an instance of a SwaggerValidator.

// Create a content validator that validates requests and responses bodies.
$contentValidator = new ContentValidator();

// Register a specific content validator that handle "application/json".
$contentValidator->registerContentValidator(new JustinRainbowJsonSchemaValidator());

Validating a response

Validating response makes sense only for testing... As you are supposed to have valid code respectful of your interface agreements in production!

// Create the validator and register the content validator.
$validator = new SwaggerValidator($swagger);
$validator->registerResponseValidator($contentValidator);

// Sample with Symfony Response....
$response = new Response(...);

$psr7Factory = new DiactorosFactory();

// Converts the response to a PSR-7 compliant format.
$response = $psr7Factory->createResponse($response);

try {
    // Validates the response against the required specification.
    $validator->validateResponseFor($response, PathItem::METHOD_GET, '/api/resource', 200);
} catch (SwaggerValidatorException $e) {
    // display $e message.
}

Validating a request

Validating response makes sense only for testing... As you are supposed to have valid code respectful of your interface agreements in production!

// Create the validator and register the content validator.
$validator = new SwaggerValidator($swagger);
$validator->registerRequestValidator($contentValidator);

// Sample with Symfony Response....
$request = new Request(...);

$psr7Factory = new DiactorosFactory();

// Converts the response to a PRS-7 compliant format.
$request = $psr7Factory->createRequest($request);

try {
    // Validates the request against the required specification.
    $validator->validateRequestFor($request, PathItem::METHOD_GET, '/api/resource');
} catch (SwaggerValidatorException $e) {
    // display $e message.
}

Complete sample

The following sample code demonstrates a complete usage of the component.

<?php

use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
use Symfony\Component\HttpFoundation\Response;
use WakeOnWeb\Component\Swagger\Specification\PathItem;
use WakeOnWeb\Component\Swagger\SwaggerFactory;
use WakeOnWeb\Component\Swagger\Loader\YamlLoader;
use WakeOnWeb\Component\Swagger\Loader\JsonLoader;
use WakeOnWeb\Component\Swagger\Test\ContentValidator;
use WakeOnWeb\Component\Swagger\Test\Exception\SwaggerValidatorException;
use WakeOnWeb\Component\Swagger\Test\JustinRainbowJsonSchemaValidator;
use WakeOnWeb\Component\Swagger\Test\SwaggerValidator;

$factory = new SwaggerFactory();

// Register a YAML loader to load YAML Swagger files.
$factory->addLoader(new YamlLoader());

// Load the Swagger definition.
$swagger = $factory->buildFrom('/path/to/swagger/file.yml');

// Create a content validator that validates requests and responses bodies.
$contentValidator = new ContentValidator();

// Register a specific content validator that handle "application/json".
$contentValidator->registerContentValidator(new JustinRainbowJsonSchemaValidator());

// Create the validator and register the content validator.
$validator = new SwaggerValidator($swagger);
$validator->registerResponseValidator($contentValidator);

$response = new Response(
    '{...}',
    200,
    [
        'Content-Type' => 'application/json',
    ]
);

$psr7Factory = new DiactorosFactory();

// Converts the response to a PRS-7 compliant format.
$response = $psr7Factory->createResponse($response);

try {
    // Validates the response against the required specification.
    $validator->validateResponseFor($response, PathItem::METHOD_GET, '/api/resource', 200);
} catch (SwaggerValidatorException $e) {
    // display $e message.
}

wakeonweb/swagger 适用场景与选型建议

wakeonweb/swagger 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 230.58k 次下载、GitHub Stars 达 49, 最近一次更新时间为 2017 年 05 月 13 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 wakeonweb/swagger 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

  • Stars: 49
  • Watchers: 7
  • Forks: 10
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-05-13