Search code examples
phpjmsserializerbundlejms-serializer

Can't serialize virtual properties in schmittjoh/serializer


One of my classes that I'm serializing has a virtual property that I would like to see. I'm using yaml configuration.

Here's the yaml:

Namespace\Model\Keg:
   exclusion_policy: ALL
   properties:
      A list of properties that work
   virtual_properties:
      getKegImage:
         serialized_name: image

Here's the class:

namespace Namespace\Model;

class Keg extends ModelAbstract
{
       /** Some properties + accessors **/

       /**
       * @param bool $asImgTag Whether or not to return the URL in an <img> tag
       * @return array
       */
       public function getKegImage ($asImgTag = false)
       {
               return [
                    'Key' => 'value',
                    'Key' => 'value',
                    'Key' => 'value'
               ];
       }
}

When I serialize the model, I would expect the to see an image field in the json with the array as its value. Instead, the field is missing. I've tried many combinations of settings in the yaml file and I can't get it to show.


Solution

  • From looking at the code, it looks like virtual properties aren't supported using yaml metadata. Luckily, you can mix metadata sources if you want. I simply added the @VirtualProperty Doctrine annotation to the method and it worked as expected.