Skip to content

Instantly share code, notes, and snippets.

@weaverryan
Created June 30, 2020 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaverryan/3b2da11198e3bb012c7c9698ef9248ef to your computer and use it in GitHub Desktop.
Save weaverryan/3b2da11198e3bb012c7c9698ef9248ef to your computer and use it in GitHub Desktop.
inlining children of a self-referencing to an IRI in API Platform
<?php
namespace App\Serializer\Normalizer;
use App\Entity\CheeseListing;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
class CheeseNormalizer implements ContextAwareNormalizerInterface, CacheableSupportsMethodInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
private const ALREADY_CALLED = 'USER_NORMALIZER_ALREADY_CALLED';
public function normalize($object, $format = null, array $context = array())
{
$context[self::ALREADY_CALLED] = true;
// set the groups to nothing so that no data is serialized from
// the child object
$context['groups'] = [];
// not sure why this is needed. This is normally added
// by the JSON-LD ObjectNormalizer, but that doesn't seem to
// be used... and the logic here is quite hard to follow.
// so, I added it myself - it's the flag that converting to an
// IRI is ok
$context['api_empty_resource_as_iri'] = true;
$data = $this->normalizer->normalize($object, $format, $context);
$context[self::ALREADY_CALLED] = false;
return $data;
}
public function supportsNormalization($data, $format = null, array $context = [])
{
// avoid recursion: only call once per object
if (isset($context[self::ALREADY_CALLED])) {
return false;
}
// api_attribute is a context key set to the property being normalized
return $data instanceof CheeseListing
&& isset($context['api_attribute'])
&& in_array($context['api_attribute'], ['parentCheese', 'childCheeses']);
}
public function hasCacheableSupportsMethod(): bool
{
return false;
}
}
@weaverryan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment