Skip to content

Instantly share code, notes, and snippets.

@simshaun
Created November 9, 2018 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simshaun/66cdaad4ce3cf242de2aea0920504f53 to your computer and use it in GitHub Desktop.
Save simshaun/66cdaad4ce3cf242de2aea0920504f53 to your computer and use it in GitHub Desktop.
API Platform custom normalizer for object constructor arguments
<?php
// src/Serializer/CommentNormalizer.php
namespace App\Serializer;
use App\DataProvider\CurrentUserProvider;
use App\Entity\Comment;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
final class CommentNormalizer implements NormalizerInterface, DenormalizerInterface
{
private $normalizer;
private $currentUserProvider;
public function __construct(NormalizerInterface $normalizer, CurrentUserProvider $currentUserProvider)
{
if (!$normalizer instanceof DenormalizerInterface) {
throw new \InvalidArgumentException('The normalizer must implement the DenormalizerInterface');
}
$this->normalizer = $normalizer;
$this->currentUserProvider = $currentUserProvider;
}
public function supportsDenormalization($data, $type, $format = null): bool
{
return $type === Comment::class;
}
public function denormalize($data, $class, $format = null, array $context = array())
{
$user = $this->currentUserProvider->getCurrentUser();
// While not technically necessary as long as the route is secured properly, this is here as a fail-safe.
if (!$user) {
throw new \InvalidArgumentException('You must be logged in to comment.');
}
return $this->normalizer->denormalize($data, $class, $format, array_merge($context, [
'default_constructor_arguments' => [
$class => [
'user' => $user,
],
],
]));
}
public function supportsNormalization($data, $format = null): bool
{
return $this->normalizer->supportsNormalization($data, $format);
}
public function normalize($object, $format = null, array $context = array())
{
return $this->normalizer->normalize($object, $format, $context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment