Created
June 30, 2020 19:43
-
-
Save weaverryan/3b2da11198e3bb012c7c9698ef9248ef to your computer and use it in GitHub Desktop.
inlining children of a self-referencing to an IRI in API Platform
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a different solution a user posted - https://gist.github.com/voltel/ac2820fc7f97892999162774452a97fa
Reference: https://symfonycasts.com/screencast/api-platform/relations-iri#comment-5391015233
Thanks to @voltel :)