Serialize an object directly from swagger-php attributes.
composer require mattyrad/openapi-serializeuseOpenApi\AttributesasOpenApi;
$sample = newclass() {
publicfunction__construct(
#[OpenApi\Property]
publicreadonlyint$two_plus_two = 4,
) {}
#[OpenApi\Property(property: 'greeting')]
publicfunctiongetGreeting(): string
{
return'hello world';
}
};
$serialized = MattyRad\OpenApi\Serializer::serialize($sample);
assert($serialized == ['two_plus_two' => 4, 'greeting' => 'hello world']);This means that if you document all of your response data using swagger-php attributes, your API documentation will necessarily match the response format.
The need for tests to verify that a response matches OpenApi schema mostly becomes a formality- or altogether unnecessary.
useMattyRad\OpenApi\Serializer;
useOpenApi\AttributesasOpenApi;
abstractclass HttpResource implements \JsonSerializable
{
finalpublicfunctionjsonSerialize(): array|string
{
return Serializer::serialize($this);
}
}
finalclass Greeting extends HttpResource
{
publicfunction__construct(
#[OpenApi\Property]
publicreadonlystring$hello = 'world',
) {}
}
// return new JsonResponse(new Greeting)Or a trait if you don't want to lock in to abstractions.
useMattyRad\OpenApi;
trait SerializesFromOpenApi
{
finalpublicfunctionjsonSerialize(): array|string
{
return Serializer::serialize($this);
}
}
finalclass Greeting implements \JsonSerializable
{
use SerializesFromOpenApi;
publicfunction__construct(
#[OpenApi\Property]
publicreadonlystring$hello = 'world',
) {}
}
// return new JsonResponse(new Greeting)