PHP code example of selency / openapi

1. Go to this page and download the library: Download selency/openapi 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/ */

    

selency / openapi example snippets


// openapi/Documentation.php

use Selency\OpenApi\Documentation\AbstractDocumentation;

class Documentation extends AbstractDocumentation
{
    public function getIdentifier(): string
    {
        return 'myapi';
    }

    public function getVersion(): string
    {
        return '1.3.4';
    }

    public function configure(DocumentationConfigurator $doc): void
    {
        $doc->info($this->openApi->info()
            ->title('Monolith API')
            ->description(file_get_contents(__DIR__.'/Resources/info_description.md'))
            ->contact(name: 'API support', url: 'https://symfony.com', email: '[email protected]')
            ->specificationExtension('x-logo', [
                'url' => 'https://symfony.com/logos/symfony_black_02.png',
                'altText' => 'Symfony logo',
            ])
            ->license('MIT')
        );

        $doc->externalDocs(url: 'https://github.com/symfony/openapi', description: 'OpenApi component');

        $doc->server($this->openApi->server('https://api.symfony.local')->description('Local'))
            ->server($this->openApi->server('https://api.symfony-staging.com')->description('Staging'))
            ->server($this->openApi->server('https://api.symfony.com')->description('Prod'));

        $doc->securityRequirement(self::REF_SECURITY_USER_JWT);

        $doc->path('/health', $this->openApi->pathItem()
            ->get($this->openApi->operation()
                ->tag('Health')
                ->operationId('app.health.check')
                ->summary('Health check')
                ->description('Check the API is up and available.')
                ->securityRequirement(null)
                ->responses($this->openApi->responses()
                    ->response('200', $this->openApi->response()
                        ->description('When the API is up and available.')
                        ->content('application/json', $this->openApi->schema()
                            ->property('name', $this->openApi->schema()->type('string')->description('Name for this API')->example('Selency API'))
                            ->property('env', $this->openApi->schema()->type('string')->description('Current environment of this instance of the API')->example('prod'))
                        )
                    )
                    ->response('500', $this->openApi->response()->description('When the API is unavailable due to a backend problem.'))
                )
            )
        );

        // ...
    }
}

// Build a read-only model representing the documentation
$compiler = new DocumentationCompiler();
$openApiDefinition = $compiler->compile($doc);

// Compile it as YAML or JSON for usage in other tools
$openApiYaml = (new Dumper\YamlDumper())->dump($openApiDefinition);
$openApiJson = (new Dumper\JsonDumper())->dump($openApiDefinition);

// HealthDocumentation.php
use Selency\OpenApi\Documentation\PartialDocumentationInterface;

#[AutoconfigureTag('app.partial_documentation')]
class HealthDocumentation implements PartialDocumentationInterface
{
    public function __construct(private OpenApiBuilderInterface $openApi)
    {
    }

    public function configure(DocumentationConfigurator $doc): void
    {
        $doc->path('/health', $this->openApi->pathItem()
            ->get($this->openApi->operation()
                ->tag('Health')
                ->operationId('app.health.check')
                ->summary('Health check')
                ->description('Check the API is up and available. Mostly used by the infrastructure to check for readiness.')
                ->securityRequirement(null)
                ->responses($this->openApi->responses()
                    ->response('200', $this->openApi->response()
                        ->description('When the API is up and available.')
                        ->content('application/json', $this->openApi->schema()
                            ->property('name', $this->openApi->schema()->type('string')->description('Name for this API')->example('Selency API'))
                            ->property('env', $this->openApi->schema()->type('string')->description('Current environment of this instance of the API')->example('prod'))
                        )
                    )
                    ->response('500', $this->openApi->response()->description('When the API is unavailable due to a backend problem.'))
                )
            )
        );
    }
}


// Documentation.php
class Documentation extends AbstractDocumentation
{
    private iterable $partialsDocs;

    public function __construct(
        private Builder\OpenApiBuilder $openApi,
        #[TaggedIterator(tag: 'app.partial_documentation')] iterable $partialsDocs,
    ) {
        $this->partialsDocs = $partialsDocs;
    }

    public function getIdentifier(): string
    {
        return 'myapi';
    }

    public function getVersion(): string
    {
        return '1.3.4';
    }

    public function configure(DocumentationConfigurator $doc): void
    {
        $doc->info($this->openApi->info()
            ->title('Monolith API')
            ->description(file_get_contents(__DIR__.'/Resources/info_description.md'))
            ->contact(name: 'API support', url: 'https://symfony.com', email: '[email protected]')
            ->specificationExtension('x-logo', [
                'url' => 'https://symfony.com/logos/symfony_black_02.png',
                'altText' => 'Symfony logo',
            ])
            ->license('MIT')
        );

        // ...

        // Apply partial documentations
        foreach ($this->partialsDocs as $partialsDoc) {
            $partialsDoc->configure($doc);
        }
    }
}

class AuthRegisterPayload implements SelfDescribingSchemaInterface
{
    #[Assert\Email(mode: Email::VALIDATION_MODE_STRICT)]
    #[Assert\NotBlank]
    public $email;

    #[Assert\Type(type: 'string')]
    #[Assert\NotBlank]
    public $firstName;

    #[Assert\Type(type: 'string')]
    #[Assert\NotBlank]
    public $lastName;

    #[Assert\Type(type: 'string')]
    #[Assert\NotBlank]
    public $password;

    public static function describeSchema(SchemaConfigurator $schema, OpenApiBuilderInterface $openApi): void
    {
        $schema
            ->title('AuthRegister')
            ->sword', $openApi->schema()
                ->type('string')
                ->description('User\'s plaintext password')
            )
        ;
    }
}

// Build a read-only model representing the documentation
$compiler = new DocumentationCompiler([
    new Selency\OpenApi\Loader\SelfDescribingSchemaLoader([
        AuthRegisterPayload::class,
    ])
]);

$openApiDefinition = $compiler->compile($doc);

class Documentation extends AbstractDocumentation
{
    // ...

    public function configure(DocumentationConfigurator $doc): void
    {
        // ...

        $doc->path('/auth/register', $this->openApi->pathItem()
            ->post($this->openApi->operation()
                ->tag('Auth')
                ->operationId('app.auth.register')
                ->summary('Auth registration')
                ->description('Register as a user.')
                ->securityRequirement(null)
                ->requestBody($this->openApi->requestBody()
                    ->content('application/json', AuthRegisterPayload::class)
                )
                ->responses($this->openApi->responses()
                    ->response('200', $this->openApi->response()
                        ->content('application/json', AuthRegisterOutput::class)
                    )
                )
            )
        );

        // ...
    }
}