Code Monkey home page Code Monkey logo

cebe-php-openapi's Introduction

Atention

This is a fork of cebe/php-openapi. I created it as library because the pull request of the openapi3.1 was taking years and a lot of developers want to use it.

php-openapi

Read and write OpenAPI 3.x YAML and JSON files and make the content accessible in PHP objects.

It also provides a CLI tool for validating and converting OpenAPI 3.x Description files.

Supported OpenAPI versions:

  • 3.0.x
  • 3.1.x

Latest Stable Version Total Downloads Build Status

Install

composer require devizzent/cebe-php-openapi

Requirements

  • PHP 7.1 or higher (works fine with PHP 8)

Used by

This library provides a low level API for reading and writing OpenAPI files. It is used by higher level tools to do awesome work:

Usage

CLI Tool

$ vendor/bin/php-openapi help
PHP OpenAPI 3 tool
------------------
by Carsten Brandt <[email protected]>

Usage:
  php-openapi <command> [<options>] [input.yml|input.json] [output.yml|output.json]

  The following commands are available:

    validate   Validate the API Description in the specified input file against the OpenAPI v3.0 schema.
               Note: the validation is performed in two steps. The results are composed of
                (1) structural errors found while reading the API Description file, and
                (2) violations of the OpenAPI v3.0 schema.

               If no input file is specified input will be read from STDIN.
               The tool will try to auto-detect the content type of the input, but may fail
               to do so. You may specify --read-yaml or --read-json to force the file type.

               Exits with code 2 on validation errors, 1 on other errors and 0 on success.

    convert    Convert a JSON or YAML input file to JSON or YAML output file.

               If no input file is specified input will be read from STDIN.
               If no output file is specified output will be written to STDOUT.
               The tool will try to auto-detect the content type of the input and output file, but may fail
               to do so. You may specify --read-yaml or --read-json to force the input file type.
               and --write-yaml or --write-json to force the output file type.

               By default all references are resolved (replaced with the object referred to). You can control
               handling of references with the following arguments:

               --resolve-none      Do not resolve references.
               --resolve-external  Only resolve references that point to external files.
                                   This process is often referred to as "inlining".
               --resolve-all       Resolve all references (default).
                                   Recursive pointers will stay references.

    inline     Convert a JSON or YAML input file to JSON or YAML output file and
               resolve all external references. The output will be a single API Description file.
               This is a shortcut for calling convert --resolve-external.

    help       Shows this usage information.

  Options:

    --read-json   force reading input as JSON. Auto-detect if not specified.
    --read-yaml   force reading input as YAML. Auto-detect if not specified.
    --write-json  force writing output as JSON. Auto-detect if not specified.
    --write-yaml  force writing output as YAML. Auto-detect if not specified.
    -s, --silent  silent mode. Will hide all success/information messages and only print errors.

Reading API Description Files

Read OpenAPI Description from JSON file:

use cebe\openapi\Reader;

// realpath is needed for resolving references with relative Paths or URLs
$openapi = Reader::readFromJsonFile(realpath('openapi.json'));

Read OpenAPI Description from YAML:

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');

Access API Description data:

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
}

Object properties are exactly like in the OpenAPI Specification. You may also access additional properties added by specification extensions.

Writing API Description Files

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);

results in the following JSON data:

{
    "openapi": "3.0.0",
    "info": {
        "title": "Test API",
        "version": "1.0.0"
    },
    "paths": {
        "/test": {
            "description": "something"
        }
    }
}

Writing API Description Files using prepared Objects

Since version 1.2.0, the above example can also be written like this (passing objects instead of arrays):

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);

Reading API Description Files and Resolving References

In the above we have passed the raw JSON or YAML data to the Reader. In order to be able to resolve references to structures in external files, we must provide the full context.

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);

If data has been loaded in a different way you can manually resolve references like this by giving a context:

$openapi->resolveReferences(
    new \cebe\openapi\ReferenceContext($openapi, 'https://www.example.com/api/openapi.yaml')
);

Validation

The library provides simple validation operations, that check basic OpenAPI spec requirements. This is the same as "structural errors found while reading the API Description file" from the CLI tool. This validation does not include checking against the OpenAPI v3.0/v3.1 JSON schemas, this is only implemented in the CLI.

// return `true` in case no errors have been found, `false` in case of errors.
$specValid = $openapi->validate();
// after validation getErrors() can be used to retrieve the list of errors found.
$errors = $openapi->getErrors();

Note: Validation is done on a very basic level and is not complete. So a failing validation will show some errors, but the list of errors given may not be complete. Also a passing validation does not necessarily indicate a completely valid spec.

Development

You may use the docker environment for local development:

docker-compose build
make IN_DOCKER=1 install
make IN_DOCKER=1 test
...

cebe-php-openapi's People

Contributors

canvural avatar cebe avatar dependabot[bot] avatar devizzent avatar elazar avatar gitetsu avatar il-m-yamagishi avatar insolita avatar izucken avatar jarjak avatar jongotlin avatar karsa-mistmere avatar lezhnev74 avatar lookyman avatar marcelthole avatar mfrischbutter avatar nadar avatar recchia avatar samdark avatar scaytrase avatar shadowhand avatar silverfire avatar simpod avatar ssfinney avatar the-csaba avatar thejamescollins avatar ttomdewit avatar wyrihaximus avatar xerkus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cebe-php-openapi's Issues

Description next to $ref gets removed

I'm working with an OpenAPI spec like this:

responses:
        200:
          $ref: '#/components/responses/UserResponse'
          description: The updated user.

I use this project to resolve references to external files and to convert to JSON. While doing so, I saw that the description is dropped. The result is like this:

responses:
        200:
          $ref: '#/components/responses/UserResponse'

I know that before, no siblings of $ref were allowed. In 3.1 however, some (like description and summary) are. It would be nice to have support for that in this project.

Servers validation fails with OAS 3.1.0

I used to use cebe/php-openapi to validate my OAS spec, and I'm considering moving to this library, as it supports OAS 3.1

The thing is that, if I switch to "openapi": "3.1.0" and run vendor/bin/php-openapi validate docs/oas.json I get this warning:

OpenAPI v3.1 schema violations:
- [servers[0].url] Invalid URL format

The servers block looks like this:

{
    "servers": [
        {
            "url": "{scheme}://{host}",
            "variables": {
                "scheme": {
                    "default": "https",
                    "enum": ["https", "http"]
                },
                "host": {
                    "default": ""
                }
            }
        }
    ],
}

Which is valid according to OAS 3.1 docs: https://spec.openapis.org/oas/v3.1.0#serverObject

The same command above passes as long as openapi is set to 3.0.3: "openapi": "3.0.3"

Is this ever getting merged?

Thanks for your contributions!

We're currently fighting with null OAS types and was wondering if there're any plans of ever opening a PR with in the cebe/php-openapi repository? I see the README statement about OAS 3.1 taking forever, but that seems to be in now. There does however seem to be some fixes in this fork that would be good to have in cebe's repository.

Vulnerabilities due to yarn.lock file

Hi,

We've started using https://github.com/thephpleague/openapi-psr7-validator in a few services and it's been great so far. Thank you for your support in maintaining this fork.

I've come to you because we've had reports of vulnerabilities in our CD/CI jobs.

Screenshot from 2023-10-23 14-28-06

These seem to be related to the yarn.lock file which is present in the package artifacts and has a few critical vulnerabilities. Is this wanted behavior ? If so would you consider upgrading them to fix the vulnerabilities?

Thanks in advance,

Artemis

Pipeline is broken

Since some time ago the pipeline is failing with php 8.1 and lower dependencies.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.