Created
September 11, 2019 06:56
-
-
Save bhaktaraz/c155a027be98b6822a73ed6e8cbc6d01 to your computer and use it in GitHub Desktop.
Symfony and JMS Serialier, Listener to add extra fields
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 | |
/** | |
* 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