PHP code example of mattyrad / openapi-serialize

1. Go to this page and download the library: Download mattyrad/openapi-serialize library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mattyrad / openapi-serialize example snippets


composer 

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

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)

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)