JMS Serializer中的字段包含规则

时间:2017-08-28 08:17:44

标签: php symfony jms-serializer

我正在寻找通过JMS序列化程序输出JSON数据时动态包含字段的方法。我在这里找到了帖子:https://jolicode.com/blog/how-to-implement-your-own-fields-inclusion-rules-with-jms-serializer

此处的解决方案是包含/排除当前实体的当前字段。但是,当实体具有一对多关系时,我还希望子实体字段定义。例如:

new[](size_t, std::nothrow_t)

这样我就可以将一个数组传递给FieldsListExclusionStrategy,以便在这里找出数据:

class User
{
   private $name;
   private $age;

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

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

但不仅仅是当前实体的$fields = [ 'User' => ['name'], 'Book' => ['title'], ]; id。有谁知道怎么做?

1 个答案:

答案 0 :(得分:0)

Em ...最后,我得到了代码(类似帖子):

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);
    }
}