Skip to content

[Swagger] Added support for customizing the Definition key #1607

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

Merged
merged 1 commit into from
Dec 26, 2017
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
3 changes: 3 additions & 0 deletions src/Serializer/SerializerContextBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use ApiPlatform\Core\Api\OperationType;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use Symfony\Component\HttpFoundation\Request;

Expand Down Expand Up @@ -92,6 +93,8 @@ public function createFromRequest(Request $request, bool $normalization, array $
$context['subresource_resource_class'] = $attributes['subresource_resource_class'] ?? null;
}

unset($context[DocumentationNormalizer::SWAGGER_DEFINITION_NAME]);

return $context;
}
}
7 changes: 6 additions & 1 deletion src/Swagger/Serializer/DocumentationNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ final class DocumentationNormalizer implements NormalizerInterface

const SWAGGER_VERSION = '2.0';
const FORMAT = 'json';
const SWAGGER_DEFINITION_NAME = 'swagger_definition_name';

private $resourceMetadataFactory;
private $propertyNameCollectionFactory;
Expand Down Expand Up @@ -445,7 +446,11 @@ private function updateDeleteOperation(\ArrayObject $pathOperation, string $reso
*/
private function getDefinition(\ArrayObject $definitions, ResourceMetadata $resourceMetadata, string $resourceClass, array $serializerContext = null): string
{
$definitionKey = $this->getDefinitionKey($resourceMetadata->getShortName(), (array) ($serializerContext[AbstractNormalizer::GROUPS] ?? []));
if (isset($serializerContext[self::SWAGGER_DEFINITION_NAME])) {
$definitionKey = sprintf('%s-%s', $resourceMetadata->getShortName(), $serializerContext[self::SWAGGER_DEFINITION_NAME]);
} else {
$definitionKey = $this->getDefinitionKey($resourceMetadata->getShortName(), (array) ($serializerContext[AbstractNormalizer::GROUPS] ?? []));
}

if (!isset($definitions[$definitionKey])) {
$definitions[$definitionKey] = []; // Initialize first to prevent infinite loop
Expand Down
6 changes: 5 additions & 1 deletion tests/Serializer/SerializerContextBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
use ApiPlatform\Core\Serializer\SerializerContextBuilder;
use ApiPlatform\Core\Swagger\Serializer\DocumentationNormalizer;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;

Expand All @@ -37,7 +38,10 @@ protected function setUp()
null,
[],
[],
['normalization_context' => ['foo' => 'bar'], 'denormalization_context' => ['bar' => 'baz']]
[
'normalization_context' => ['foo' => 'bar', DocumentationNormalizer::SWAGGER_DEFINITION_NAME => 'MyDefinition'],
'denormalization_context' => ['bar' => 'baz'],
]
);

$resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class);
Expand Down
94 changes: 94 additions & 0 deletions tests/Swagger/Serializer/DocumentationNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,100 @@ public function testNormalizeWithOnlyNormalizationGroups()
$this->assertEquals($expected, $normalizer->normalize($documentation));
}

public function testNormalizeWithSwaggerDefinitionName()
{
$documentation = new Documentation(new ResourceNameCollection([Dummy::class]), 'Test API', 'This is a test API.', '1.2.3', ['jsonld' => ['application/ld+json']]);

$propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
$propertyNameCollectionFactoryProphecy->create(Dummy::class, [])->shouldBeCalled()->willReturn(new PropertyNameCollection(['id']));

$dummyMetadata = new ResourceMetadata(
'Dummy',
'This is a dummy.',
'http://schema.example.com/Dummy',
[
'get' => [
'method' => 'GET',
'normalization_context' => [
DocumentationNormalizer::SWAGGER_DEFINITION_NAME => 'Read',
],
],
]
);
$resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class);
$resourceMetadataFactoryProphecy->create(Dummy::class)->shouldBeCalled()->willReturn($dummyMetadata);

$propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);
$propertyMetadataFactoryProphecy->create(Dummy::class, 'id')->shouldBeCalled()->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_INT), 'This is an id.', true, false));
$resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class);
$resourceClassResolverProphecy->isResourceClass(Dummy::class)->willReturn(true);

$operationMethodResolverProphecy = $this->prophesize(OperationMethodResolverInterface::class);
$operationMethodResolverProphecy->getItemOperationMethod(Dummy::class, 'get')->shouldBeCalled()->willReturn('GET');

$operationPathResolver = new CustomOperationPathResolver(new OperationPathResolver(new UnderscorePathSegmentNameGenerator()));

$normalizer = new DocumentationNormalizer(
$resourceMetadataFactoryProphecy->reveal(),
$propertyNameCollectionFactoryProphecy->reveal(),
$propertyMetadataFactoryProphecy->reveal(),
$resourceClassResolverProphecy->reveal(),
$operationMethodResolverProphecy->reveal(),
$operationPathResolver
);

$expected = [
'swagger' => '2.0',
'basePath' => '/app_dev.php/',
'info' => [
'title' => 'Test API',
'description' => 'This is a test API.',
'version' => '1.2.3',
],
'paths' => new \ArrayObject([
'/dummies/{id}' => [
'get' => new \ArrayObject([
'tags' => ['Dummy'],
'operationId' => 'getDummyItem',
'produces' => ['application/ld+json'],
'summary' => 'Retrieves a Dummy resource.',
'parameters' => [
[
'name' => 'id',
'in' => 'path',
'type' => 'string',
'required' => true,
],
],
'responses' => [
200 => [
'description' => 'Dummy resource response',
'schema' => ['$ref' => '#/definitions/Dummy-Read'],
],
404 => ['description' => 'Resource not found'],
],
]),
],
]),
'definitions' => new \ArrayObject([
'Dummy-Read' => new \ArrayObject([
'type' => 'object',
'description' => 'This is a dummy.',
'externalDocs' => ['url' => 'http://schema.example.com/Dummy'],
'properties' => [
'id' => new \ArrayObject([
'type' => 'integer',
'description' => 'This is an id.',
'readOnly' => true,
]),
],
]),
]),
];

$this->assertEquals($expected, $normalizer->normalize($documentation, DocumentationNormalizer::FORMAT, ['base_url' => '/app_dev.php/']));
}

public function testNormalizeWithOnlyDenormalizationGroups()
{
$title = 'Test API';
Expand Down