All Projects → swaggest → php-code-builder

swaggest / php-code-builder

Licence: MIT License
JSON Schema enabled PHP code building abstraction for PHP

Programming Languages

PHP
23972 projects - #3 most used programming language
Makefile
30231 projects

Projects that are alternatives of or similar to php-code-builder

php-json-schema-model-generator
Creates (immutable) PHP model classes from JSON-Schema files including all validation rules as PHP code
Stars: ✭ 36 (-34.55%)
Mutual labels:  code-generator, json-schema
Datamodel Code Generator
Pydantic model generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.
Stars: ✭ 393 (+614.55%)
Mutual labels:  code-generator, json-schema
commun
🎩 Fully-featured framework for REST APIs and GraphQL from JSON Schema with TypeScript and MongoDB
Stars: ✭ 97 (+76.36%)
Mutual labels:  json-schema
TIGER
implement a full compiler based on c++ 11
Stars: ✭ 17 (-69.09%)
Mutual labels:  code-generator
json-schema-inferrer
Java library for inferring JSON schema from sample JSONs
Stars: ✭ 78 (+41.82%)
Mutual labels:  json-schema
i18n-tag-schema
Generates a json schema for all i18n tagged template literals in your project
Stars: ✭ 15 (-72.73%)
Mutual labels:  json-schema
grunt-tv4
Use Grunt and Tiny Validator tv4 to validate files against json-schema draft v4
Stars: ✭ 13 (-76.36%)
Mutual labels:  json-schema
home
This is the home page for the API specification toolbox.
Stars: ✭ 16 (-70.91%)
Mutual labels:  json-schema
php-code-generator
PHP code generator library
Stars: ✭ 144 (+161.82%)
Mutual labels:  code-generator
autogenu-jupyter
An automatic code generator for nonlinear model predictive control (NMPC) and the continuation/GMRES method (C/GMRES) based numerical solvers for NMPC
Stars: ✭ 89 (+61.82%)
Mutual labels:  code-generator
yoma
一个小而美的低代码全栈开发平台,一键生成后端api接口+前端页面代码+在线接口文档,节省50%的前后端开发的工作量。基于springboot +mybatis+spring security+vue 技术栈
Stars: ✭ 137 (+149.09%)
Mutual labels:  code-generator
svelte-form
JSON Schema form for Svelte v3
Stars: ✭ 47 (-14.55%)
Mutual labels:  json-schema
molicode
molicode
Stars: ✭ 75 (+36.36%)
Mutual labels:  code-generator
openapi-schemas
JSON Schemas for every version of the OpenAPI Specification
Stars: ✭ 22 (-60%)
Mutual labels:  json-schema
jsf
Creates fake JSON files from a JSON schema
Stars: ✭ 46 (-16.36%)
Mutual labels:  json-schema
Argus
Builds models from JSON Schemas
Stars: ✭ 106 (+92.73%)
Mutual labels:  json-schema
form-pa
A flexible and configurable form based on json schema
Stars: ✭ 13 (-76.36%)
Mutual labels:  json-schema
json-schema-sugar
Create a JSON Schema without the pain of writing it 🍦
Stars: ✭ 20 (-63.64%)
Mutual labels:  json-schema
qm
QM model-based design tool and code generator based on UML state machines
Stars: ✭ 54 (-1.82%)
Mutual labels:  code-generator
sts
Swagger to sf schema & st column in ng-alain
Stars: ✭ 20 (-63.64%)
Mutual labels:  json-schema

Swaggest JSON-schema enabled PHP code builder

Build Status Scrutinizer Code Quality Code Climate codecov

This library generates PHP mapping structures defined by JSON schema using swaggest/json-schema.

Example

Generated code

You need to add swaggest/json-schema to your dependencies.

<?php

require_once __DIR__ . '/vendor/autoload.php';

