Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for generation open-api schema references by transformers #139

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) princip

## [Unreleased][unreleased]

### Added

* Support for automatic generation open-api schema references by transformers

## 2.11.0

### Added
Expand Down
40 changes: 36 additions & 4 deletions src/Handlers/OpenApiHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
namespace Tomaj\NetteApi\Handlers;

use InvalidArgumentException;
use League\Fractal\TransformerAbstract;
use Nette\Application\UI\InvalidLinkException;
use Nette\Http\IResponse;
use Nette\Http\Request;
use ReflectionClass;
use Symfony\Component\Yaml\Yaml;
use Tomaj\NetteApi\Api;
use Tomaj\NetteApi\ApiDecider;
Expand Down Expand Up @@ -40,6 +42,9 @@ class OpenApiHandler extends BaseHandler
/** @var Request */
private $request;

/** @var TransformerAbstract[] */
private $transformers = [];

private $initData = [];

private $definitions = [];
Expand All @@ -49,18 +54,21 @@ class OpenApiHandler extends BaseHandler
* @param ApiDecider $apiDecider
* @param ApiLink $apiLink
* @param Request $request
* @param TransformerAbstract[] $transformers
* @param array $initData - structured data for initialization response
*/
public function __construct(
ApiDecider $apiDecider,
ApiLink $apiLink,
Request $request,
array $transformers = [],
array $initData = []
) {
parent::__construct();
$this->apiDecider = $apiDecider;
$this->apiLink = $apiLink;
$this->request = $request;
$this->transformers = $transformers;
$this->initData = $initData;
}

Expand Down Expand Up @@ -219,6 +227,8 @@ public function handle(array $params): ResponseInterface
$data['components']['schemas'] = array_merge($this->definitions, $data['components']['schemas']);
}

$this->linkTransformerSchemas($data);

$data = array_replace_recursive($data, $this->initData);

if ($params['format'] === 'yaml') {
Expand Down Expand Up @@ -257,7 +267,7 @@ private function getPaths(array $versionApis, string $baseUrl, string $basePath)
'application/json; charset=utf-8' => [
'schema' => $schema,
],
]
],
];
}

Expand All @@ -269,9 +279,9 @@ private function getPaths(array $versionApis, string $baseUrl, string $basePath)
'description' => $output->getDescription(),
'schema' => [
'type' => 'string',
]
],
],
]
],
];
}
}
Expand All @@ -297,7 +307,7 @@ private function getPaths(array $versionApis, string $baseUrl, string $basePath)
'schema' => [
'$ref' => '#/components/schemas/ErrorWrongInput',
],
]
],
],
];
}
Expand Down Expand Up @@ -609,4 +619,26 @@ private function normalizeSecuritySchemeName(string $type, string $name): string
{
return 'api_key__' . $type . '__' . strtolower(str_replace('-', '_', $name));
}

private function linkTransformerSchemas(&$data)
{
$processedRefs = [];
foreach ($this->transformers as $transformer) {
if (!method_exists($transformer, 'schema')) {
continue;
}
$stringForReplace = json_encode($this->transformSchema($transformer->schema()));
if (in_array(md5($stringForReplace), $processedRefs)) {
continue;
}
$componentName = (new ReflectionClass($transformer))->getShortName();
if (strlen($componentName) > 11 && substr($componentName, -11) === 'Transformer') {
$componentName = substr($componentName, 0, -11);
}
$data['components']['schemas'][$componentName] = $this->transformSchema($transformer->schema());
$processedRefs[] = md5($stringForReplace);

$data['paths'] = json_decode(str_replace($stringForReplace, '{"$ref": "#/components/schemas/' . $componentName . '"}', json_encode($data['paths'])), true);
}
}
}
97 changes: 97 additions & 0 deletions tests/Handler/OpenApiHandlerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Test\Handler;

use Nette\Application\LinkGenerator;
use Nette\Application\Routers\SimpleRouter;
use Nette\Http\Request;
use Nette\Http\UrlScript;
use PHPUnit\Framework\TestCase;
use Tomaj\NetteApi\ApiDecider;
use Tomaj\NetteApi\Authorization\NoAuthorization;
use Tomaj\NetteApi\EndpointIdentifier;
use Tomaj\NetteApi\Handlers\OpenApiHandler;
use Tomaj\NetteApi\Link\ApiLink;
use Tomaj\NetteApi\Test\Transformer\DummyTransformer;
use Tomaj\NetteApi\Test\Transformer\NoSchemaTransformer;
use Tomaj\NetteApi\Test\Transformer\NullSchemaTransformer;
use Tomaj\NetteApi\Test\Transformer\SameSchemaTransformer;

class OpenApiHandlerTest extends TestCase
{
public function testReferencesGeneration()
{
$linkGenerator = new LinkGenerator(new SimpleRouter([]), new UrlScript('http://test/'));
$apiLink = new ApiLink($linkGenerator);
$request = new Request(new UrlScript('http://test/'));

$dummyTransformer = new DummyTransformer();
$noSchemaTransformer = new NoSchemaTransformer();
$sameSchemaTransformer = new SameSchemaTransformer();
$nullSchemaTransformer = new NullSchemaTransformer();

$apiDecider = new ApiDecider();
$apiDecider->addApi(
new EndpointIdentifier('GET', 1, 'dummy'),
new TransformerTestHandler($dummyTransformer),
new NoAuthorization()
);
$apiDecider->addApi(
new EndpointIdentifier('GET', 1, 'toodummy'),
new TransformerTestHandler($dummyTransformer),
new NoAuthorization()
);
$apiDecider->addApi(
new EndpointIdentifier('GET', 1, 'sameschema'),
new TransformerTestHandler($sameSchemaTransformer),
new NoAuthorization()
);
$apiDecider->addApi(
new EndpointIdentifier('GET', 1, 'noschema'),
new TransformerTestHandler($noSchemaTransformer),
new NoAuthorization()
);
$apiDecider->addApi(
new EndpointIdentifier('GET', 1, 'nullschema'),
new TransformerTestHandler($nullSchemaTransformer),
new NoAuthorization()
);

$apiDecider->addApi(
new EndpointIdentifier('GET', 1, 'docs', 'open-api'),
new OpenApiHandler($apiDecider, $apiLink, $request, [$dummyTransformer, $noSchemaTransformer, $sameSchemaTransformer, $nullSchemaTransformer]),
new NoAuthorization()
);

$result = $apiDecider->getApi('GET', 1, 'docs', 'open-api');
$handler = $result->getHandler();

$response = $handler->handle(['format' => 'json']);
$this->assertEquals(200, $response->getCode());
$payload = $response->getPayload();

$this->assertEquals(6, count($payload['paths']));
$this->assertEquals(5, count($payload['components']['schemas']));

$def = array_values($payload['paths'])[0];
$this->assertSame($def['get']['responses'][200]['content']['application/json; charset=utf-8']['schema']['$ref'], '#/components/schemas/Dummy');
$this->assertSame($payload['components']['schemas']['Dummy']['properties']['id']['type'], 'string');

$def = array_values($payload['paths'])[1];
$this->assertSame($def['get']['responses'][200]['content']['application/json; charset=utf-8']['schema']['$ref'], '#/components/schemas/Dummy');
$this->assertSame($payload['components']['schemas']['Dummy']['properties']['id']['type'], 'string');

$def = array_values($payload['paths'])[2];
$this->assertSame($def['get']['responses'][200]['content']['application/json; charset=utf-8']['schema']['$ref'], '#/components/schemas/Dummy');
$this->assertSame($payload['components']['schemas']['Dummy']['properties']['id']['type'], 'string');

$def = array_values($payload['paths'])[3];
$this->assertSame($def['get']['responses'][200]['content']['application/json; charset=utf-8']['schema'], []);

$def = array_values($payload['paths'])[4];
$this->assertSame($def['get']['responses'][200]['content']['application/json; charset=utf-8']['schema']['$ref'], '#/components/schemas/NullSchema');
$this->assertSame($payload['components']['schemas']['Dummy']['properties']['id']['type'], 'string');
}
}
35 changes: 35 additions & 0 deletions tests/Handler/TransformerTestHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Test\Handler;

use League\Fractal\TransformerAbstract;
use Nette\Http\IResponse;
use Tomaj\NetteApi\Handlers\BaseHandler;
use Tomaj\NetteApi\Output\JsonOutput;
use Tomaj\NetteApi\Response\JsonApiResponse;
use Tomaj\NetteApi\Response\ResponseInterface;

class TransformerTestHandler extends BaseHandler
{
/** @var TransformerAbstract */
private $transformer;

public function __construct(TransformerAbstract $transformer)
{
$this->transformer = $transformer;
}

public function handle(array $params): ResponseInterface
{
return new JsonApiResponse(200, ['id' => 5]);
}

public function outputs(): array
{
return [
new JsonOutput(IResponse::S200_OK, json_encode(method_exists($this->transformer, 'schema') ? $this->transformer->schema() : []), 'Successful request'),
];
}
}
22 changes: 22 additions & 0 deletions tests/Transformer/DummyTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Test\Transformer;

use League\Fractal\TransformerAbstract;

class DummyTransformer extends TransformerAbstract
{
public function schema(): array
{
return [
'type' => 'object',
'properties' => [
'id' => [
'type' => 'string',
],
],
];
}
}
22 changes: 22 additions & 0 deletions tests/Transformer/DuplicateDummyTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Test\Transformer\Duplicate;

use League\Fractal\TransformerAbstract;

class DummyTransformer extends TransformerAbstract
{
public function schema(): array
{
return [
'type' => 'object',
'properties' => [
'id' => [
'type' => 'int',
],
],
];
}
}
11 changes: 11 additions & 0 deletions tests/Transformer/NoSchemaTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Test\Transformer;

use League\Fractal\TransformerAbstract;

class NoSchemaTransformer extends TransformerAbstract
{
}
22 changes: 22 additions & 0 deletions tests/Transformer/NullSchemaTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Test\Transformer;

use League\Fractal\TransformerAbstract;

class NullSchemaTransformer extends TransformerAbstract
{
public function schema(): array
{
return [
'type' => 'object',
'properties' => [
'id' => [
'type' => ['string', 'null'],
],
],
];
}
}
22 changes: 22 additions & 0 deletions tests/Transformer/SameSchemaTransformer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Test\Transformer;

use League\Fractal\TransformerAbstract;

class SameSchemaTransformer extends TransformerAbstract
{
public function schema(): array
{
return [
'type' => 'object',
'properties' => [
'id' => [
'type' => 'string',
],
],
];
}
}
Loading