All Projects → wol-soft → php-json-schema-model-generator

wol-soft / php-json-schema-model-generator

Licence: MIT license
Creates (immutable) PHP model classes from JSON-Schema files including all validation rules as PHP code

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to php-json-schema-model-generator

openapi-generator-go
An opinionated OpenAPI v3 code generator for Go. Use this to generate API models and router scaffolding.
Stars: ✭ 42 (+16.67%)
Mutual labels:  code-generator, openapi, openapi3, openapi-generator
ogen
OpenAPI v3 code generator for go
Stars: ✭ 436 (+1111.11%)
Mutual labels:  code-generator, openapi, openapi3, openapi-generator
Spectral
A flexible JSON/YAML linter for creating automated style guides, with baked in support for OpenAPI v2 & v3.
Stars: ✭ 876 (+2333.33%)
Mutual labels:  json-schema, openapi, openapi3
Fastapi
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Stars: ✭ 39,588 (+109866.67%)
Mutual labels:  json-schema, openapi, openapi3
Full Stack Fastapi Couchbase
Full stack, modern web application generator. Using FastAPI, Couchbase as database, Docker, automatic HTTPS and more.
Stars: ✭ 243 (+575%)
Mutual labels:  json-schema, openapi, openapi3
php-currency-api
Standardized wrapper for popular currency rate APIs. Currently supports FixerIO, CurrencyLayer, Open Exchange Rates and Exchange Rates API.
Stars: ✭ 17 (-52.78%)
Mutual labels:  php8, php73, php74
Full Stack Fastapi Postgresql
Full stack, modern web application generator. Using FastAPI, PostgreSQL as database, Docker, automatic HTTPS and more.
Stars: ✭ 7,635 (+21108.33%)
Mutual labels:  json-schema, openapi, openapi3
Spot
Spot is a concise, developer-friendly way to describe your API contract.
Stars: ✭ 230 (+538.89%)
Mutual labels:  json-schema, openapi, openapi3
Openapi Generator
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
Stars: ✭ 10,634 (+29438.89%)
Mutual labels:  openapi, openapi3, openapi-generator
intellij-openapi-generator
Intellij Plugin for openapi-generator
Stars: ✭ 73 (+102.78%)
Mutual labels:  openapi, openapi3, openapi-generator
Fpp
Functional PHP Preprocessor - Generate Immutable Data Types
Stars: ✭ 282 (+683.33%)
Mutual labels:  immutable, code-generator, code-generation
oag
Idiomatic Go (Golang) client package generation from OpenAPI documents
Stars: ✭ 51 (+41.67%)
Mutual labels:  code-generator, openapi, code-generation
modelina
Library for generating data models based on inputs such as AsyncAPI, OpenAPI, or JSON Schema documents.
Stars: ✭ 55 (+52.78%)
Mutual labels:  json-schema, model, openapi
openapi-schemas
JSON Schemas for every version of the OpenAPI Specification
Stars: ✭ 22 (-38.89%)
Mutual labels:  json-schema, openapi, openapi3
Apispec
A pluggable API specification generator. Currently supports the OpenAPI Specification (f.k.a. the Swagger specification)..
Stars: ✭ 831 (+2208.33%)
Mutual labels:  json-schema, openapi, openapi3
Quenya
Quenya is a framework to build high-quality REST API applications based on extended OpenAPI spec
Stars: ✭ 121 (+236.11%)
Mutual labels:  openapi, code-generation, openapi3
Uvicorn Gunicorn Fastapi Docker
Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.
Stars: ✭ 1,014 (+2716.67%)
Mutual labels:  json-schema, openapi, openapi3
laravel-username-generator
Automatically generate usernames for Laravel User Model
Stars: ✭ 37 (+2.78%)
Mutual labels:  php8, php73, php74
Gnostic
A compiler for APIs described by the OpenAPI Specification with plugins for code generation and other API support tasks.
Stars: ✭ 870 (+2316.67%)
Mutual labels:  openapi, code-generation, openapi3
Datamodel Code Generator
Pydantic model generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.
Stars: ✭ 393 (+991.67%)
Mutual labels:  code-generator, json-schema, openapi

Latest Version Minimum PHP Version Maintainability Build Status Coverage Status MIT License Documentation Status

php-json-schema-model-generator

Generates PHP model classes from JSON-Schema files including validation and providing a fluent auto completion for the generated classes.

Table of Contents

Motivation

Simple example from a PHP application: you define and document an API with swagger annotations and JSON-Schema models. Now you want to use models in your controller actions instead of manually accessing the request data (eg. array stuff). Additionally your schema already defines the validation rules for the models. Why duplicate this rules into your manually written code? Instead you can set up a middleware which instantiates models generated with this library and feed the model with the request data. Now you have a validated model which you can use in your controller action. With full auto completion when working with nested objects. Yay!

Requirements

  • Requires at least PHP 7.2
  • Requires the PHP extensions ext-json and ext-mbstring

Installation

The recommended way to install php-json-schema-model-generator is through Composer:

$ composer require --dev wol-soft/php-json-schema-model-generator
$ composer require wol-soft/php-json-schema-model-generator-production

To avoid adding all dependencies of the php-json-schema-model-generator to your production dependencies it's recommended to add the library as a dev-dependency and include the wol-soft/php-json-schema-model-generator-production library. The production library provides all classes to run the generated code. Generating the classes should either be a step done in the development environment or as a build step of your application (which is the recommended workflow).

