Fields inclusion rules in JMS Serializer

129 views Asked by At

I'm looking for a way to dynamic include fields when output JSON data through JMS serializer. And I found the post here: https://jolicode.com/blog/how-to-implement-your-own-fields-inclusion-rules-with-jms-serializer

The solution here is for including/excluding current fields of the current entity. But I also want the sub-entities fields definition when the entity has one-to-many relationships. For example:

class User
{
   private $name;
   private $age;

   /**@Type("array<Book>")**/
   var $books = [];
}

class Book
{
   private $title;
   private $pages;
   private $content;
}

So that I can pass an array to the FieldsListExclusionStrategy to figure out it the data here:

$fields = [
  'User' => ['name'],
  'Book' => ['title'],
];

But not just id and title for current entity. Anyone know how to this?

1

There are 1 answers

0
Yarco On

Em...Finally, I got the code (similar as the post):

class FieldsListExclusionStrategy implements \JMS\Serializer\Exclusion\ExclusionStrategyInterface
{
    private $fields = [];

    public function __construct(array $fields = [])
    {
        $this->fields = $fields;
    }

    public function shouldSkipClass(\JMS\Serializer\Metadata\ClassMetadata $metadata, \JMS\Serializer\Context $context)
    {
        return false;
    }

    public function shouldSkipProperty(\JMS\Serializer\Metadata\PropertyMetadata $property, \JMS\Serializer\Context $context)
    {
        $class = $property->class;
        if (!isset($this->fields[$class])) return false;

        $fields = $this->fields[$class];
        $name = $property->serializedName ?: $property->name;
        return !in_array($name, $fields);
    }
}