Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@
"ringcentral/psr7": "^1.3",
"symfony/yaml": "^5.4",
"wyrihaximus/composer-update-bin-autoload-path": "^1 || ^1.0.1",
"wyrihaximus/hydrator": "dev-master",
"league/openapi-psr7-validator": "^0.16",
"react/http": "^1.8",
"reactivex/rxphp": "^2.0",
"api-clients/contracts": "dev-main"
"api-clients/contracts": "dev-main",
"eventsauce/object-hydrator": "^1.1"
},
"autoload": {
"psr-4": {
Expand Down
587 changes: 63 additions & 524 deletions composer.lock

Large diffs are not rendered by default.

21 changes: 4 additions & 17 deletions src/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,9 @@

final class File
{
private string $fqcn;
private Node $contents;

public function __construct(string $path, Node $contents)
{
$this->fqcn = $path;
$this->contents = $contents;
}

public function fqcn(): string
{
return $this->fqcn;
}

public function contents(): Node
{
return $this->contents;
public function __construct(
public readonly string $fqcn,
public readonly Node|string $contents,
){
}
}
32 changes: 22 additions & 10 deletions src/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
use ApiClients\Tools\OpenApiClientGenerator\Generator\WebHooks;
use cebe\openapi\Reader;
use cebe\openapi\spec\OpenApi;
use EventSauce\ObjectHydrator\ObjectMapperCodeGenerator;
use Jawira\CaseConverter\Convert;
use League\ConstructFinder\ConstructFinder;
use PhpParser\Node;
use PhpParser\PrettyPrinter\Standard;

final class Generator
Expand All @@ -31,16 +34,17 @@ public function generate(string $namespace, string $destinationPath)
$namespace = self::cleanUpNamespace($namespace);
$codePrinter = new Standard();

foreach ($this->all($namespace) as $file) {
$fileName = $destinationPath . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, substr($file->fqcn(), strlen($namespace)));
foreach ($this->all($namespace, $destinationPath . DIRECTORY_SEPARATOR) as $file) {
$fileName = $destinationPath . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, substr($file->fqcn, strlen($namespace)));
@mkdir(dirname($fileName), 0744, true);
file_put_contents($fileName . '.php', $codePrinter->prettyPrintFile([$file->contents()]) . PHP_EOL);
file_put_contents($fileName . '.php', ($file->contents instanceof Node ? $codePrinter->prettyPrintFile([$file->contents]) : $file->contents) . PHP_EOL);
include_once $fileName . '.php';
}
}

public static function className(string $className): string
{
return str_replace(['{', '}', '-', '$', '_', '+'], ['Cb', 'Rcb', 'Dash', '_', '\\', 'Plus'], (new Convert($className))->toPascal()) . (self::isKeyword(self::basename($className)) ? '_' : '');
return str_replace(['{', '}', '-', '$', '_', '+', '*', '.'], ['Cb', 'Rcb', 'Dash', '_', '\\', 'Plus', 'Obelix', 'Dot'], (new Convert($className))->toPascal()) . (self::isKeyword(self::basename($className)) ? '_' : '');
}

private static function cleanUpNamespace(string $namespace): string
Expand All @@ -56,8 +60,9 @@ private static function cleanUpNamespace(string $namespace): string
* @param string $destinationPath
* @return iterable<File>
*/
private function all(string $namespace): iterable
private function all(string $namespace, string $rootPath): iterable
{
$schemaClasses = [];
$schemaRegistry = new SchemaRegistry();
if (count($this->spec->components->schemas ?? []) > 0) {
foreach ($this->spec->components->schemas as $name => $schema) {
Expand All @@ -73,6 +78,7 @@ private function all(string $namespace): iterable
continue;
}

$schemaClasses[] = $namespace . 'Schema/' . $schemaClassName;
yield from Schema::generate(
$name,
self::dirname($namespace . 'Schema/' . $schemaClassName),
Expand Down Expand Up @@ -134,6 +140,7 @@ private function all(string $namespace): iterable
yield from Clients::generate(
$operationGroup,
self::dirname($namespace . 'Operation/' . $operationGroup),
$namespace,
self::basename($namespace . 'Operation/' . $operationGroup),
$operations,
);
Expand Down Expand Up @@ -166,10 +173,6 @@ private function all(string $namespace): iterable
);
}

yield from WebHookInterface::generate(
self::dirname($namespace . 'WebHookInterface'),
'WebHookInterface',
);
yield from WebHooks::generate(
self::dirname($namespace . 'WebHooks'),
$namespace,
Expand All @@ -179,6 +182,7 @@ private function all(string $namespace): iterable

while ($schemaRegistry->hasUnknownSchemas()) {
foreach ($schemaRegistry->unknownSchemas() as $schema) {
$schemaClasses[] = $namespace . 'Schema/' . $schema['className'];
yield from Schema::generate(
$schema['name'],
self::dirname($namespace . 'Schema/' . $schema['className']),
Expand All @@ -189,6 +193,14 @@ private function all(string $namespace): iterable
);
}
}

yield new File(
$namespace . 'OptimizedHydratorMapper',
(new ObjectMapperCodeGenerator())->dump(
array_unique(array_filter(array_map(static fn (string $className): string => str_replace('/', '\\', $className), $schemaClasses), static fn (string $className): bool => count((new \ReflectionMethod($className, '__construct'))->getParameters()) > 0)),
$namespace . 'OptimizedHydratorMapper'
)
);
}

private static function fqcn(string $fqcn): string
Expand All @@ -212,6 +224,6 @@ public static function basename(string $fqcn): string

private static function isKeyword(string $name): bool
{
return in_array(strtolower($name), array('__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor', 'self'), false);
return in_array(strtolower($name), array('__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor', 'self', 'parent', 'object'), false);
}
}
18 changes: 18 additions & 0 deletions src/Generator/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public static function generate(string $namespace, array $clients, SchemaRegistr
$factory->property('requestSchemaValidator')->setType('\League\OpenAPIValidation\Schema\SchemaValidator')->makeReadonly()->makePrivate()
)->addStmt(
$factory->property('responseSchemaValidator')->setType('\League\OpenAPIValidation\Schema\SchemaValidator')->makeReadonly()->makePrivate()
)->addStmt(
$factory->property('hydrator')->setType('\\' . $namespace . 'OptimizedHydratorMapper')->makeReadonly()->makePrivate()
)->addStmt(
$factory->method('__construct')->makePublic()->addParam(
(new Param('authentication'))->setType('\\' . AuthenticationInterface::class)
Expand Down Expand Up @@ -98,6 +100,18 @@ public static function generate(string $namespace, array $clients, SchemaRegistr
]
),
)
)->addStmt(
new Node\Expr\Assign(
new Node\Expr\PropertyFetch(
new Node\Expr\Variable('this'),
'hydrator'
),
new Node\Expr\New_(
new Node\Name('\\' . $namespace . 'OptimizedHydratorMapper'),
[
]
),
)
)
);