Basic usage

Check out the docs for more details.

The base object for generating models is the Generator. After you have created a Generator you can use the object to generate your model classes without any further configuration:

(new Generator())
    ->generateModels(new RecursiveDirectoryProvider(__DIR__ . '/schema'), __DIR__ . '/result');

The first parameter of the generateModels method must be a class implementing the SchemaProviderInterface. The provider fetches the JSON schema files and provides them for the generator. The following providers are available:

Provider Description
RecursiveDirectoryProvider Fetches all *.json files from the given source directory. Each file must contain a JSON Schema object definition on the top level
OpenAPIv3Provider Fetches all objects defined in the #/components/schemas section of an Open API v3 spec file

The second parameter must point to an existing and empty directory (you may use the generateModelDirectory helper method to create your destination directory). This directory will contain the generated PHP classes after the generator is finished.

As an optional parameter you can set up a GeneratorConfiguration object (check out the docs for all available options) to configure your Generator and/or use the method generateModelDirectory to generate your model directory (will generate the directory if it doesn't exist; if it exists, all contained files and folders will be removed for a clean generation process):

$generator = new Generator(
    (new GeneratorConfiguration())
        ->setNamespacePrefix('MyApp\Model')
        ->setImmutable(false)
);

$generator
    ->generateModelDirectory(__DIR__ . '/result');
    ->generateModels(new RecursiveDirectoryProvider(__DIR__ . '/schema'), __DIR__ . '/result');

The generator will check the given source directory recursive and convert all found *.json files to models. All JSON-Schema files inside the source directory must provide a schema of an object.

Examples

The directory ./tests/manual contains some easy examples which show the usage. After installing the dependencies of the library via composer update you can execute php ./tests/manual/test.php to generate the examples and play around with some JSON-Schema files to explore the library.

Let's have a look into an easy example. We create a simple model for a person with a name and an optional age. Our resulting JSON-Schema:

{
  "$id": "Person",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer",
      "minimum": 0
    }
  },
  "required": [
    "name"
  ]
}

After generating a class with this JSON-Schema our class with the name Person will provide the following interface:

// the constructor takes an array with data which is validated and applied to the model
public function __construct(array $modelData);

// the method getRawModelDataInput always delivers the raw input which was provided on instantiation
public function getRawModelDataInput(): array;

// getters to fetch the validated properties. Age is nullable as it's not required
public function getName(): string;
public function getAge(): ?int;

// setters to change the values of the model after instantiation (only generated if immutability is disabled)
public function setName(string $name): Person;
public function setAge(?int $age): Person;

Now let's have a look at the behaviour of the generated model:

// Throws an exception as the required name isn't provided.
// Exception: 'Missing required value for name'
$person = new Person([]);

// Throws an exception as the name provides an invalid value.
// Exception: 'Invalid type for name. Requires string, got int'
$person = new Person(['name' => 12]);

// Throws an exception as the age contains an invalid value due to the minimum definition.
// Exception: 'Value for age must not be smaller than 0'
$person = new Person(['name' => 'Albert', 'age' => -1]);

// A valid example as the age isn't required
$person = new Person(['name' => 'Albert']);
$person->getName(); // returns 'Albert'
$person->getAge(); // returns NULL
$person->getRawModelDataInput(); // returns ['name' => 'Albert']

// If setters are generated the setters also perform validations.
// Exception: 'Value for age must not be smaller than 0'
$person->setAge(-10);

More complex exception messages eg. from a allOf composition may look like:

Invalid value for Animal declined by composition constraint.
  Requires to match 3 composition elements but matched 1 elements.
  - Composition element #1: Failed
    * Value for age must not be smaller than 0
  - Composition element #2: Valid
  - Composition element #3: Failed
    * Value for legs must not be smaller than 2
    * Value for legs must be a multiple of 2

How the heck does this work?

The class generation process basically splits up into three to four steps:

  • Scan the given source directory to find all *.json files which should be processed.
  • Loop over all schemas which should be generated. This is the main step of the class generation. Now each schema is parsed and a Schema model class which holds the properties for the generated model is populated. All validation rules defined in the JSON-Schema are translated into plain PHP code. After the model is finished a RenderJob is generated and added to the RenderQueue. If a JSON-Schema contains nested objects or references multiple RenderJobs may be added to the RenderQueue for a given schema file.
  • If post processors are defined for the generation process the post processors will be applied.
  • After all schema files have been parsed without an error the RenderQueue will be worked off. All previous added RenderJobs will be executed and the PHP classes will be saved to the filesystem at the given destination directory.

Tests

The library is tested via PHPUnit.

After installing the dependencies of the library via composer update you can execute the tests with ./vendor/bin/phpunit (Linux) or vendor\bin\phpunit.bat (Windows). The test names are optimized for the usage of the --testdox output. Most tests are atomic integration tests which will set up a JSON-Schema file and generate a class from the schema and test the behaviour of the generated class afterwards.

During the execution the tests will create a directory PHPModelGeneratorTest in tmp where JSON-Schema files and PHP classes will be written to.

If a test which creates a PHP class from a JSON-Schema fails the JSON-Schema and the generated class(es) will be dumped to the directory ./failed-classes

Docs

The docs for the library is generated with Sphinx.

To generate the documentation install Sphinx, enter the docs directory and execute make html (Linux) or make.bat html (Windows). The generated documentation will be available in the directory ./docs/build.

The documentation hosted at Read the Docs is updated on each push.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].