-
-
Save bastien70/acecd7813613aa87ed1f5036a7291885 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 | |
{ | |
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