1

我有一个作为 api-platform 资源公开的实体,并包含以下属性:

/**
 * @ORM\Column(type="string", nullable=true)
 */
private $note;

当我尝试更新实体(通过 PUT)时,发送以下 json:

{
  "note": null
}

我从 Symfony 序列化程序收到以下错误:

[2017-06-29 21:47:33] request.CRITICAL:未捕获的 PHP 异常 Symfony\Component\Serializer\Exception\UnexpectedValueException:“类型为“字符串”的预期参数,在 /var/www/html 处给出“NULL” /testapp/server/vendor/symfony/symfony/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php 第 196 行 {"exception":"[object] (Symfony\Component\Serializer\Exception\UnexpectedValueException(code: 0) :在 /var/www/html/testapp/server/vendor/symfony/symfony/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php:196 给出的类型为 \"string\"、\"NULL\" 的预期参数, Symfony\Component\PropertyAccess\Exception\InvalidArgumentException(code: 0): 类型为 \"string\", \"NULL\" 的预期参数在 /var/www/html/testapp/server/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php:275)"} []

似乎我缺少一些配置以允许此属性为空?为了让事情变得更奇怪,当我 GET 一个包含空注释的资源时,该注释正确地返回为空:

{
  "@context": "/contexts/RentPayment",
  "@id": "/rent_payments/1",
  "@type": "RentPayment",
  "id": 1,
  "note": null,
  "date": "2016-03-01T00:00:00+00:00"
}

我错过了什么 - ps 我是 api-platform 的新手

4

1 回答 1

5

好吧,正如评论中确定的那样,您使用的是类型提示的 setter à la:

public function setNote(string $note) {
    $this->note = $note;
    return $this;
}

从 PHP 7.1 开始,我们有可以为空的类型,因此以下是首选,因为它实际上检查 null 或字符串而不是任何类型。

public function setNote(?string $note = null) {

在以前的版本中,只需删除类型提示,如果愿意,可以在里面添加一些类型检查。

public function setNote($note) {
    if ((null !== $note) && !is_string($note)) {
        // throw some type exception!
    }
    
    $this->note = $note;
    return $this;
}

您可能要考虑的另一件事是使用类似的东西:

$this->note = $note ?: null;

这是 if (三元运算符) 的排序。如果字符串为空,则将值设置为 null(但在 '0' 上存在错误,因此您可能需要执行更长的版本)。

于 2017-06-30T11:26:51.460 回答