Search code examples
phpsymfonyjms-serializer

Access the SerializedName of a object property defined by Annotation


I have a model, which is using the JMS Serializer for Annotations of it's properties. In another class where I use this object I would like to access the information in the annotations. Example:

class ExampleObject
{
    /**
    * @var int The status code of a report
    *
    * @JMS\Expose
    * @JMS\Type("integer")
    * @JMS\SerializedName("StatusCode")
    * @Accessor(getter="getStatusCode")
    */
    public $statusCode;

}

As you can see the property is named in camelcase style, which is ok for our coding standards. But for passing the information in this object on to an external service I need the the SerializedName.

So my idea is to write an method in this class which gives me for every property the SerializedName from the Annotation back. Is it possible to access the information in the annotation via a method? If yes how?

My idea is something like:

public function getSerializerName($propertyName)
{
    $this->$propertyName;
    // Do some magic here with the annotation info
    return $serializedName;
}

So the "magic" part is where I need some help.


Solution

  • I found where the magic is happening: in the header of your class you have to add the following use statements:

    use Doctrine\Common\Annotations\AnnotationReader;
    use Doctrine\Common\Annotations\DocParser;
    

    the method to get the SerializedName works as follows:

    /**
     * Returns the name from the Annotations used by the serializer.
     * 
     * @param $propertyName property whose Annotation is requested
     *
     * @return mixed
     */
    public function getSerializerName($propertyName)
    {
        $reader = new AnnotationReader((new DocParser()));
        $reflection = new \ReflectionProperty($this, $propertyName);
        $serializedName = $reader->getPropertyAnnotation($reflection, 'JMS\Serializer\Annotation\SerializedName');
    
        return $serializedName->name;
    }
    

    Now you can call from another class the name, which is used for serialization and do with it whatever you need it for.