在 JMS 序列化程序中混合访问器和 SkipWhenEmpty

Mixing Accessor and SkipWhenEmpty in JMS Serializer

我在一个项目中使用 JMS serializer,我正在为一件事而苦恼。

我正在使用 @Accessor 注释(在 DateTime 属性 上)仅回显没有时间的日期。但是在我的一些objects上,我不会有任何信息,我不希望在这种情况下输出日期键。

没有 @Accessor,我可以轻松地使用 @SkipWhenEmpty,这对其他属性非常有效。但是我好像不能把他们两个混在一起?

这是我的示例代码:

composer.json:

{
    "require": {
        "jms/serializer": "^1.14"
    }
}

WhosebugExample.php:

<?php

declare(strict_types=1);

use JMS\Serializer\Annotation as Serializer;

class WhosebugExample
{
    /**
     * @var \DateTime
     * @Serializer\Accessor(getter="getDate")
     * @Serializer\SkipWhenEmpty()
     */
    private $date;

    /**
     * @var string
     * @Serializer\SkipWhenEmpty()
     */
    private $title;

    public function getDate(): string
    {
        if (null === $this->date) {
            return '';
        }

        return $this->date->format('Y-m-d');
    }

    public function setDate(\DateTime $date): void
    {
        $this->date = $date;
    }

    public function getTitle(): string
    {
        return $this->title;
    }

    public function setTitle(string $title): void
    {
        $this->title = $title;
    }
}

Whosebug.php:

<?php

$loader = require __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/WhosebugExample.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);

$serializer = \JMS\Serializer\SerializerBuilder::create()->build();

$testWithDateAndTitle = new WhosebugExample();
$testWithDateAndTitle->setDate(new DateTime());
$testWithDateAndTitle->setTitle('Example with date and title');

$testWithDateAndNoTitle = new WhosebugExample();
$testWithDateAndNoTitle->setDate(new DateTime());

$testWithNoDateButTitle = new WhosebugExample();
$testWithNoDateButTitle->setTitle('Example with title but no date');

echo $serializer->serialize($testWithDateAndTitle, 'json').PHP_EOL;
echo $serializer->serialize($testWithDateAndNoTitle, 'json').PHP_EOL;
echo $serializer->serialize($testWithNoDateButTitle, 'json').PHP_EOL;

执行Whosebug.php时,输出数据如下:

{"date":"2019-05-03","title":"Example with date and title"}
{"date":"2019-05-03"}
{"date":"","title":"Example with title but no date"}

第一行是控件。

在第二行,当省略设置标题时,输出的 json 中没有 "title" 键,感谢 @SkipWhenEmpty

但是在第三行,即使有 @SkipWhenEmpty,我仍然有日期键。

有什么我忘记了吗?如何仅在日期字段已填满时回显日期字段?

根据我的研究,我认为您需要 return null 而不是

return '';

在您的 getDate 函数中。

See