Last active
September 16, 2019 18:29
-
-
Save rakodev/433a413a22b89afc6f4209545e250770 to your computer and use it in GitHub Desktop.
This file contains 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\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