Skip to content

Instantly share code, notes, and snippets.

@rakodev rakodev/userNormalizer.php
Last active Sep 16, 2019

Embed
What would you like to do?
<?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
{
private $normalizer;
public function __construct(ObjectNormalizer $normalizer)
{
$this->normalizer = $normalizer;
}
public function normalize($object, $format = null, array $context = array()): array
{
/** @var User $object */
if ($this->userIsOwner($object)) {
$context['groups'][] = 'owner:read';
}
$data = $this->normalizer->normalize($object, $format, $context);
return $data;
}
public function supportsNormalization($data, $format = null): bool
{
return $data instanceof User;
}
public function hasCacheableSupportsMethod(): bool
{
return true;
}
private function userIsOwner(User $user): bool
{
return rand(0, 10) > 5;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.