PHP code example of openapi-tools / generator-utils
1. Go to this page and download the library: Download openapi-tools/generator-utils 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/ */
openapi-tools / generator-utils example snippets
use OpenAPITools\Generator\Utils\FileStringyfier;
use OpenAPITools\Utils\File;
use PhpParser\BuilderFactory;
use PhpParser\PrettyPrinter\Standard;
$builderFactory = new BuilderFactory();
$stringyfier = new FileStringyfier(new Standard());
// AST-backed file
$astFile = new File(
'src',
'Example',
$builderFactory->namespace('Vendor\\Api')
->addStmt($builderFactory->class('Example')->makeFinal()->getNode())
->getNode(),
File::DO_NOT_LOAD_ON_WRITE,
);
$php = $stringyfier->toString($astFile);
// generates into
<<<'PHP'
declare (strict_types=1);
namespace Vendor\Api;
final class Example
{
}
PHP;
// String-backed file (for example generation state JSON)
$jsonFile = new File('', 'state.json', '{"specHash":""}', File::DO_NOT_LOAD_ON_WRITE);
$json = $stringyfier->toString($jsonFile);
// generates into
'{"specHash":""}' . PHP_EOL
use OpenAPITools\Generator\Utils\Builder\DocBlockBuilder;
$docComment = DocBlockBuilder::fromLines([
'A generated schema class.',
'@property string $name',
'@property int $count',
]);
// generates into
/**
* A generated schema class.
* @property string $name
* @property int $count
*/
$builderFactory->method('__construct')->setDocComment($docComment);
use OpenAPITools\Generator\Utils\Builder\DocBlockBuilder;
use OpenAPITools\Generator\Utils\Type\DocBlockTag;
use OpenAPITools\Generator\Utils\Type\PropertyTypeResolver;
$lines = [];
foreach ($schema->properties as $property) {
$resolved = PropertyTypeResolver::resolve($property, DocBlockTag::Param);
if ($resolved->docBlockLine !== '') {
$lines[] = $resolved->docBlockLine;
}
}
$constructor->setDocComment(DocBlockBuilder::fromDocLines([
'/** @param string $name */',
...$lines,
]));
// generates into
/**
* @param string $name
* @param ?array<\Vendor\Schema\Item> $items
*/
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$variable = ExpressionBuilder::var('payload');
$printer->prettyPrintExpr($variable);
// generates into
$payload
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$property = ExpressionBuilder::thisProperty('handler');
$printer->prettyPrintExpr($property);
// generates into
$this->handler
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$call = ExpressionBuilder::thisMethod('resolve', ['headers', 'data']);
$printer->prettyPrintExpr($call);
// generates into
$this->resolve($headers, $data)
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$call = ExpressionBuilder::methodCall(
ExpressionBuilder::thisMethod('getObjectMapperUsers'),
'hydrateObject',
['className', 'payload'],
);
$printer->prettyPrintExpr($call);
// generates into
$this->getObjectMapperUsers()->hydrateObject($className, $payload)
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$class = ExpressionBuilder::classConstant('\\Vendor\\Schema\\User');
$printer->prettyPrintExpr($class);
// generates into
\Vendor\Schema\User::class
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$className = ExpressionBuilder::objectClassConstant('object');
$printer->prettyPrintExpr($className);
// generates into
$object::class
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$fetch = ExpressionBuilder::arrayFetch('data', 'id');
$printer->prettyPrintExpr($fetch);
// generates into
$data['id']
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$fetch = ExpressionBuilder::arrayFetchKey('data', ExpressionBuilder::var('index'));
$printer->prettyPrintExpr($fetch);
// generates into
$data[$index]
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$comparison = ExpressionBuilder::identical(
ExpressionBuilder::var('status'),
ExpressionBuilder::literalString('ok'),
);
$printer->prettyPrintExpr($comparison);
// generates into
$status === 'ok'
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$ternary = ExpressionBuilder::nullSafe(
ExpressionBuilder::var('value'),
ExpressionBuilder::thisProperty('value'),
);
$printer->prettyPrintExpr($ternary);
// generates into
$value === null ? null : $this->value
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$printer->prettyPrintExpr(ExpressionBuilder::null());
// generates into
null
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$printer->prettyPrintExpr(ExpressionBuilder::true());
// generates into
true
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$printer->prettyPrintExpr(ExpressionBuilder::false());
// generates into
false
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$literal = ExpressionBuilder::literalString('missing');
$printer->prettyPrintExpr($literal);
// generates into
'missing'
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$literal = ExpressionBuilder::literalInt(42);
$printer->prettyPrintExpr($literal);
// generates into
42
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$call = ExpressionBuilder::invoke(ExpressionBuilder::var('callback'), ['value']);
$printer->prettyPrintExpr($call);
// generates into
$callback($value)
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$call = ExpressionBuilder::funcCall('strlen', ['value']);
$printer->prettyPrintExpr($call);
// generates into
strlen($value)
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$instance = ExpressionBuilder::newInstance('\\EventSauce\\ObjectHydrator\\IterableList', [
ExpressionBuilder::thisMethod('doHydrateObjects', ['className', 'payloads']),
]);
$printer->prettyPrintExpr($instance);
// generates into
new \EventSauce\ObjectHydrator\IterableList($this->doHydrateObjects($className, $payloads))
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$exception = ExpressionBuilder::newRuntimeException('Unknown class');
$printer->prettyPrintExpr($exception);
// generates into
new \RuntimeException('Unknown class')
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$statement = ExpressionBuilder::throwRuntimeException('missing');
$printer->prettyPrint([$statement]);
// generates into
throw new \RuntimeException('missing');
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$statement = ExpressionBuilder::throwNew('\\InvalidArgumentException', ['message']);
$printer->prettyPrint([$statement]);
// generates into
throw new \InvalidArgumentException($message);
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$catch = ExpressionBuilder::catchThrowable('throwable', 'error');
$printer->prettyPrint([$catch]);
// generates into
catch (\Throwable $throwable) {
$error = $throwable;
}
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$if = ExpressionBuilder::lazyInitIfNotInstance('mapper', '\\Vendor\\Mapper', ['config']);
$printer->prettyPrint([$if]);
// generates into
if ($this->mapper instanceof \Vendor\Mapper === false) {
$this->mapper = new \Vendor\Mapper($config);
}
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
$return = ExpressionBuilder::returnProperty('mapper');
$printer->prettyPrint([$return]);
// generates into
return $this->mapper;
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
use PhpParser\Node\Arg;
$args = ExpressionBuilder::args([
new Arg(ExpressionBuilder::var('value')),
'other',
]);
// $args[0] wraps $value, $args[1] wraps $other
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
use OpenAPITools\Generator\Utils\Builder\StatementBuilder;
$assign = StatementBuilder::assign(
'payload',
ExpressionBuilder::thisMethod('resolve', ['data']),
);
$printer->prettyPrint([$assign]);
// generates into
$payload = $this->resolve($data);
use OpenAPITools\Generator\Utils\Builder\StatementBuilder;
$foreach = StatementBuilder::yieldMapOverIterable(
'payloads',
'payload',
'index',
'hydrateObject',
['className', 'payload'],
);
$printer->prettyPrint([$foreach]);
// generates into
foreach ($payloads as $index => $payload) {
yield $index => $this->hydrateObject($className, $payload);
}
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
use OpenAPITools\Generator\Utils\Builder\StatementBuilder;
use PhpParser\Node\Stmt\Return_;
$tryCatch = StatementBuilder::tryReturnIgnoringThrowable(
new Return_(ExpressionBuilder::var('value')),
);
$printer->prettyPrint([$tryCatch]);
// generates into
try {
return $value;
} catch (\Throwable) {
}
use OpenAPITools\Generator\Utils\Builder\StatementBuilder;
$throw = StatementBuilder::throwVariable('error');
$printer->prettyPrint([$throw]);
// generates into
throw $error;
use OpenAPITools\Generator\Utils\Builder\StatementBuilder;
$return = StatementBuilder::returnMethodCall('receiver', 'run', ['input']);
$printer->prettyPrint([$return]);
// generates into
return $receiver->run($input);
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
use OpenAPITools\Generator\Utils\Builder\MatchBuilder;
use PhpParser\Node\Expr;
use PhpParser\Node\Scalar;
$match = MatchBuilder::onVariable('status', [
[
'conditions' => [new Scalar\String_('ok')],
'body' => ExpressionBuilder::thisProperty('handler'),
],
], ExpressionBuilder::throwRuntimeException('Unknown status'));
$printer->prettyPrintExpr($match);
// generates into
match ($status) {
'ok' => $this->handler,
default => throw new \RuntimeException('Unknown status'),
}
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
use OpenAPITools\Generator\Utils\Builder\MatchBuilder;
$match = MatchBuilder::onClassNameStrings('className', [
[
'classNames' => ['\\Vendor\\Schema\\Foo', '\\Vendor\\Schema\\Bar'],
'body' => ExpressionBuilder::methodCall(
ExpressionBuilder::thisMethod('getObjectMapperUsers'),
'hydrateObject',
['className', 'payload'],
),
],
], ExpressionBuilder::throwRuntimeException('Unknown class'));
$printer->prettyPrintExpr($match);
// generates into
match ($className) {
'\\Vendor\\Schema\\Foo', '\\Vendor\\Schema\\Bar' => $this->getObjectMapperUsers()->hydrateObject($className, $payload),
default => throw new \RuntimeException('Unknown class'),
}
use OpenAPITools\Generator\Utils\Builder\ExpressionBuilder;
use OpenAPITools\Generator\Utils\Builder\HydrationBuilder;
$call = HydrationBuilder::hydrateCall(
'\\Vendor\\Schema\\User',
ExpressionBuilder::var('data'),
ExpressionBuilder::var('hydrator'),
);
$printer->prettyPrintExpr($call);
// generates into
$hydrator->hydrate(\Vendor\Schema\User::class, $data)
$fromArray = HydrationBuilder::hydrateCall(
'\\Vendor\\Schema\\User',
ExpressionBuilder::var('data'),
ExpressionBuilder::var('hydrator'),
'fromArray',
);
$printer->prettyPrintExpr($fromArray);
// generates into
$hydrator->fromArray(\Vendor\Schema\User::class, $data)
use OpenAPITools\Generator\Utils\Builder\NamespaceBuilder;
use PhpParser\BuilderFactory;
use PhpParser\PrettyPrinter\Standard;
$builderFactory = new BuilderFactory();
$namespaceBuilder = new NamespaceBuilder($builderFactory);
$classNode = $builderFactory->class('Example')->makeFinal()->getNode();
$namespace = $namespaceBuilder->namespaceNode('Vendor\\Api', $classNode);
$printer = new Standard();
$printer->prettyPrint([$namespace]);
// generates into
namespace Vendor\Api;
final class Example
{
}
use OpenAPITools\Generator\Utils\Builder\NamespaceBuilder;
use OpenAPITools\Utils\ClassString;
use OpenAPITools\Utils\File;
use OpenAPITools\Utils\Namespace_;
use PhpParser\BuilderFactory;
$builderFactory = new BuilderFactory();
$classString = ClassString::factory(
new Namespace_('Vendor\\Api', 'Vendor\\Tests\\Api'),
'Schema\\User',
);
$classNode = $builderFactory->class($classString->className)->makeFinal()->getNode();
$file = new NamespaceBuilder($builderFactory)->classFile(
'src',
$classString,
$classNode,
File::DO_LOAD_ON_WRITE,
);
// generates into
$file->pathPrefix === 'src'
$file->fqcn === 'Schema\\User'
$file->loadOnWrite === true
$file->contents is a namespace node wrapping the class
use OpenAPITools\Generator\Utils\Type\UnionTypeUtils;
use OpenAPITools\Representation\Namespaced\Property\Type;
$typeString = UnionTypeUtils::buildUnionType(new Type('union', [
new Type('string', 'string', null, [], false),
new Type('string', 'int', null, [], false),
new Type('object', $schema, null, [], false),
], false));
// generates into
'string|int|\\Vendor\\Schema\\User'
use OpenAPITools\Generator\Utils\Type\UnionTypeUtils;
$schemaClasses = [...UnionTypeUtils::getUnionTypeSchemas($property->type)];
foreach ($schemaClasses as $schema) {
yield from SingleCastUnionToType::generate(
$builderFactory,
$pathPrefix,
$castToUnionToType,
$schema,
);
}
use OpenAPITools\Generator\Utils\Type\DocBlockTag;
use OpenAPITools\Generator\Utils\Type\PropertyTypeResolver;
// Promoted property / class docblock (default)
$resolved = PropertyTypeResolver::resolve($property);
$resolved->typeHints;
// generates into
['string|int']
$resolved->nullablePrefix;
// generates into
'null|'
$resolved->docBlockLine;
// generates into
'@property null|string|int $value'
$resolved->typeHint();
// generates into
'null|string|int'
// Constructor parameter docblock
$param = PropertyTypeResolver::resolve($property, DocBlockTag::Param);
$param->docBlockLine;
// generates into
'@param ?array<\\Vendor\\Schema\\Item> $items'
$param->typeHint();
// generates into
'?array'
// Apply to a generated constructor parameter
$constructorParam = $builderFactory->param($property->name)->makePublic();
if ($param->docBlockLine !== '') {
$constructDocBlock[] = $param->docBlockLine;
}
if ($param->typeHint() !== '') {
$constructorParam->setType($param->typeHint());
}