GithubHelp home page GithubHelp logo

informaticacba / php-code-builder Goto Github PK

View Code? Open in Web Editor NEW

This project forked from swaggest/php-code-builder

1.0 0.0 0.0 536 KB

JSON Schema enabled PHP code building abstraction for PHP

License: MIT License

PHP 99.89% Makefile 0.11%

php-code-builder's Introduction

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.

php-code-builder's People

Contributors

blackstark123 avatar cussrox avatar klim0v avatar krisod avatar reflexxion avatar simoheinonen avatar stephanniewerth avatar vearutop avatar

Stargazers

 avatar

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.