Repo of the Day
cebe/php-openapi
Published: Oct 11, 2024
Open repository ↗Read and write OpenAPI yaml/json files and make the content accessible in PHP objects.
Summary
cebe/php-openapi is a PHP library for reading and writing OpenAPI 3.0.x specification files in JSON or YAML and exposing their content as PHP objects. It also ships a command-line tool for validating and converting OpenAPI 3.0.x description files. The project is published under the MIT license and requires PHP 7.1 or higher.
What it is useful for
The library is described by its author as a "low level API for reading and writing OpenAPI files" that higher-level tools build on. Concrete use cases include:
- Loading an existing
openapi.jsonoropenapi.yamlinto a PHP application so paths, operations, components, and schemas can be inspected in code. - Programmatically constructing or modifying a spec (for example, adding a new
PathItem) and serializing it back to JSON or YAML. - Validating a spec on the command line or converting between JSON and YAML.
- Resolving
$refpointers either fully (RESOLVE_MODE_ALL) or only those pointing to external files (RESOLVE_MODE_INLINE, exposed as theinlineCLI command). - Serving as the foundation for code generators and request/response validators; the README lists projects such as
cebe/yii2-openapi,league/openapi-psr7-validator, andhotmeteor/spectatorthat depend on it.
How engineers can use it
The documented setup is a single Composer command:
composer require cebe/php-openapi
Reading a spec into PHP objects mirrors the OpenAPI structure, for example:
use cebe\openapi\Reader;
$openapi = Reader::readFromYamlFile(realpath('openapi.yaml'));
echo $openapi->info->title;
foreach ($openapi->paths as $path => $definition) {
// iterate path definitions
}
$foo = $openapi->components->schemas['Foo'];
Writing a spec works by instantiating cebe\openapi\spec\OpenApi (and other spec classes such as Info and PathItem) and passing them to cebe\openapi\Writer::writeToJson or writeToYaml. External $ref resolution requires a base URL or filesystem path so relative references can be resolved, and is controlled through ReferenceContext.
The CLI is invoked as vendor/bin/php-openapi and supports validate, convert, and inline subcommands, with --read-json/--read-yaml and --write-json/--write-yaml flags to force formats. validate exits with code 2 on validation errors, 1 on other errors, and 0 on success.
Documented limitations to keep in mind: only OpenAPI 3.0.x is supported, library-level validate() is explicitly described as "very basic" and "not complete" (full schema validation is only available via the CLI), Schema Object validation is not implemented, and Link Object Runtime Expressions are listed as missing. The repository is also marked as work in progress, so consumers should review the completeness checklist in the README.