Search code examples
phpsymfonyfosrestbundlejmsserializerbundlejms-serializer

FosRestBundle: Dynamic VirtualProperties


In FOSRestBundle : Annotations, I want to use multiple @VirtualProperty with dynamic names because i fetch the properties names from the database (unknown number of properties)

class User
{
   private $id;
   private $name;

   /**
    * @Serializer\VirtualProperty
    *
    * @return array
    */
   public function getSomeMethod()
   {
       return array('property_name1'=> 'value1', 'property_name2'=>'value2');
   }
}

Where property_name1 & property_name2 .. property_name3 .. etc are dynamic with infinit number

I want to set them as virtual properties , each property has a string value.

I don't want to set them as array with one property.

If there is no way to do this, please let me know if i can do the same task from the controller?


Solution

  • Originally a comment...

    You might be able to do this using @Serializer\Inline so that the properties of the array of bought up to be properties of the the parent object.

    Some more info

    This essentially allows you to have the exposed properties or keys/value of and array or object to be bought up to be properties of the parent object.

    For example..

    class Id
    {
        /**
         * @Expose
         */
        private $id;
    
        //...
    }
    
    class Parent
    {
        /**
         * @Expose
         * @Inline
         */
        private $id;
    
        /**
         * @Expose
         * @Inline
         */
        private $name = 'parent';
    
        /**
         * @Expose
         * @Inline
         */
        private [
            'key' => 'value',
        ];
    
        public function __construct()
        {
            $this->id = new Id('an-id');
        }
    }
    

    Would first be transformed to an array similar to the following during serialization

    [
        'id' => 'an-id',
        'name' => 'parent',
        'key' => 'value',
    ]