Skip to content

Instantly share code, notes, and snippets.

@bhaktaraz
Created September 11, 2019 06:56
Show Gist options
  • Save bhaktaraz/c155a027be98b6822a73ed6e8cbc6d01 to your computer and use it in GitHub Desktop.
Save bhaktaraz/c155a027be98b6822a73ed6e8cbc6d01 to your computer and use it in GitHub Desktop.
Symfony and JMS Serialier, Listener to add extra fields
<?php
/**
* Created by PhpStorm.
* User: bhaktaraz
* Date: 9/11/19
* Time: 11:33 AM
*/
namespace App\Serializer;
use App\Entity\User;
use App\Entity\AccessCode;
use Doctrine\ORM\EntityManagerInterface;
use JMS\Serializer\EventDispatcher\ObjectEvent;
use JMS\Serializer\Metadata\StaticPropertyMetadata;
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
class ResponseSerializationSubscriber implements EventSubscriberInterface
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public static function getSubscribedEvents()
{
return [
['event' => 'serializer.post_serialize', 'method' => 'onPostSerialize'],
];
}
public function onPostSerialize(ObjectEvent $event)
{
$object = $event->getObject();
if($object instanceof User) {
$code = $this->em->getRepository(AccessCode::class)->findOneBy(['code' => $object->getClinicCode()]);
$clinic = $code->getClinic();
$visitor = $event->getVisitor();
$visitor->visitProperty(new StaticPropertyMetadata(User::class, 'clinic_name', $clinic->getName()), $clinic->getName());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment