Skip to content

Commit

Permalink
Merge pull request #2665 from teohhanhui/fix/cacheable-noop-scalar-no…
Browse files Browse the repository at this point in the history
…rmalizer

Add a cacheable no-op scalar normalizer
  • Loading branch information
soyuka authored Mar 28, 2019
2 parents 66ee1ba + 1010b95 commit 7893a72
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@
<tag name="serializer.normalizer" priority="-925" />
</service>

<service id="api_platform.serializer.normalizer.no_op_scalar" class="ApiPlatform\Core\Serializer\NoOpScalarNormalizer" public="false">
<!-- Run before our non-cacheable normalizers -->
<tag name="serializer.normalizer" priority="-900" />
</service>

<!-- Resources Operations path resolver -->

<service id="api_platform.operation_path_resolver" alias="api_platform.operation_path_resolver.router" public="false" />
Expand Down
51 changes: 51 additions & 0 deletions src/Serializer/NoOpScalarNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?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\Serializer;

use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

/**
* A no-op normalizer that passes through scalar values.
*
* When there are non-cacheable normalizers in use, and you don't need to normalize
* scalar values, register this normalizer with a higher priority than the non-cacheable
* normalizers. This allows caching supportsNormalization calls for scalar values.
*/
final class NoOpScalarNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
{
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null): bool
{
return is_scalar($data);
}

/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = [])
{
return $object;
}

/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool
{
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,7 @@ private function getPartialContainerBuilderProphecy()
'api_platform.serializer.group_filter',
'api_platform.serializer.normalizer.item',
'api_platform.serializer.normalizer.item.non_resource',
'api_platform.serializer.normalizer.no_op_scalar',
'api_platform.serializer.property_filter',
'api_platform.serializer_locator',
'api_platform.subresource_data_provider',
Expand Down

0 comments on commit 7893a72

Please sign in to comment.