Skip to content

Instantly share code, notes, and snippets.

@bastien70
Created May 28, 2021 13:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save bastien70/acecd7813613aa87ed1f5036a7291885 to your computer and use it in GitHub Desktop.
<?php
namespace App\Serializer\Normalizer;
use App\Entity\User;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class UserNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
{
public function __construct(private ObjectNormalizer $normalizer){}
/**
* @param User $object
*/
public function normalize($object, $format = null, array $context = []): array
{
if($this->userIsOwner($object)) {
$context['groups'][] = 'owner:read';
}
$data = $this->normalizer->normalize($object, $format, $context);
// Here: add, edit, or delete some data
return $data;
}
public function supportsNormalization($data, $format = null): bool
{
return $data instanceof User;
}
public function hasCacheableSupportsMethod(): bool
{
return true;
}
private function userIsOwner(User $object): bool
{
return true;
return random_int(0, 10) > 5;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment