Skip to content

input and output class refactoring #2483

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 3 commits into from
Feb 2, 2019
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
5 changes: 4 additions & 1 deletion src/Api/IdentifiersExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Util\ClassInfoTrait;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
Expand All @@ -33,13 +34,15 @@ final class IdentifiersExtractor implements IdentifiersExtractorInterface
private $propertyMetadataFactory;
private $propertyAccessor;
private $resourceClassResolver;
private $resourceMetadataFactory;

public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, PropertyAccessorInterface $propertyAccessor = null, ResourceClassResolverInterface $resourceClassResolver = null)
public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, PropertyAccessorInterface $propertyAccessor = null, ResourceClassResolverInterface $resourceClassResolver = null, ResourceMetadataFactoryInterface $resourceMetadataFactory = null)
{
$this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
$this->propertyMetadataFactory = $propertyMetadataFactory;
$this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
$this->resourceClassResolver = $resourceClassResolver;
$this->resourceMetadataFactory = $resourceMetadataFactory;

if (null === $this->resourceClassResolver) {
@trigger_error(sprintf('Not injecting %s in the CachedIdentifiersExtractor might introduce cache issues with object identifiers.', ResourceClassResolverInterface::class), E_USER_DEPRECATED);
Expand Down
1 change: 1 addition & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@
<service id="api_platform.listener.view.write" class="ApiPlatform\Core\EventListener\WriteListener">
<argument type="service" id="api_platform.data_persister" />
<argument type="service" id="api_platform.iri_converter" on-invalid="null" />
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing on-invalid="null"


<tag name="kernel.event_listener" event="kernel.view" method="onKernelView" priority="32" />
</service>
Expand Down
4 changes: 0 additions & 4 deletions src/Bridge/Symfony/Routing/ApiLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,6 @@ public function load($data, $type = null): RouteCollection
'_controller' => $controller,
'_format' => null,
'_api_resource_class' => $operation['resource_class'],
'_api_input_class' => $operation['input_class'],
'_api_output_class' => $operation['output_class'],
'_api_subresource_operation_name' => $operation['route_name'],
'_api_subresource_context' => [
'property' => $operation['property'],
Expand Down Expand Up @@ -212,8 +210,6 @@ private function addRoute(RouteCollection $routeCollection, string $resourceClas
'_controller' => $controller,
'_format' => null,
'_api_resource_class' => $resourceClass,
'_api_input_class' => $resourceMetadata->getAttribute('input_class', $resourceClass),
'_api_output_class' => $resourceMetadata->getAttribute('output_class', $resourceClass),
sprintf('_api_%s_operation_name', $operationType) => $operationName,
] + ($operation['defaults'] ?? []),
$operation['requirements'] ?? [],
Expand Down
8 changes: 4 additions & 4 deletions src/DataProvider/OperationDataProviderTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ trait OperationDataProviderTrait
*/
private function getCollectionData(array $attributes, array $context)
{
return $this->collectionDataProvider->getCollection($attributes['output_class'] ?: $attributes['resource_class'], $attributes['collection_operation_name'], $context);
return $this->collectionDataProvider->getCollection($attributes['resource_class'], $attributes['collection_operation_name'], $context);
}

/**
Expand All @@ -59,7 +59,7 @@ private function getCollectionData(array $attributes, array $context)
*/
private function getItemData($identifiers, array $attributes, array $context)
{
return $this->itemDataProvider->getItem($attributes['output_class'] ?: $attributes['resource_class'], $identifiers, $attributes['item_operation_name'], $context);
return $this->itemDataProvider->getItem($attributes['resource_class'], $identifiers, $attributes['item_operation_name'], $context);
}

/**
Expand All @@ -75,7 +75,7 @@ private function getSubresourceData($identifiers, array $attributes, array $cont
throw new RuntimeException('Subresources not supported');
}

return $this->subresourceDataProvider->getSubresource($attributes['output_class'] ?: $attributes['resource_class'], $identifiers, $attributes['subresource_context'] + $context, $attributes['subresource_operation_name']);
return $this->subresourceDataProvider->getSubresource($attributes['resource_class'], $identifiers, $attributes['subresource_context'] + $context, $attributes['subresource_operation_name']);
}

/**
Expand All @@ -93,7 +93,7 @@ private function extractIdentifiers(array $parameters, array $attributes)
$id = $parameters['id'];

if (null !== $this->identifierConverter) {
return $this->identifierConverter->convert((string) $id, $attributes['output_class'] ?: $attributes['resource_class']);
return $this->identifierConverter->convert((string) $id, $attributes['resource_class']);
}

return $id;
Expand Down
15 changes: 8 additions & 7 deletions src/EventListener/DeserializeListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,11 @@ public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$method = $request->getMethod();

if (
'DELETE' === $method
|| $request->isMethodSafe(false)
|| !($attributes = RequestAttributesExtractor::extractAttributes($request))
|| false === ($attributes['input_class'] ?? null)
|| !$attributes['receive']
|| (
'' === ($requestContent = $request->getContent())
Expand All @@ -76,17 +76,18 @@ public function onKernelRequest(GetResponseEvent $event)
) {
return;
}

$context = $this->serializerContextBuilder->createFromRequest($request, false, $attributes);
if (false === $context['input_class']) {
return;
}

// BC check to be removed in 3.0
if (null !== $this->formatsProvider) {
$this->formats = $this->formatsProvider->getFormatsFromAttributes($attributes);
}
$this->formatMatcher = new FormatMatcher($this->formats);

$format = $this->getFormat($request);
$context = $this->serializerContextBuilder->createFromRequest($request, false, $attributes);
if (isset($context['input_class'])) {
$context['resource_class'] = $context['input_class'];
}

$data = $request->attributes->get('data');
if (null !== $data) {
Expand All @@ -96,7 +97,7 @@ public function onKernelRequest(GetResponseEvent $event)
$request->attributes->set(
'data',
$this->serializer->deserialize(
$requestContent, $attributes['input_class'], $format, $context
$requestContent, $context['input_class'], $format, $context
)
);
}
Expand Down
20 changes: 17 additions & 3 deletions src/EventListener/WriteListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\DataPersister\DataPersisterInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;

Expand All @@ -28,11 +29,13 @@ final class WriteListener
{
private $dataPersister;
private $iriConverter;
private $resourceMetadataFactory;

public function __construct(DataPersisterInterface $dataPersister, IriConverterInterface $iriConverter = null)
public function __construct(DataPersisterInterface $dataPersister, IriConverterInterface $iriConverter = null, ResourceMetadataFactoryInterface $resourceMetadataFactory = null)
{
$this->dataPersister = $dataPersister;
$this->iriConverter = $iriConverter;
$this->resourceMetadataFactory = $resourceMetadataFactory;
}

/**
Expand Down Expand Up @@ -65,10 +68,21 @@ public function onKernelView(GetResponseForControllerResultEvent $event)
// Controller result must be immutable for _api_write_item_iri
// if it's class changed compared to the base class let's avoid calling the IriConverter
// especially that the Output class could be a DTO that's not referencing any route
if (null !== $this->iriConverter && (false !== $attributes['output_class'] ?? null) && $attributes['resource_class'] === ($class = \get_class($controllerResult)) && $class === \get_class($event->getControllerResult())) {
if (null === $this->iriConverter) {
return;
}

$hasOutput = true;
if (null !== $this->resourceMetadataFactory) {
$resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);
$hasOutput = false !== $resourceMetadata->getOperationAttribute($attributes, 'output_class', null, true);
}

$class = \get_class($controllerResult);
if ($hasOutput && $attributes['resource_class'] === $class && $class === \get_class($event->getControllerResult())) {
$request->attributes->set('_api_write_item_iri', $this->iriConverter->getIriFromItem($controllerResult));
}
break;
break;
case 'DELETE':
$this->dataPersister->remove($controllerResult);
$event->setControllerResult(null);
Expand Down
35 changes: 35 additions & 0 deletions src/Identifier/ContextAwareIdentifierConverterInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Identifier;

/**
* Identifier converter.
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/

namespace ApiPlatform\Core\Identifier;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops ?


/**
* Gives access to the context.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
interface ContextAwareIdentifierConverterInterface extends IdentifierConverterInterface
{
/**
* {@inheritdoc}
*/
public function convert(string $data, string $class, array $context = []): array;
}
14 changes: 11 additions & 3 deletions src/Identifier/IdentifierConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,31 +16,39 @@
use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
use ApiPlatform\Core\Exception\InvalidIdentifierException;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use Symfony\Component\PropertyInfo\Type;

/**
* Identifier converter that chains identifier denormalizers.
*
* @author Antoine Bluchet <soyuka@gmail.com>
*/
final class IdentifierConverter implements IdentifierConverterInterface
final class IdentifierConverter implements ContextAwareIdentifierConverterInterface
{
private $propertyMetadataFactory;
private $identifiersExtractor;
private $identifierDenormalizers;
private $resourceMetadataFactory;

public function __construct(IdentifiersExtractorInterface $identifiersExtractor, PropertyMetadataFactoryInterface $propertyMetadataFactory, $identifierDenormalizers)
public function __construct(IdentifiersExtractorInterface $identifiersExtractor, PropertyMetadataFactoryInterface $propertyMetadataFactory, $identifierDenormalizers, ResourceMetadataFactoryInterface $resourceMetadataFactory = null)
{
$this->propertyMetadataFactory = $propertyMetadataFactory;
$this->identifiersExtractor = $identifiersExtractor;
$this->identifierDenormalizers = $identifierDenormalizers;
$this->resourceMetadataFactory = $resourceMetadataFactory;
}

/**
* {@inheritdoc}
*/
public function convert(string $data, string $class): array
public function convert(string $data, string $class, array $context = []): array
{
if (null !== $this->resourceMetadataFactory) {
$resourceMetadata = $this->resourceMetadataFactory->create($class);
$class = $resourceMetadata->getOperationAttribute($context, 'output_class', $class, true);
}

$keys = $this->identifiersExtractor->getIdentifiersFromResourceClass($class);

if (($numIdentifiers = \count($keys)) > 1) {
Expand Down
2 changes: 0 additions & 2 deletions src/Operation/Factory/SubresourceOperationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,6 @@ private function computeSubresourceOperations(string $resourceClass, array &$tre
'collection' => $subresource->isCollection(),
'resource_class' => $subresourceClass,
'shortNames' => [$subresourceMetadata->getShortName()],
'input_class' => $subresourceMetadata->getAttribute('input_class', $subresourceClass),
'output_class' => $subresourceMetadata->getAttribute('output_class', $subresourceClass),
];

if (null === $parentOperation) {
Expand Down
26 changes: 9 additions & 17 deletions src/Serializer/SerializerContextBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,36 +45,28 @@ public function createFromRequest(Request $request, bool $normalization, array $

$resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);
$key = $normalization ? 'normalization_context' : 'denormalization_context';

$operationKey = null;
$operationType = null;

if (isset($attributes['collection_operation_name'])) {
$operationKey = 'collection_operation_name';
$operationType = OperationType::COLLECTION;
} elseif (isset($attributes['subresource_operation_name'])) {
} elseif (isset($attributes['item_operation_name'])) {
$operationKey = 'item_operation_name';
$operationType = OperationType::ITEM;
} else {
$operationKey = 'subresource_operation_name';
$operationType = OperationType::SUBRESOURCE;
}

if (null !== $operationKey) {
$attribute = $attributes[$operationKey];
$context = $resourceMetadata->getCollectionOperationAttribute($attribute, $key, [], true);
$context[$operationKey] = $attribute;
} else {
$context = $resourceMetadata->getItemOperationAttribute($attributes['item_operation_name'], $key, [], true);
$context['item_operation_name'] = $attributes['item_operation_name'];
}

$context['operation_type'] = $operationType ?: OperationType::ITEM;
$context = $resourceMetadata->getTypedOperationAttribute($operationType, $attributes[$operationKey], $key, [], true);
$context['operation_type'] = $operationType;
$context[$operationKey] = $attributes[$operationKey];

if (!$normalization && !isset($context['api_allow_update'])) {
$context['api_allow_update'] = \in_array($request->getMethod(), ['PUT', 'PATCH'], true);
}

$context['resource_class'] = $attributes['resource_class'];
$context['input_class'] = $attributes['input_class'] ?? $attributes['resource_class'];
$context['output_class'] = $attributes['output_class'] ?? $attributes['resource_class'];
$context['input_class'] = $resourceMetadata->getTypedOperationAttribute($operationKey, $attributes[$operationKey], 'input_class', $attributes['resource_class'], true);
$context['output_class'] = $resourceMetadata->getTypedOperationAttribute($operationKey, $attributes[$operationKey], 'output_class', $attributes['resource_class'], true);
$context['request_uri'] = $request->getRequestUri();
$context['uri'] = $request->getUri();

Expand Down
3 changes: 0 additions & 3 deletions src/Util/AttributesExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ private function __construct()
public static function extractAttributes(array $attributes): array
{
$result = ['resource_class' => $attributes['_api_resource_class'] ?? null];
$result['input_class'] = $attributes['_api_input_class'] ?? $result['resource_class'];
$result['output_class'] = $attributes['_api_output_class'] ?? $result['resource_class'];

if ($subresourceContext = $attributes['_api_subresource_context'] ?? null) {
$result['subresource_context'] = $subresourceContext;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ public function testWithResource()
$this->response
);

$this->assertSame(['resource_class' => DummyEntity::class, 'input_class' => DummyEntity::class, 'output_class' => DummyEntity::class, 'item_operation_name' => 'get', 'receive' => true, 'persist' => true], $dataCollector->getRequestAttributes());
$this->assertSame(['resource_class' => DummyEntity::class, 'item_operation_name' => 'get', 'receive' => true, 'persist' => true], $dataCollector->getRequestAttributes());
$this->assertSame(['foo', 'bar'], $dataCollector->getAcceptableContentTypes());
$this->assertSame(DummyEntity::class, $dataCollector->getResourceClass());
$this->assertSame(['foo' => null, 'a_filter' => \stdClass::class], $dataCollector->getFilters());
Expand Down
4 changes: 0 additions & 4 deletions tests/Bridge/Symfony/Routing/ApiLoaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -305,8 +305,6 @@ private function getRoute(string $path, string $controller, string $resourceClas
'_controller' => $controller,
'_format' => null,
'_api_resource_class' => $resourceClass,
'_api_input_class' => $resourceClass,
'_api_output_class' => $resourceClass,
sprintf('_api_%s_operation_name', $collection ? 'collection' : 'item') => $operationName,
] + $extraDefaults,
$requirements,
Expand All @@ -326,8 +324,6 @@ private function getSubresourceRoute(string $path, string $controller, string $r
'_controller' => $controller,
'_format' => null,
'_api_resource_class' => $resourceClass,
'_api_input_class' => $resourceClass,
'_api_output_class' => $resourceClass,
'_api_subresource_operation_name' => $operationName,
'_api_subresource_context' => $context,
],
Expand Down
2 changes: 1 addition & 1 deletion tests/EventListener/AddFormatListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ public function testResourceClassSupportedRequestFormat()
$event = $eventProphecy->reveal();

$formatsProviderProphecy = $this->prophesize(FormatsProviderInterface::class);
$formatsProviderProphecy->getFormatsFromAttributes(['resource_class' => 'Foo', 'input_class' => 'Foo', 'output_class' => 'Foo', 'collection_operation_name' => 'get', 'receive' => true, 'persist' => true])->willReturn(['csv' => ['text/csv']])->shouldBeCalled();
$formatsProviderProphecy->getFormatsFromAttributes(['resource_class' => 'Foo', 'collection_operation_name' => 'get', 'receive' => true, 'persist' => true])->willReturn(['csv' => ['text/csv']])->shouldBeCalled();

$listener = new AddFormatListener(new Negotiator(), $formatsProviderProphecy->reveal());
$listener->onKernelRequest($event);
Expand Down
Loading