Skip to content

Instantly share code, notes, and snippets.

@VeryStrongFingers
Last active November 2, 2021 08:52
Show Gist options
  • Save VeryStrongFingers/866f755b558b2b4f6d47389c8fd51816 to your computer and use it in GitHub Desktop.
Save VeryStrongFingers/866f755b558b2b4f6d47389c8fd51816 to your computer and use it in GitHub Desktop.
ResourceItemNormalizer.php
<?php
declare(strict_types=1);
namespace App\Serializer;
use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\Serializer\AbstractItemNormalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Based off code provided from 'ghettovoice' @ GitHub
*
* #1. Copy & paste to src/Serializer/ResourceItemNormalizer.php
* #2. Add service definition to config/services.yaml otherwise you'll find recursion exception
* <pre>
* App\Serializer\ResourceItemNormalizer:
* arguments: [ '@api_platform.iri_converter', '@api_platform.serializer.normalizer.item' ]
* </pre>
* #3. ????
* #4. Profit
*
* @see https://github.com/api-platform/core/issues/2123
*/
final class ResourceItemNormalizer implements NormalizerInterface, DenormalizerInterface
{
private $iriConverter;
private $normalizer;
public function __construct(IriConverterInterface $iriConverter, NormalizerInterface $normalizer)
{
if (!$normalizer instanceof DenormalizerInterface) {
throw new \InvalidArgumentException('The normalizer must implement the DenormalizerInterface');
}
$this->iriConverter = $iriConverter;
$this->normalizer = $normalizer;
}
public function denormalize($data, string $type, string $format = null, array $context = [])
{
if (is_string($data) === true &&
($context['operation_type'] ?? null) === 'collection' &&
strtolower($context['collection_operation_name'] ?? '') === 'post' &&
isset($context[AbstractItemNormalizer::OBJECT_TO_POPULATE]) === false
) {
// Use IRI Converter to resolve item only for POST requests against a collection
return $this->iriConverter->getItemFromIri($data, $context + ['fetch_data' => true]);
}
return $this->normalizer->denormalize($data, $type, $format, $context);
}
public function normalize($object, string $format = null, array $context = [])
{
return $this->normalizer->normalize($object, $format, $context);
}
public function supportsDenormalization($data, string $type, string $format = null)
{
return $this->normalizer->supportsDenormalization($data, $type, $format);
}
public function supportsNormalization($data, string $format = null)
{
return $this->normalizer->supportsNormalization($data, $format);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment