cebe/php-openapi

repository·master·Indexed 19 days ago

https://github.com/cebe/php-openapi

A PHP-based toolset for working with OpenAPI 3.0.x specifications. It provides a CLI tool for validating API descriptions against the official schema and converting between JSON and YAML formats, including capabilities to inline external references. The library includes a Reader for parsing specs from strings or files and a set of spec classes (such as Parameter, MediaType, Encoding, and Callback) to represent and validate OpenAPI objects programmatically.

Tokens
8.5K
Snippets
33
Records
39
Agent score
67%

What's inside cebe-php-openapi

  1. Use the PHP OpenAPI CLI tool

    master

    The php-openapi CLI tool allows you to validate OpenAPI 3.0.x files against the official schema and convert between JSON and YAML formats. It supports reading from files or STDIN and writing to files or STDOUT.

    # Validate a YAML file
    ./bin/php-openapi validate input.yaml
    
    # Convert a JSON file to a single YAML file with external references inlined
    ./bin/php-openapi inline input.json output.yaml
  2. Run the development environment with Docker Compose

    master

    The project provides a docker-compose.yml file to orchestrate a development environment consisting of a PHP service and a Node.js service. This setup is primarily intended for running tests or development tasks in a containerized environment.

    Services

    • php: A service built from tests/docker/Dockerfile. It includes pre-configured environment variables for timezones, Docker detection, and Xdebug support.
    • node: A service using the node:12 image, useful for tasks requiring a Node.js runtime.

    Environment Configuration (PHP Service)

    The PHP service exposes several environment variables that can be used to configure the container behavior:

    VariableDefault ValueDescription
    TZUTCSystem timezone
    TIMEZONEUTCPHP timezone
    IN_DOCKERdockerFlag indicating the environment is Docker
    PHP_XDEBUG_ENABLED1Enables Xdebug
    XDEBUG_CONFIGremote_host=host.docker.internalXdebug configuration string
    PHP_IDE_CONFIGserverName=DockerConfiguration for IDE integration (e.g., PhpStorm)

    Volume Mappings

    • The PHP service maps the local project root to /app in the container.
    • The local ./tests/tmp/.composer directory is mapped to /root/.composer to persist Composer data.
    • The Node service maps the local project root to /app in the container.
    # To start the environment, run:
    docker-compose up
  3. Configure reference resolution in Reader

    master

    When using readFromJsonFile() or readFromYamlFile(), you can control how $resolveReferences behaves. This determines if Reference objects are replaced by the actual objects they point to.

    Supported values for $resolveReferences:

    • true (default): Resolves all references.
    • false: Does not resolve any references.
    • 'inline': Only resolves references to external files.
    • 'all': Resolves all references except recursive references.
    use cebe\openapi\Reader;
    
    // Resolve only external file references
    $spec = Reader::readFromYamlFile('spec.yaml', OpenApi::class, 'inline');
    
    // Resolve all non-recursive references
    $spec = Reader::readFromYamlFile('spec.yaml', OpenApi::class, 'all');
    
    // Do not resolve any references
    $spec = Reader::readFromYamlFile('spec.yaml', OpenApi::class, false);
  4. Validate Callback object data

    master

    You can validate a Callback object against the OpenAPI specification using the validate() method. This checks both the callback structure itself and the underlying PathItem object.

    If validate() returns false, you can retrieve a list of specific validation errors using getErrors(). Errors may include the JSON pointer position of the error within the document.

    if (!$callback->validate()) {
        foreach ($callback->getErrors() as $error) {
            echo "Error: " . $error . PHP_EOL;
        }
    }
  5. Resolve OpenAPI references with Reference::resolve()

    master

    The Reference class represents an OpenAPI $ref object. To transform a Reference object into the actual object it points to (e.g., a Schema or Parameter object), use the resolve() method.

    Important:

    • You must provide a ReferenceContext to resolve(). If you haven't previously called setContext() on the Reference instance, you must pass the context directly to the method.
    • resolve() does not automatically resolve recursive references. If the resolved object contains further references, you may need to call resolveReferences() on the resulting object (if it supports it) to handle them recursively.
    • If the reference is cyclic, an UnresolvableReferenceException will be thrown.
    // Assuming $reference is an instance of cebe\openapi\spec\Reference
    // and $context is an instance of cebe\openapi\ReferenceContext
    
    try {
        $resolvedObject = $reference->resolve($context);
        // $resolvedObject is now the actual SpecObjectInterface (e.g., a Schema object)
    } catch (UnresolvableReferenceException $e) {
        // Handle resolution failure
    }
  6. Get raw spec data from a Reference object

    master

    If you need to access the original array data (the raw YAML/JSON input) used to instantiate the Reference object, use getRawSpecData(). This is useful for debugging or manual inspection of the $ref key.

    $rawData = $reference->getRawSpecData();
    // Returns ['$ref' => '...']
  7. Represent an OpenAPI Encoding object

    master

    The cebe\openapi\spec\Encoding class represents an OpenAPI Encoding object, which defines how a single schema property is encoded in a request or response body. It is used to specify content types, headers, styles, and explosion behavior.

    Available Properties

    When working with an Encoding instance, you can access the following properties:

    PropertyTypeDescription
    contentTypestringThe media type used for encoding (e.g., application/json).
    headersHeader[] or Reference[]A list of headers used in the encoding.
    stylestringThe encoding style (e.g., form, json, simple, spaceDelimited).
    explodebooleanWhether to explode the property in the encoding.
    allowReservedbooleanWhether to allow reserved characters in the encoding.

    Default Behavior and Spec Compliance

    The class automatically handles several OpenAPI specification defaults during construction:

    1. Explode Default: If the style is set to form, the explode property defaults to true.
    2. Content-Type Defaults: If a Schema object is provided during construction, the contentType is automatically inferred based on the schema type and format:
      • String with format: binary: Defaults to application/octet-stream.
      • String (other), Boolean, Integer, Number: Defaults to text/plain.
      • Object: Defaults to application/json.
      • Array: The default is determined by the type of the items within the array.
  8. Validate a Reference object

    master

    You can check if a Reference object is valid according to the OpenAPI specification by calling validate(). This checks if the $ref value is a valid JSON pointer and if the object contains only the allowed $ref property.

    If validate() returns false, you can retrieve the specific error messages using getErrors().

    if (!$reference->validate()) {
        $errors = $reference->getErrors();
        foreach ($errors as $error) {
            echo "Validation error: $error\n";
        }
    }
  9. Convert OpenAPI spec objects to YAML strings

    master

    Use Writer::writeToYaml() to convert an object implementing SpecObjectInterface (such as an OpenApi instance) into a YAML-formatted string. The output is configured to dump objects as maps and empty arrays as sequences to maintain OpenAPI compatibility.

    use cebe\openapi\Writer;
    
    // Assuming $openapi is an instance of cebe\openapi\spec\OpenApi
    $yamlString = Writer::writeToYaml($openapi);
  10. Read OpenAPI specs from JSON or YAML strings

    master

    Use Reader::readFromJson() or Reader::readFromYaml() to instantiate OpenAPI spec objects directly from raw strings. By default, these methods return an instance of cebe\openapi\spec\OpenApi. If you are working with sub-sections of a specification, you can pass a different class name as the $baseType argument, provided it implements SpecObjectInterface.

    use cebe\openapi\Reader;
    use cebe\openapi\spec\OpenApi;
    
    // From a JSON string
    $spec = Reader::readFromJson($jsonString);
    
    // From a YAML string
    $spec = Reader::readFromYaml($yamlString);
    
    // Specifying a custom base type for sub-sections
    $pathItem = Reader::readFromYaml($yamlString, PathItem::class);
  11. Represent OpenAPI Callback objects with the Callback class

    master

    The cebe\openapi\spec\Callback class represents an OpenAPI Callback object. A callback is a map of possible out-of-band callbacks related to a parent operation. Each entry in the map consists of a URL and a corresponding PathItem object describing the callback request.

    To create a Callback object, pass an associative array where the key is the callback URL and the value is the data for the PathItem (e.g., an array representing the path item structure).

    Key methods:

    • getUrl(): Returns the callback URL.
    • getRequest(): Returns the PathItem object associated with the callback.
    • getSerializableData(): Returns the serializable data used for converting the object back to JSON or YAML.
    use cebe\openapi\spec\Callback;
    
    // Example data representing a callback URL and its path item
    $data = [
        'https://example.com/callback' => [
            'post' => [
                'responses' => [
                    '200' => ['description' => 'Callback received']
                ]
            ]
        ]
    ];
    
    $callback = new Callback($data);
    echo $callback->getUrl(); // https://example.com/callback
  12. Represent OpenAPI Path Item objects with PathItem

    master

    The cebe\openapi\spec\PathItem class represents an OpenAPI Path Item object, which describes the operations (GET, POST, etc.) available on a single path.

    Key properties available on a PathItem instance include:

    • summary: A short summary of the path.
    • description: A detailed description of the path.
    • Operations: get, put, post, delete, options, head, patch, and trace (each returns an Operation|null).
    • servers: An array of Server objects.
    • parameters: An array of Parameter or Reference objects.

    Note: A Path Item may be empty due to ACL constraints; the path remains exposed in documentation, but operations and parameters may be unknown.