API 平台 - 更新可为空的字符串错误

dbl*_*ack 1 symfony api-platform.com

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

/**
 * @ORM\Column(type="string", nullable=true)
 */
private $note;
Run Code Online (Sandbox Code Playgroud)

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

{
  "note": null
}
Run Code Online (Sandbox Code Playgroud)

我从 Symfony Serializer 收到以下错误:

[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 line 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)"} []

似乎我缺少一些允许此属性为空的配置?更奇怪的是,当我获取包含空注释的资源时,该注释正确返回为空:

{
  "@context": "/contexts/RentPayment",
  "@id": "/rent_payments/1",
  "@type": "RentPayment",
  "id": 1,
  "note": null,
  "date": "2016-03-01T00:00:00+00:00"
}
Run Code Online (Sandbox Code Playgroud)

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

Jen*_*eer 5

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

public function setNote(string $note) {
    $this->note = $note;
    return $this;
}
Run Code Online (Sandbox Code Playgroud)

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

public function setNote(?string $note = null) {
Run Code Online (Sandbox Code Playgroud)

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

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

您可能要考虑的另一件事是使用以下内容:

$this->note = $note ?: null;
Run Code Online (Sandbox Code Playgroud)

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