PHP code example of open-code-modeling / json-schema-to-php-ast

1. Go to this page and download the library: Download open-code-modeling/json-schema-to-php-ast library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

open-code-modeling / json-schema-to-php-ast example snippets




use OpenCodeModeling\CodeAst\Builder\FileCollection;
use OpenCodeModeling\CodeAst\Package\ClassInfoList;
use OpenCodeModeling\CodeAst\Package\Psr4Info;
use OpenCodeModeling\Filter\FilterFactory;
use OpenCodeModeling\JsonSchemaToPhp\Type\Type;
use OpenCodeModeling\JsonSchemaToPhpAst\ValueObjectFactory;

$parser = (new PhpParser\ParserFactory())->create(PhpParser\ParserFactory::ONLY_PHP7);
$printer = new PhpParser\PrettyPrinter\Standard(['shortArraySyntax' => true]);

// configure your Composer info
// FilterFactory of library open-code-modeling/php-filter is used for sake of brevity
$classInfoList = new ClassInfoList(
    ...Psr4Info::fromComposer(
        'src/',
        file_get_contents('composer.json'),
        FilterFactory::directoryToNamespaceFilter(),
        FilterFactory::namespaceToDirectoryFilter(),
    )
);

$valueObjectFactory = new ValueObjectFactory(
    $classInfoList,
    $parser,
    $printer,
    true,
    FilterFactory::classNameFilter(),
    FilterFactory::propertyNameFilter(),
    FilterFactory::methodNameFilter(),
    FilterFactory::constantNameFilter(),
    FilterFactory::constantValueFilter()
);

// $json contains the json string from above
$decodedJson = \json_decode($json, true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR);

$typeSet = Type::fromDefinition($decodedJson);
$srcFolder = 'tmp/';

$fileCollection = FileCollection::emptyList();
$classBuilder = ClassBuilder::fromScratch('Order', 'YourNamespaceFromComposer')->setFinal(true);

$valueObjectFactory->generateClasses($classBuilder, $fileCollection, $typeSet, $srcFolder);

// $fileCollection contains 6 classes

// now let's add constants and getter methods of properties for non value objects
$valueObjectFactory->addGetterMethodsForProperties($fileCollection, true);
$valueObjectFactory->addClassConstantsForProperties($fileCollection);

// generate PHP code
$files = $valueObjectFactory->generateFiles($fileCollection);

foreach ($files as $filename => $code) {
    // store PHP code to filesystem
}