### Install php-openapi using Composer Source: https://github.com/cebe/php-openapi/blob/master/README.md This command installs the php-openapi library using Composer, the dependency manager for PHP. Ensure you have Composer installed and configured in your project. ```bash composer require cebe/php-openapi ``` -------------------------------- ### Display Help for php-openapi CLI Tool Source: https://github.com/cebe/php-openapi/blob/master/README.md View the usage information and available commands for the php-openapi CLI tool. This command lists all possible operations and their options. ```bash vendor/bin/php-openapi help ``` -------------------------------- ### Write OpenAPI Description using Prepared Objects Source: https://github.com/cebe/php-openapi/blob/master/README.md An alternative method for writing OpenAPI descriptions where component objects like `Info` and `PathItem` are passed directly to the `OpenApi` constructor. This offers a more object-oriented approach to building the API description. ```php use cebe\openapi\spec\OpenApi; use cebe\openapi\spec\PathItem; use cebe\openapi\spec\Info; // create base API Description $openapi = new OpenApi([ 'openapi' => '3.0.2', 'info' => new Info([ 'title' => 'Test API', 'version' => '1.0.0', ]), 'paths' => [ '/test' => new PathItem([ 'description' => 'something' ]), ], ]); $json = \cebe\openapi\Writer::writeToJson($openapi); ``` -------------------------------- ### Convert OpenAPI 3.0.x File Format using CLI Source: https://github.com/cebe/php-openapi/blob/master/README.md Convert OpenAPI Description files between JSON and YAML formats using the CLI tool. Input and output can be specified as files or STDOUT/STDIN. Reference resolution can be controlled. ```bash vendor/bin/php-openapi convert input.yml output.json ``` ```bash cat input.json | vendor/bin/php-openapi convert --write-yaml > output.yml ``` ```bash vendor/bin/php-openapi convert input.yml --resolve-none output.yml ``` -------------------------------- ### Write OpenAPI with Object Instances (PHP) Source: https://context7.com/cebe/php-openapi/llms.txt This snippet shows how to create OpenAPI specifications using typed object instances, which enhances IDE support. It involves creating instances of classes like OpenApi, Info, PathItem, Operation, and Response. The output can be written to YAML strings or files using the Writer class. ```php '3.0.0', 'info' => new Info([ 'title' => 'Test API', 'version' => '1.0.0', ]), 'paths' => [ '/test' => new PathItem([ 'description' => 'Test endpoint', 'get' => new Operation([ 'summary' => 'Get test data', 'responses' => new Responses([ '200' => new Response([ 'description' => 'Success' ]) ]) ]) ]), ], ]); // Write to YAML string $yaml = Writer::writeToYaml($openapi); echo $yaml; // Write to YAML file Writer::writeToYamlFile($openapi, '/path/to/output.yaml'); ``` -------------------------------- ### Accessing Path Operations and Parameters in PHP Source: https://context7.com/cebe/php-openapi/llms.txt Navigates and extracts information from API paths, operations, and parameters. It allows iteration over all paths, retrieval of path-level parameters, and access to details of each operation including summary, description, operation ID, parameters, request body, and responses. ```php paths as $path => $pathItem) { echo "=== Path: $path ===\n"; // Get path-level parameters if (isset($pathItem->parameters)) { foreach ($pathItem->parameters as $param) { echo "Path parameter: {$param->name} ({$param->in})\n"; } } // Get all operations (GET, POST, PUT, DELETE, etc.) $operations = $pathItem->getOperations(); foreach ($operations as $method => $operation) { echo "\n$method Operation:\n"; echo " Summary: {$operation->summary}\n"; echo " Description: {$operation->description}\n"; echo " OperationId: {$operation->operationId}\n"; // Operation parameters if (isset($operation->parameters)) { foreach ($operation->parameters as $param) { echo " Parameter: {$param->name} in {$param->in}"; echo $param->required ? " (required)" : " (optional)"; echo "\n"; } } // Request body if (isset($operation->requestBody)) { echo " Request body required: "; echo $operation->requestBody->required ? "yes" : "no"; echo "\n"; } // Responses foreach ($operation->responses as $statusCode => $response) { echo " Response $statusCode: {$response->description}\n"; } } } ``` -------------------------------- ### CLI Tool - Convert Command (Bash) Source: https://context7.com/cebe/php-openapi/llms.txt This section outlines the 'convert' command of the php-openapi CLI tool, used for transforming OpenAPI files between YAML and JSON formats. It supports converting to files or standard output, reading from standard input, forcing input/output formats, and controlling reference resolution modes (none, external, all). The 'inline' command is a shortcut for resolving external references. ```bash # Convert YAML to JSON vendor/bin/php-openapi convert openapi.yaml openapi.json # Convert JSON to YAML vendor/bin/php-openapi convert openapi.json openapi.yaml # Convert with output to STDOUT vendor/bin/php-openapi convert openapi.yaml --write-json > output.json vendor/bin/php-openapi convert openapi.json --write-yaml > output.yaml # Convert from STDIN cat openapi.yaml | vendor/bin/php-openapi convert --read-yaml --write-json > output.json # Force input/output formats vendor/bin/php-openapi convert --read-yaml --write-json input.txt output.txt # Reference resolution modes vendor/bin/php-openapi convert --resolve-none openapi.yaml output.yaml vendor/bin/php-openapi convert --resolve-external openapi.yaml output.yaml vendor/bin/php-openapi convert --resolve-all openapi.yaml output.yaml # Inline external references (shortcut for --resolve-external) vendor/bin/php-openapi inline openapi.yaml single-file.yaml ``` -------------------------------- ### Access OpenAPI Schema Components and Properties - PHP Source: https://context7.com/cebe/php-openapi/llms.txt Illustrates how to access reusable components and schema definitions within an OpenAPI specification. This includes retrieving schema descriptions, types, and iterating through defined properties. ```php components->schemas['Foo']; echo $fooSchema->description; // "This is a description" echo $fooSchema->type; // "object" // Read schema properties $messageProperty = $fooSchema->properties['message']; echo $messageProperty->type; // "string" $codeProperty = $fooSchema->properties['code']; echo $codeProperty->type; // "number" ``` -------------------------------- ### Access OpenAPI Description Data Source: https://github.com/cebe/php-openapi/blob/master/README.md Demonstrates how to access various properties of a parsed OpenAPI object, such as the OpenAPI version, API title, and path definitions. It shows iterating through paths and accessing schema properties. ```php echo $openapi->openapi; // openAPI version, e.g. 3.0.0 echo $openapi->info->title; // API title foreach($openapi->paths as $path => $definition) { // iterate path definitions } # read a component schema $foo = $openapi->components->schemas['Foo']; # read a property of schema $foo->properties['message'] ``` -------------------------------- ### Write OpenAPI Description to JSON Source: https://github.com/cebe/php-openapi/blob/master/README.md Creates an OpenAPI description object using the `OpenApi` and `PathItem` classes and then serializes it into a JSON string using `Writer::writeToJson()`. This method allows programmatic construction of API descriptions. ```php use cebe\openapi\spec\OpenApi; use cebe\openapi\spec\PathItem; // create base API Description $openapi = new OpenApi([ 'openapi' => '3.0.2', 'info' => [ 'title' => 'Test API', 'version' => '1.0.0', ], 'paths' => [], ]); // manipulate description as needed $openapi->paths['/test'] = new PathItem([ 'description' => 'something' ]); // ... $json = \cebe\openapi\Writer::writeToJson($openapi); ``` -------------------------------- ### Inline External References in OpenAPI File using CLI Source: https://github.com/cebe/php-openapi/blob/master/README.md Resolve all external references within an OpenAPI Description file and output a single, inlined file. This is a shortcut for the `convert` command with the `--resolve-external` option. ```bash vendor/bin/php-openapi inline input.yml output.json ``` -------------------------------- ### Validate OpenAPI 3.0.x Description File using CLI Source: https://github.com/cebe/php-openapi/blob/master/README.md Use the CLI tool to validate an OpenAPI Description file against the OpenAPI v3.0 schema. The validation includes structural errors and schema violations. Input can be from a file or STDIN, and content type can be forced. ```bash vendor/bin/php-openapi validate input.yml ``` ```bash cat input.json | vendor/bin/php-openapi validate --read-json ``` -------------------------------- ### Control Reference Resolution for OpenAPI Reading - PHP Source: https://context7.com/cebe/php-openapi/llms.txt Demonstrates how to control reference resolution when reading OpenAPI files using the `Reader` class. Options include resolving all references, only inline references, or no references, as well as manual resolution with a custom context. ```php resolveReferences( new \cebe\openapi\ReferenceContext($openapi, 'https://example.com/api/openapi.yaml') ); ``` -------------------------------- ### Write OpenAPI to JSON (PHP) Source: https://context7.com/cebe/php-openapi/llms.txt This snippet demonstrates how to programmatically create an OpenAPI specification and write it to a JSON string or file using the cebe/php-openapi library. It requires the 'cebe/php-openapi' package and utilizes the Writer class for output. ```php '3.0.0', 'info' => [ 'title' => 'Test API', 'version' => '1.0.0', ], 'paths' => [ '/test' => [ 'description' => 'Test endpoint' ] ], ]); // Write to JSON string $json = Writer::writeToJson($openapi); echo $json; // Output: // { // "openapi": "3.0.0", // "info": { // "title": "Test API", // "version": "1.0.0" // }, // "paths": { // "/test": { // "description": "Test endpoint" // } // } // } // Write to JSON file Writer::writeToJsonFile($openapi, '/path/to/output.json'); ``` -------------------------------- ### Working with OpenAPI References in PHP Source: https://context7.com/cebe/php-openapi/llms.txt Handles and resolves OpenAPI references, including external files and transitive references. It allows checking if an object is a reference, resolving references, and custom reference contexts for external files. Errors during resolution can be collected instead of thrown. ```php paths as $path => $pathItem) { if ($pathItem instanceof Reference) { echo "Path $path is a reference\n"; $resolved = $pathItem->resolve(); echo "Reference points to: {$pathItem->getReference()}\n"; } } // Access referenced schemas $schema = $openapi->components->schemas['User']; if ($schema instanceof Reference) { $actualSchema = $schema->resolve(); echo $actualSchema->type; } // Custom reference context for external files $context = new ReferenceContext($openapi, 'file:///path/to/openapi.yaml'); $context->mode = ReferenceContext::RESOLVE_MODE_ALL; $context->throwException = false; // Collect errors instead of throwing $openapi->resolveReferences($context); // Check for reference resolution errors $errors = $openapi->getErrors(); if (!empty($errors)) { foreach ($errors as $error) { echo "Reference error: $error\n"; } } ``` -------------------------------- ### Read OpenAPI Description with Reference Resolution Source: https://github.com/cebe/php-openapi/blob/master/README.md Reads an OpenAPI description from a JSON or YAML file/URL and resolves references. It supports different resolution modes (`RESOLVE_MODE_ALL` and `RESOLVE_MODE_INLINE`) to control how external and internal references are handled. ```php use cebe\openapi\Reader; use cebe\openapi\spec\OpenAPI; use cebe\openapi\ReferenceContext; // there are two different modes for resolving references: // ALL: resolve all references, which will result in a large description with a lot of repetition // but no references (except if there are recursive references, these will stop at some level) $mode = ReferenceContext::RESOLVE_MODE_ALL; // INLINE: only references to external files are resolved, references to places in the current file // are still Reference objects. $mode = ReferenceContext::RESOLVE_MODE_INLINE; // an absolute URL or file path is needed to allow resolving external references $openapi = Reader::readFromJsonFile('https://www.example.com/api/openapi.json', OpenAPI::class, $mode); $openapi = Reader::readFromYamlFile('https://www.example.com/api/openapi.yaml', OpenAPI::class, $mode); ``` -------------------------------- ### Read OpenAPI Description from YAML Source: https://github.com/cebe/php-openapi/blob/master/README.md Reads an OpenAPI description from a YAML file or a URL. `realpath()` is recommended for local files to ensure correct reference resolution. This function supports both local file paths and remote URLs. ```php use cebe\openapi\Reader; // realpath is needed for resolving references with relative Paths or URLs $openapi = Reader::readFromYamlFile(realpath('openapi.yaml')); // you may also specify the URL to your API Description file $openapi = Reader::readFromYamlFile('https://raw.githubusercontent.com/OAI/OpenAPI-Specification/3.0.2/examples/v3.0/petstore-expanded.yaml'); ``` -------------------------------- ### Read OpenAPI Description from JSON File Source: https://github.com/cebe/php-openapi/blob/master/README.md Reads an OpenAPI description from a JSON file. `realpath()` is used to correctly resolve relative paths or URLs for references within the file. The function returns an instance of the OpenAPI object. ```php use cebe\openapi\Reader; // realpath is needed for resolving references with relative Paths or URLs $openapi = Reader::readFromJsonFile(realpath('openapi.json')); ``` -------------------------------- ### Read OpenAPI from YAML File - PHP Source: https://context7.com/cebe/php-openapi/llms.txt Reads and parses OpenAPI specifications from YAML files, supporting both local files and remote URLs. It allows access to API information like title, description, contact email, and component schemas. ```php info->title; echo $openapi->info->description; echo $openapi->info->contact->email; // Access components schemas $userSchema = $openapi->components->schemas['User']; echo $userSchema->type; // "object" foreach ($userSchema->properties as $propName => $property) { echo "$propName: {$property->type}\n"; } ``` -------------------------------- ### CLI Tool - Validate Command (Bash) Source: https://context7.com/cebe/php-openapi/llms.txt This section details the command-line interface (CLI) 'validate' command for the php-openapi tool. It allows users to validate OpenAPI specification files (YAML or JSON) directly from the terminal. Options include reading from standard input, forcing input format, and silent mode for error output only. Exit codes indicate success, general errors, or validation errors. ```bash # Validate a YAML file vendor/bin/php-openapi validate openapi.yaml # Validate a JSON file vendor/bin/php-openapi validate openapi.json # Validate from STDIN cat openapi.yaml | vendor/bin/php-openapi validate # Force input format vendor/bin/php-openapi validate --read-yaml openapi.txt vendor/bin/php-openapi validate --read-json openapi.txt # Silent mode (only output errors) vendor/bin/php-openapi validate -s openapi.yaml vendor/bin/php-openapi validate --silent openapi.yaml # Exit codes: # 0 - validation successful # 1 - general error (file not found, etc.) # 2 - validation errors found ``` -------------------------------- ### Manually Resolve OpenAPI References Source: https://github.com/cebe/php-openapi/blob/master/README.md Manually resolves references within an already loaded OpenAPI object by providing a `ReferenceContext`. This is useful when references need to be resolved after the initial loading or when the context needs to be explicitly defined. ```php $openapi->resolveReferences( new \cebe\openapi\ReferenceContext($openapi, 'https://www.example.com/api/openapi.yaml') ); ``` -------------------------------- ### Read OpenAPI from JSON File - PHP Source: https://context7.com/cebe/php-openapi/llms.txt Reads and parses an OpenAPI specification from a local JSON file. It automatically resolves external references and provides access to basic information, paths, operations, and servers within the specification. ```php openapi; // "3.0.0" echo $openapi->info->title; // "My API" echo $openapi->info->version; // "1.0.0" // Iterate through paths and operations foreach ($openapi->paths as $path => $pathItem) { echo "Path: $path\n"; foreach ($pathItem->getOperations() as $method => $operation) { echo " $method: {$operation->summary}\n"; echo " OperationId: {$operation->operationId}\n"; } } // Access servers foreach ($openapi->servers as $server) { echo "Server URL: {$server->url}\n"; } ``` -------------------------------- ### Validate OpenAPI Specifications (PHP) Source: https://context7.com/cebe/php-openapi/llms.txt This PHP code snippet demonstrates how to validate an OpenAPI specification loaded from a YAML file. It uses the Reader to load the specification and the validate() method to check its structural integrity. Validation errors can be retrieved using getErrors(). Modifications can be made and re-validated. ```php validate(); if ($isValid) { echo "OpenAPI specification is valid\n"; } else { // Get all validation errors $errors = $openapi->getErrors(); foreach ($errors as $error) { echo "Validation error: $error\n"; } // Example errors: // - "Missing required property: openapi" // - "Missing required property: info" // - "[/paths/users/get] Missing required property: responses" // - "Unsupported openapi version: 2.0" } // Validate after modification $openapi->paths['/newpath'] = new \cebe\openapi\spec\PathItem([ 'get' => new \cebe\openapi\spec\Operation([ // Missing required 'responses' property 'summary' => 'Test operation' ]) ]); $openapi->validate(); // returns false print_r($openapi->getErrors()); // shows validation errors ``` -------------------------------- ### Validate OpenAPI Specification in PHP Source: https://github.com/cebe/php-openapi/blob/master/README.md This snippet demonstrates how to validate an OpenAPI specification using the PHP OpenAPI library. It returns a boolean indicating validity and allows retrieval of any found errors. Note that this validation is basic and not exhaustive. ```php $specValid = $openapi->validate(); $errors = $openapi->getErrors(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.