Expand Down Expand Up @@ -149,6 +163,10 @@ public static function generate(string $namespace, array $clients, SchemaRegistr
new Node\Expr\Variable('this'),
'responseSchemaValidator'
)),
new Node\Arg(new Node\Expr\PropertyFetch(
new Node\Expr\Variable('this'),
'hydrator'
)),
]
)
)
Expand Down
18 changes: 17 additions & 1 deletion src/Generator/Clients.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ final class Clients
* @param array<string, string> $operations
* @return iterable<Node>
*/
public static function generate(string $operationGroup, string $namespace, string $className, array $operations): iterable
public static function generate(string $operationGroup, string $namespace, string $rootNamespace, string $className, array $operations): iterable
{
$factory = new BuilderFactory();
$stmt = $factory->namespace($namespace);
Expand All @@ -26,6 +26,8 @@ public static function generate(string $operationGroup, string $namespace, strin
$factory->property('requestSchemaValidator')->setType('\League\OpenAPIValidation\Schema\SchemaValidator')->makeReadonly()->makePrivate()
)->addStmt(
$factory->property('responseSchemaValidator')->setType('\League\OpenAPIValidation\Schema\SchemaValidator')->makeReadonly()->makePrivate()
)->addStmt(
$factory->property('hydrator')->setType('\\' . $rootNamespace . 'OptimizedHydratorMapper')->makeReadonly()->makePrivate()
)->addStmt(
$factory->method('__construct')->makePublic()->addParam(
(new Param('requestSchemaValidator'))->setType('\League\OpenAPIValidation\Schema\SchemaValidator')
Expand All @@ -47,6 +49,16 @@ public static function generate(string $operationGroup, string $namespace, strin
),
new Node\Expr\Variable('responseSchemaValidator'),
)
)->addParam(
(new Param('hydrator'))->setType('\\' . $rootNamespace . 'OptimizedHydratorMapper')
)->addStmt(
new Node\Expr\Assign(
new Node\Expr\PropertyFetch(
new Node\Expr\Variable('this'),
'hydrator'
),
new Node\Expr\Variable('hydrator'),
)
)
);

Expand All @@ -60,6 +72,10 @@ public static function generate(string $operationGroup, string $namespace, strin
new Node\Expr\Variable('this'),
'responseSchemaValidator'
);
$params[] = new Node\Expr\PropertyFetch(
new Node\Expr\Variable('this'),
'hydrator'
);
$cn = str_replace('/', '\\', '\\' . $namespace . '\\' . $operationDetails['class']);
$method = $factory->method(lcfirst($operationOperation))->setReturnType($cn)->makePublic();
foreach ($operationDetails['operation']->parameters as $parameter) {
Expand Down
26 changes: 18 additions & 8 deletions src/Generator/Operation.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ public static function generate(string $path, string $method, string $namespace,
$factory->property('requestSchemaValidator')->setType('\League\OpenAPIValidation\Schema\SchemaValidator')->makeReadonly()->makePrivate()
)->addStmt(
$factory->property('responseSchemaValidator')->setType('\League\OpenAPIValidation\Schema\SchemaValidator')->makeReadonly()->makePrivate()
)->addStmt(
$factory->property('hydrator')->setType('\\' . $rootNamespace . 'OptimizedHydratorMapper')->makeReadonly()->makePrivate()
);

$constructor = $factory->method('__construct')->makePublic()->addParam(
Expand All @@ -94,6 +96,16 @@ public static function generate(string $path, string $method, string $namespace,
),
new Node\Expr\Variable('responseSchemaValidator'),
)
)->addParam(
(new Param('hydrator'))->setType('\\' . $rootNamespace . 'OptimizedHydratorMapper')
)->addStmt(
new Node\Expr\Assign(
new Node\Expr\PropertyFetch(
new Node\Expr\Variable('this'),
'hydrator'
),
new Node\Expr\Variable('hydrator'),
)
);
$requestReplaces = [];
$query = [];
Expand All @@ -113,7 +125,7 @@ public static function generate(string $path, string $method, string $namespace,
'bool',
], implode('|', is_array($parameter->schema->type) ? $parameter->schema->type : [$parameter->schema->type])));
}
$class->addStmt($paramterStmt->makeReadonly()->makePrivate());
$class->addStmt($paramterStmt->makePrivate());

$param = new Param($parameter->name);
if ($parameter->schema->type !== null) {
Expand Down Expand Up @@ -225,8 +237,11 @@ public static function generate(string $path, string $method, string $namespace,
$returnType[] = ($contentTypeSchema->schema->type === 'array' ? '\\' . Observable::class . '<' : '') . $object . ($contentTypeSchema->schema->type === 'array' ? '>' : '');
$returnTypeRaw[] = $contentTypeSchema->schema->type === 'array' ? '\\' . Observable::class : $object;
$hydrate = new Node\Expr\MethodCall(
new Node\Expr\Variable('hydrator'),
new Node\Name('hydrate'),
new Node\Expr\PropertyFetch(
new Node\Expr\Variable('this'),
'hydrator'
),
new Node\Name('hydrateObject'),
[
new Node\Arg(new Node\Scalar\String_($object)),
new Node\Arg(new Node\Expr\Variable('body')),
Expand Down Expand Up @@ -277,9 +292,6 @@ public static function generate(string $path, string $method, string $namespace,
'params' => [
new Node\Param(new Node\Expr\Variable('body'), null, new Node\Name('array'))
],
'uses' => [
new Node\Expr\Variable('hydrator'),
],
'returnType' => $object,
]))
]
Expand Down Expand Up @@ -320,8 +332,6 @@ public static function generate(string $path, string $method, string $namespace,
new Node\Expr\Assign(new Node\Expr\Variable('contentType'), new Node\Expr\MethodCall(new Node\Expr\Variable('response'), 'getHeaderLine', [new Arg(new Node\Scalar\String_('Content-Type'))]))
)->addStmt(
new Node\Expr\Assign(new Node\Expr\Variable('body'), new Node\Expr\FuncCall(new Node\Name('json_decode'), [new Node\Expr\MethodCall(new Node\Expr\MethodCall(new Node\Expr\Variable('response'), 'getBody'), 'getContents'), new Node\Expr\ConstFetch(new Node\Name('true'))]))
)->addStmt(
new Node\Expr\Assign(new Node\Expr\Variable('hydrator'), new Node\Expr\New_(new Node\Name('\\' . Hydrator::class)))
)->addStmt(
new Node\Stmt\Switch_(
new Node\Expr\MethodCall(new Node\Expr\Variable('response'), 'getStatusCode'),
Expand Down
Loading