Skip to content

Latest commit

 

History

History
80 lines (56 loc) · 2.32 KB

File metadata and controls

80 lines (56 loc) · 2.32 KB

Using the Builder

Introduction

The Builder class is the recommended entry point for generating OpenAPI documents from PHP code. It provides a clean, fluent API and returns a Result object with access to the generated spec, scanned files, and validation diagnostics.

Basic usage

$result = (new \OpenApi\Builder())
    ->addSource('src/Controllers')
    ->addSource('src/Models')
    ->build();

echo $result->toYaml();

API

Sources

// Add sources one at a time
$builder->addSource('src/Controllers');
$builder->addSource(new \OpenApi\Utils\SourceFinder('src/', ['tests']));

// Or set all at once
$builder->setSources(['src/Controllers', 'src/Models']);

Sources can be directory paths, file paths, \SplFileInfo, \Symfony\Component\Finder\Finder instances, or nested iterables of these.

Version

$builder->setVersion('3.1.0');

Sets the target OpenAPI version. If not set, defaults to the version declared in your #[OA\OpenApi] attribute.

Logger

$builder->setLogger($psrLogger);

Accepts any PSR-3 logger. Defaults to NullLogger (silent). The CLI command sets its own console logger.

Generator configuration

For advanced Generator configuration (custom analysers, processors, aliases, type resolvers), use withGenerator():

$builder->withGenerator(function (\OpenApi\Generator $generator) {
    $generator->setAnalyser($customAnalyser);
    $generator->setConfig(['operationId.hash' => false]);
    $generator->withProcessorPipeline(function ($pipeline) {
        $pipeline->remove(\OpenApi\Processors\CleanUnusedComponents::class);
    });
});

The callable receives a pre-configured Generator instance and may either modify it in-place or return a new instance.

Result

The build() method returns a \OpenApi\Builder\Result instance:

$result = $builder->build();

$result->isValid();     // bool — true if a spec was generated
$result->toArray();     // array — the spec as a PHP array
$result->toJson();      // string — JSON output
$result->toYaml();      // string — YAML output
$result->files();       // string[] — scanned source files
$result->log();         // array — all log entries [{level, message}, ...]
$result->warnings();    // string[] — warning messages
$result->errors();      // string[] — error messages