Skip to content

Commit

Permalink
feat: Add OpenApiClientGenerator initial
Browse files Browse the repository at this point in the history
  • Loading branch information
il-masaru-yamagishi committed Nov 6, 2023
1 parent bd65395 commit d64b4cb
Show file tree
Hide file tree
Showing 7 changed files with 236 additions and 23 deletions.
3 changes: 3 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,6 @@ tab_width = 4

[composer.json]
indent_size = 4

[*.actual]
trim_trailing_whitespace = false
77 changes: 70 additions & 7 deletions src/Scenario/Generator/ApiClientMethod.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,20 @@

namespace Heavyrain\Scenario\Generator;

use cebe\openapi\spec\MediaType;
use cebe\openapi\spec\Operation;
use cebe\openapi\spec\Parameter;
use cebe\openapi\spec\Schema;
use Stringable;
use cebe\openapi\spec\RequestBody;

/**
* Api client method definition
*/
final class ApiClientMethod implements Stringable
{
private const STUB = <<<'EOL'
public function {{ methodName }}({{ parameters }}): AssertableResponseInterface
{{ description }}public function {{ methodName }}({{ parameters }}): AssertableResponseInterface
{
return $this->client->requestWithOptions({{ options }});
}
Expand All @@ -36,7 +38,15 @@ public function {{ methodName }}({{ parameters }}): AssertableResponseInterface
* @psalm-var array<string, array{type: string, name: string, required: bool}> $query
*/
private readonly array $query;
private readonly ?string $body;
/**
* @var array $query
* @psalm-var array{type: string, name: string, required: bool} $query
*/
private readonly ?array $body;
/**
* @var array $query
* @psalm-var array{type: string, name: string, required: bool} $query
*/
private readonly ?array $json;

/**
Expand All @@ -45,6 +55,8 @@ public function {{ methodName }}({{ parameters }}): AssertableResponseInterface
*/
private readonly array $parameters;

private readonly string $descritpion;

public function __construct(
public readonly string $path,
public readonly string $method,
Expand All @@ -54,8 +66,8 @@ public function __construct(
$pathArgs = [];
$parameters = [];
$query = [];
$this->body = null;
$this->json = null;
$body = null;
$json = null;

// Add from parameters
foreach ($this->operation->parameters as $parameter) {
Expand Down Expand Up @@ -93,18 +105,63 @@ public function __construct(
}
$this->pathArgs = $pathArgs;
$this->query = $query;
$this->parameters = $parameters;

// Add from requestBody
if ($this->operation->requestBody) {
\assert($this->operation->requestBody instanceof RequestBody);
if ($this->operation->requestBody->content) {
foreach ($this->operation->requestBody->content as $contentType => $mediaType) {
\assert(\is_null($mediaType->schema) || $mediaType->schema instanceof Schema);
if ($contentType === 'application/json') {
$type = [
'type' => 'array', // TODO: support nested array
'name' => 'body',
'required' => true,
];
$json = $type;
$parameters['body'] = $type;
} else {
$type = [
'type' => 'string', // TODO: support array
'name' => 'body',
'required' => false,
];
$body = $type;
$parameters['body'] = $type;
}
}
}
}
$this->json = $json;
$this->body = $body;
$this->parameters = $parameters;

// Add description
{
$description = '';
if ($this->operation->summary) {
$description .= \sprintf(" * %s\n", $this->operation->summary);
}
if ($this->operation->description) {
$description .= " *\n";
$description .= \sprintf(" * %s\n", \str_replace(["\r", "\n"], ' ', $this->operation->description));
}
if ($description !== '') {
$description = \sprintf(" /**\n%s */\n", $description);
}
$this->descritpion = \sprintf('%s ', $description);
}
}

public function __toString(): string
{
return \str_replace([
'{{ description }}',
'{{ methodName }}',
'{{ parameters }}',
'{{ options }}',
], [
$this->descritpion,
$this->getMethodName(),
$this->getParameters(),
$this->getOptions(),
Expand Down Expand Up @@ -207,12 +264,18 @@ private function getQuery(): string

private function getBody(): string
{
return 'null';
if (\is_null($this->body)) {
return 'null';
}
return \sprintf('$%s', $this->body['name']);
}

private function getJson(): string
{
return 'null';
if (\is_null($this->json)) {
return 'null';
}
return \sprintf('$%s', $this->json['name']);
}

private function getAssertsOk(): string
Expand Down
39 changes: 31 additions & 8 deletions src/Scenario/Generator/OpenApiClientGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,32 @@
*/
final class OpenApiClientGenerator
{
private const STUB = <<<'EOL'
<?php
/**
* Generated by Heavyrain OpenApiClientGenerator.
*/
declare(strict_types=1);
use Heavyrain\Contracts\AssertableResponseInterface;
use Heavyrain\Contracts\ClientInterface;
/**
* OpenAPI-based ApiClient.
*/
class ApiClient
{
public function __construct(protected readonly ClientInterface $client)
{
}
{{ methods }}
}

EOL
;
/**
* Generates an ApiClient class from an OpenAPI schema.
* @param OpenApi $openApiSchema
Expand All @@ -26,12 +52,8 @@ public function generate(OpenApi $openApiSchema): string
$this->ensureSupportedVersion($openApiSchema->openapi);
$methods = $this->generateMethods($openApiSchema);

$clientStub = \file_get_contents(__DIR__ . '/Stubs/ApiClient.stub');

return $this->generateFromStub(
$openApiSchema,
$methods,
$clientStub,
);
}

Expand Down Expand Up @@ -85,12 +107,13 @@ private function generateMethods(OpenApi $openApiSchema): array

/**
* Generates ApiClient class file contents from stubs.
* @param OpenApi $openApiSchema
* @param array $methods
* @param string $clientStub
* @param ApiClientMethod[] $methods
* @return string
*/
private function generateFromStub(OpenApi $openApiSchema, array $methods, string $clientStub): string
private function generateFromStub(array $methods): string
{
$methods = \implode(PHP_EOL, $methods);

return \str_replace('{{ methods }}', $methods, self::STUB);
}
}
4 changes: 0 additions & 4 deletions src/Scenario/Generator/Stubs/ApiClientMethod.stub

This file was deleted.

38 changes: 35 additions & 3 deletions tests/Stubs/PetStoreApiClient.actual
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,44 @@ use Heavyrain\Contracts\ClientInterface;
*/
class ApiClient
{
public function __construct(private readonly ClientInterface $client)
public function __construct(protected readonly ClientInterface $client)
{
}

public function {{ methodName }}({{ parameters }}): AssertableResponseInterface
/**
*
* Returns all pets from the system that the user has access to Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia. Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.
*/
public function findPets(array $tags, int $limit): AssertableResponseInterface
{
return $this->client->requestWithOptions({{ options }});
return $this->client->requestWithOptions(method: 'get', path: '/pets', pathArgs: null, query: ['tags' => $tags, 'limit' => $limit], body: null, json: null, assertsOk: true);
}

/**
*
* Creates a new pet in the store. Duplicates are allowed
*/
public function addPet(array $body): AssertableResponseInterface
{
return $this->client->requestWithOptions(method: 'post', path: '/pets', pathArgs: null, query: null, body: null, json: $body, assertsOk: true);
}

/**
*
* Returns a user based on a single ID, if the user does not have access to the pet
*/
public function findPetById(int $id): AssertableResponseInterface
{
return $this->client->requestWithOptions(method: 'get', path: '/pets/{id}', pathArgs: ['id' => $id], query: null, body: null, json: null, assertsOk: true);
}

/**
*
* deletes a single pet based on the ID supplied
*/
public function deletePet(int $id): AssertableResponseInterface
{
return $this->client->requestWithOptions(method: 'delete', path: '/pets/{id}', pathArgs: ['id' => $id], query: null, body: null, json: null, assertsOk: true);
}

}
96 changes: 96 additions & 0 deletions tests/Unit/Scenario/Generator/ApiClientMethodTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,102 @@ public function getWeapon(int $id): AssertableResponseInterface
return $this->client->requestWithOptions(method: 'get', path: '/weapon', pathArgs: null, query: ['id' => $id], body: null, json: null, assertsOk: true);
}

EOL
],
'post query /todo/add' => [
'path' => '/todo/add',
'method' => 'post',
'operation' => new Operation([
'operationId' => 'AddTodo',
'requestBody' => [
'content' => [
'application/x-www-form-urlencoded' => [
'schema' => [
'type' => 'object',
'properties' => [
'title' => [
'type' => 'string',
],
'description' => [
'type' => 'string',
],
],
'required' => [
'title',
],
],
],
],
],
]),
'assertsOk' => true,
'expected' => <<<'EOL'
public function addTodo(string $body): AssertableResponseInterface
{
return $this->client->requestWithOptions(method: 'post', path: '/todo/add', pathArgs: null, query: null, body: $body, json: null, assertsOk: true);
}

EOL
],
'post query /todo/update' => [
'path' => '/todo/update',
'method' => 'post',
'operation' => new Operation([
'operationId' => 'UpdateTodo',
'requestBody' => [
'content' => [
'application/json' => [
'schema' => [
'type' => 'object',
'properties' => [
'title' => [
'type' => 'string',
],
'description' => [
'type' => 'string',
],
],
'required' => [
'title',
'description',
],
],
],
],
],
]),
'assertsOk' => true,
'expected' => <<<'EOL'
public function updateTodo(array $body): AssertableResponseInterface
{
return $this->client->requestWithOptions(method: 'post', path: '/todo/update', pathArgs: null, query: null, body: null, json: $body, assertsOk: true);
}

EOL
],
'has Description get /' => [
'path' => '/',
'method' => 'get',
'operation' => new Operation([
'summary' => 'Get root',
'description' => <<<'EOL'
Get parameters from root
2nd line
EOL
,
]),
'assertsOk' => true,
'expected' => <<<'EOL'
/**
* Get root
*
* Get parameters from root 2nd line
*/
public function get(): AssertableResponseInterface
{
return $this->client->requestWithOptions(method: 'get', path: '/', pathArgs: null, query: null, body: null, json: null, assertsOk: true);
}

EOL
],
];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ final class OpenApiClientGeneratorTest extends TestCase
#[Test]
public function testGenerate(): void
{
$openapi = Reader::readFromYamlFile(__DIR__ . '/../../../Stubs/petstore3.0.0.0.yaml');
$openapi = Reader::readFromYamlFile(__DIR__ . '/../../../Stubs/petstore3.0.0.yaml');

$actual = (new OpenApiClientGenerator())->generate($openapi);

Expand Down

0 comments on commit d64b4cb

Please sign in to comment.