Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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