Symfony Restful API - Expose virtual property isLiked by current logged in user Symfony Restful API - Expose virtual property isLiked by current logged in user symfony symfony

Symfony Restful API - Expose virtual property isLiked by current logged in user


You could implments an EventSubscriberInterface as described here in the doc.

As Example:

use JMS\Serializer\EventDispatcher\EventSubscriberInterface;use JMS\Serializer\EventDispatcher\ObjectEvent;...class RestaurantSerializerSubscriber implements EventSubscriberInterface{    protected $tokenStorage;public function __construct(TokenStorageInterface $tokenStorage){    $this->tokenStorage = $tokenStorage;}public static function getSubscribedEvents(){    return [        [            'event' => 'serializer.post_serialize',            'class' => Restaurant::class,            'method' => 'onPostSerialize',        ],    ];}public function onPostSerialize(ObjectEvent $event){    $visitor = $event->getVisitor();    $restaurant = $event->getObject();    // your custom logic    $isFavourite = $this->getCurrentUser()->isFavourite($restaurant);    $visitor->addData('isFavorited', $isFavourite);}/** * Return the logged user. * * @return User */protected function getCurrentUser(){    return $this->tokenStorage->getToken()->getUser();}

And register, as YML example:

acme.restaurant_serializer_subscriber:    class: Acme\DemoBundle\Subscriber\RestaurantSerializerSubscriber    arguments: ["@security.token_storage"]    tags:        - { name: "jms_serializer.event_subscriber" }

Hope this help

PS: You could also intercept the serialization group selected, let me know if you neet that code.


Entity should know nothing about current logged in user so injecting user into entity is not a good idea.

Solution 1:

This can be done with custom serialization:

// serialize single entity or collection$data = $this->serializer->serialize($restaurant);// extra logic$data['is_favourited'] = // logic to check if it's favourited by current user// return serialized data

Solution 2

This can be also achieved by adding Doctrine2->postLoad listener or subscriber after loading Restaurant entity. You can add dependency for current authenticated token to such listener and set there Restaurant->is_favorited virtual property that will be next serialized with JMS.