Versions and output

Writing a document

Write any object as JSON, YAML or a PHP array, and save it to a file.

Every object, from the whole OpenApi document to a single Schema, has three methods that write it for a version.

JSON, YAML or array

use Ark4ne\OpenApiWriter\Enums\Version;

$json = $document->toJson(Version::V3_1_2, JSON_PRETTY_PRINT);
$yaml = $document->toYaml(Version::V3_1_2);     // needs symfony/yaml
$array = $document->toArray(Version::V3_1_2);
MethodReturns
toJson($version = null, int $flags = 0, $extensions = None)A JSON string; the flags are those of json_encode()
toYaml($version = null, $extensions = None)A YAML string; needs symfony/yaml
toArray($version = null, $extensions = None)A PHP array; empty objects are \stdClass, so they stay {} in JSON

The version is a Version case or its string: toJson('3.0.4'). Without one, the version given to OpenApi::openapi() is used, else 3.1.2. $extensions turns on the Redoc extensions.

toYaml()
$document->toYaml(Version::V3_1_2);
openapi.yaml
openapi: 3.1.2
info:
  title: 'Books API'
  version: 1.0.0
paths:
  '/books/{id}':
    get:
      operationId: books.show
      responses:
        '200':
          description: OK

Writing any object

Writing is not limited to the document: a schema, a response or a parameter can be written alone, which helps to inspect a piece or to test it.

use Ark4ne\OpenApiWriter\Objects\Schema;

$subtitle = Schema::string()->nullable();

$subtitle->toJson('3.1.2');  // {"type":["string","null"]}
$subtitle->toJson('3.0.4');  // {"type":"string","nullable":true}

OpenApi also implements JsonSerializable: json_encode($document) writes it for its declared version.

Saving files

$directory = __DIR__ . '/public';

file_put_contents(
    $directory . '/openapi.json',
    $document->toJson(Version::V3_1_2, JSON_PRETTY_PRINT) . "\n",
);
file_put_contents(
    $directory . '/openapi.yaml',
    $document->toYaml(Version::V3_1_2),
);
file_put_contents(
    $directory . '/openapi-3.0.json',
    $document->toJson(Version::V3_0_4, JSON_PRETTY_PRINT) . "\n",
);

The library writes strings; where they go (a file, an HTTP response, a build artifact) is up to you. Point Swagger UI, Redoc, Scalar or any other viewer to the result.

Key order

The keys are written in the order of the specification, whatever the order of the calls: openapi, info, servers, paths… at the root; type, required, properties… in a schema. Two builds of the same document give the same output, which keeps the diffs of a committed file small.

The serializer

toJson() and its siblings are shortcuts for the Serializer, which also returns the diagnostics:

use Ark4ne\OpenApiWriter\Enums\Strictness;
use Ark4ne\OpenApiWriter\Serialization\Serializer;

$result = Serializer::for(Version::V3_0_4, Strictness::Lenient)
    ->serialize($document);

$json = $result->toJson(JSON_PRETTY_PRINT);
$yaml = $result->toYaml();
$array = $result->toArray();
$diagnostics = $result->diagnostics();