mattyrad/openapi-serialize

直接从 Swagger-PHP 属性序列化对象

1.0.0 2023-12-07 23:23 UTC

This package is auto-updated.

Last update: 2024-09-11 22:26:29 UTC


README

直接从 swagger-php 属性序列化对象。

composer require mattyrad/openapi-serialize
use OpenApi\Attributes as OpenApi;

$sample = new class() {
    public function __construct(
        #[OpenApi\Property]
        public readonly int $two_plus_two = 4,
    ) {}

    #[OpenApi\Property(property: 'greeting')]
    public function getGreeting(): string
    {
        return 'hello world';
    }
};

$serialized = MattyRad\OpenApi\Serializer::serialize($sample);

assert($serialized == ['two_plus_two' => 4, 'greeting' => 'hello world']);

这意味着如果您使用 swagger-php 属性文档化所有的响应数据,您的 API 文档将必然匹配响应格式。

验证响应是否匹配 OpenApi 模式测试的需要大多成为形式性的,或者完全不必要的。

示例

use MattyRad\OpenApi\Serializer;
use OpenApi\Attributes as OpenApi;

abstract class HttpResource implements \JsonSerializable
{
    final public function jsonSerialize(): array|string
    {
        return Serializer::serialize($this);
    }
}

final class Greeting extends HttpResource
{
    public function __construct(
        #[OpenApi\Property]
        public readonly string $hello = 'world',
    ) {}
}

// return new JsonResponse(new Greeting)

或者如果您不想锁定在抽象中,可以使用 trait。

use MattyRad\OpenApi;

trait SerializesFromOpenApi
{
    final public function jsonSerialize(): array|string
    {
        return Serializer::serialize($this);
    }
}

final class Greeting implements \JsonSerializable
{
    use SerializesFromOpenApi;

    public function __construct(
        #[OpenApi\Property]
        public readonly string $hello = 'world',
    ) {}
}

// return new JsonResponse(new Greeting)