• Stars
    star
    467
  • Rank 93,935 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 6 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Read and write OpenAPI yaml/json files and make the content accessible in PHP objects.

php-openapi

Read and write OpenAPI 3.0.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.0.x Description files.

Latest Stable Version Total Downloads Build Status

Install

composer require 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 JSON schema, 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.

Completeness

This library is currently work in progress, the following list tracks completeness:

  • read OpenAPI 3.0 JSON
  • read OpenAPI 3.0 YAML
  • OpenAPI 3.0 Schema
    • OpenAPI Object
    • Info Object
    • Contact Object
    • License Object
    • Server Object
    • Server Variable Object
    • Components Object
    • Paths Object
    • Path Item Object
    • Operation Object
    • External Documentation Object
    • Parameter Object
    • Request Body Object
    • Media Type Object
    • Encoding Object
    • Responses Object
    • Response Object
    • Callback Object
    • Example Object
    • Link Object
    • Header Object
    • Tag Object
    • Reference Object
    • Schema Object
      • load/read
      • validation
    • Discriminator Object
    • XML Object
    • Security Scheme Object
    • OAuth Flows Object
    • OAuth Flow Object
    • Security Requirement Object

Development

You may use the docker environment for local development:

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

Support

Need help with your API project?

Professional support, consulting as well as software development services are available:

https://www.cebe.cc/en/contact

Development of this library is sponsored by cebe.☁️ "Your Professional Deployment Platform".

More Repositories

1

markdown

A super fast, highly extensible markdown parser for PHP
HTML
994
star
2

pdfpc-latex-notes

Latex Package that allows creating a pdfpc compatible notes file directly from your latex presentation \notes.
TeX
144
star
3

js-search

A client side search engine for use on static pages.
PHP
139
star
4

yii2-openapi

REST API application generator for Yii2, openapi 3.0 YAML -> Yii2
PHP
131
star
5

yii2-app-api

OpenAPI Spec to API in 3, 2, 1... done!
PHP
104
star
6

assetfree-yii2

A composer package that allows you to install yii2 without composer-asset-plugin
PHP
50
star
7

yii2-lifecycle-behavior

Define the lifecycle of a model by defining allowed status changes.
PHP
50
star
8

markdown-latex

A markdown parser for converting markdown to LaTeX written in PHP.
PHP
44
star
9

yii2-gravatar

Gravatar Widget for Yii Framework 2
PHP
40
star
10

git-simple-subsplit

A git subtree/subsplit script for quickly creating one-way subsplit of repositories. (use for composer packages)
Shell
20
star
11

indent

A small tool to convert text file indentation
PHP
17
star
12

trace-graph

tool to create a network graph from different traceroutes
PHP
13
star
13

luya-module-sitemap

📇 sitemap.xml module for LUYA CMS
PHP
12
star
14

humhub-deployment

Reliable deployments for Humhub. Install Humhub with modules, themes and custom configuration.
Makefile
10
star
15

color-nick

A simple PHP lib that can color nick names to make them distinguishable in a chat room.
PHP
8
star
16

yii2-vuejs

Vue JS asset for Yii 2
PHP
6
star
17

yii2-psr7-messages

PSR7 HTTP Request and Response classes for yii2
PHP
6
star
18

yii2-oauth-server-example

Example application to demonstrate the implementation of an OAuth-Server with Yii 2
PHP
6
star
19

pulse-php-discover

A PHP implementation of the pulse/syncthing cluster discovery protocol.
PHP
5
star
20

gnucash-php

A library for reading gnucash XML format in PHP
PHP
5
star
21

yii-course-example-code

Example code of my yii 1.1 training course
PHP
5
star
22

yii2-oauth-client-example

Example application to demonstrate the implementation of an OAuth-Client with Yii 2
4
star
23

yii2-loki-log-target

Grafana Loki Log Target for Yii2
PHP
4
star
24

jsonstore

A dead simple json file storage.
PHP
3
star
25

make-php

A simple script to build different PHP versions
Shell
3
star
26

clean-docblox-theme

A Docblox template that offers a clean tidy frontend to your docs.
3
star
27

commonmark-latex

A LaTeX extension for https://github.com/thephpleague/commonmark
3
star
28

yii-base-application

A more sophisticated yii base application to start new projects from
PHP
2
star
29

code-dashboard

code dashboard shows your git commits and lets you comment on code and changes
PHP
2
star
30

yii2-debug-profiler

xhprof/uprofiler based profiling added to yii2 debug toolbar
2
star
31

tex-presentation

Template for starting a new latex beamer presentation.
TeX
1
star
32

yii-app-testrunner-standalone

standalone version of yii app testrunner
PHP
1
star
33

bower-asset

This package is registered on packagist to reserve the namespace for the composer-asset-plugin.
1
star
34

commonmark-smartypants

A smartypants extension for https://github.com/thephpleague/commonmark
1
star
35

yiimap.com

A map to show Yii users in the world and bring them together for meetups.
PHP
1
star
36

npm-asset

This package is registered on packagist to reserve the namespace for the composer-asset-plugin.
1
star
37

smartyml

A Multi-Language plugin for smarty template engine
1
star
38

test-gitrepostub

test repo
1
star
39

yii2-activerecord-benchmark

A benchmark to test yii active record performance for different backends
PHP
1
star
40

github-tracker

advanced github notification and pull request viewer
PHP
1
star
41

website-down

the code used while migrating yiiframework.com to a new server.
PHP
1
star
42

yii-app-testrunner

phpunit unittest runner for yii applications
PHP
1
star
43

yiidoc-test

testing something for yiidoc
1
star
44

demo.cebe.cc

Demo site for my yii extensions and some other stuff that comes out while developing cool applications.
PHP
1
star
45

yii2-statsd

A statsd component for Yii 2 to collect profiling and other metrics
1
star
46

db-state-driver

A tool that saves db state for testing purpose.
PHP
1
star