$schemaData = json_decode(<<<'JSON'
{
    "type": "object",
    "properties": {
        "id": {"type": "integer"},
        "name": {"type": "string"},
        "parent": {"$ref": "#"},
        "children": {"type": "array", "items": {"$ref": "#"}},
        "info": {"$ref": "#/definitions/info"}
    },
    "definitions": {
        "info": {
            "type": "object",
            "properties": {
                "lastName": {"type": "string"},
                "birthDate": {"type": "string", "format": "date-time"},
                "options": {"$ref": "#/definitions/options"}
            }
        },
        "options": {
            "type": "object",
            "properties": {
                "rememberSession": {"type": "boolean"},
                "allowNotifications": {"type": "boolean"}
            }
        }
    }
}
JSON
);

$swaggerSchema = \Swaggest\JsonSchema\Schema::import($schemaData);

$appPath = realpath(__DIR__ . '/tests/src/Tmp') . '/Example';
$appNs = 'Swaggest\PhpCodeBuilder\Tests\Tmp\Example';

$app = new \Swaggest\PhpCodeBuilder\App\PhpApp();
$app->setNamespaceRoot($appNs, '.');

$builder = new \Swaggest\PhpCodeBuilder\JsonSchema\PhpBuilder();
$builder->buildSetters = true;
$builder->makeEnumConstants = true;

$builder->classCreatedHook = new \Swaggest\PhpCodeBuilder\JsonSchema\ClassHookCallback(
    function (\Swaggest\PhpCodeBuilder\PhpClass $class, $path, $schema) use ($app, $appNs) {
        $desc = '';
        if ($schema->title) {
            $desc = $schema->title;
        }
        if ($schema->description) {
            $desc .= "\n" . $schema->description;
        }
        if ($fromRefs = $schema->getFromRefs()) {
            $desc .= "\nBuilt from " . implode("\n" . ' <- ', $fromRefs);
        }

        $class->setDescription(trim($desc));

        $class->setNamespace($appNs);
        if ('#' === $path) {
            $class->setName('User'); // Class name for root schema
        } elseif (strpos($path, '#/definitions/') === 0) {
            $class->setName(\Swaggest\PhpCodeBuilder\PhpCode::makePhpClassName(
                substr($path, strlen('#/definitions/'))));
        }
        $app->addClass($class);
    }
);

$builder->getType($swaggerSchema);
$app->clearOldFiles($appPath);
$app->store($appPath);

Creating and exporting an instance

$user = new \Swaggest\PhpCodeBuilder\Tests\Tmp\Example\User();
$user->name = "John";
$user->info = (new \Swaggest\PhpCodeBuilder\Tests\Tmp\Example\Info())
    ->setLastName("Doe")
    ->setBirthDate("1980-01-01")
    ->setOptions(
        (new \Swaggest\PhpCodeBuilder\Tests\Tmp\Example\Options())
            ->setRememberSession(true)
            ->setAllowNotifications(false)
    );

// No exception on exporting valid data
$jsonData = \Swaggest\PhpCodeBuilder\Tests\Tmp\Example\User::export($user);

// {"name":"John","info":{"lastName":"Doe","birthDate":"1980-01-01","options":{"rememberSession":true,"allowNotifications":false}}}
echo json_encode($jsonData);

// Setting invalid value (integer instead of string)
$user->name = 123;

// Exception: String expected, 123 received at #->$ref[#]->properties:name
$jsonData = \Swaggest\PhpCodeBuilder\Tests\Tmp\Example\User::export($user);

Creating class instance from raw data

// Importing raw data to entity class instance will do validation and mapping
$user = \Swaggest\PhpCodeBuilder\Tests\Tmp\Example\User::import(
    json_decode('{"name":"John","info":{"lastName":"Doe","birthDate":"1980-01-01","options":{"rememberSession":true,"allowNotifications":false}}}')
);

var_dump($user->info->options->allowNotifications); // bool(false)

CLI Tool

You can use json-cli to render JSON Schema into PHP classes from command line.

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].