You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中根据模型类型转换数组值类型的解决方案咨询

Symfony Serializer 类型转换与空值兼容问题

背景信息

API返回数据

调用API始终返回如下格式的$arrayResponse数组:

[
  "fooId" => "123",
  "barId" => "456",
  "totoId" => "789",
  "azertyId" => null,
  "closeId" => null
]

目标模型类(不可修改)

代码库中的Model.php类定义如下,无法修改其属性及类型声明:

class Model
{
    /**
     * @var int
     */
    private int $fooId;

    /**
     * @var int
     */
    private int $barId;

    /**
     * @var int
     */
    private int $totoId;

    /**
     * @var int
     */
    private int $azertyId;

    /**
     * @var int
     */
    private int $closeId;

    /**
     * @return int
     */
    public function getFooId(): int
    {
        return $this->fooId;
    }

    /**
     * @param int $fooId
     */
    public function setFooId(int $fooId): void
    {
        $this->fooId = $fooId;
    }

    /**
     * @return int
     */
    public function getBarId(): int
    {
        return $this->barId;
    }

    /**
     * @param int $barId
     */
    public function setBarId(int $barId): void
    {
        $this->barId = $barId;
    }

    /**
     * @return int
     */
    public function getTotoId(): int
    {
        return $this->totoId;
    }

    /**
     * @param int $totoId
     */
    public function setTotoId(int $totoId): void
    {
        $this->totoId = $totoId;
    }

    /**
     * @return int
     */
    public function getAzertyId(): int
    {
        return $this->azertyId;
    }

    /**
     * @param int $azertyId
     */
    public function setAzertyId(int $azertyId): void
    {
        $this->azertyId = $azertyId;
    }

    /**
     * @return int
     */
    public function getCloseId(): int
    {
        return $this->closeId;
    }

    /**
     * @param int $closeId
     */
    public function setCloseId(int $closeId): void
    {
        $this->closeId = $closeId;
    }
}

执行代码与报错

执行Symfony Serializer的反序列化代码:

$this->serializer->denormalize($arrayResponse, $class);

触发两个错误:

  1. The type of the "fooId" attribute for class "Folder\Model" must be one of "int" ("string" given).
  2. The type of the "azertyId" attribute for class "Folder\Model" must be one of "int" ("null" given).

需求与尝试过的方案

  • 限制条件:不能修改Model.php的属性定义,不想使用AbstractObjectNormalizer::DISABLE_TYPE_ENFORCEMENT,必须严格遵循模型的类型声明。
  • 尝试过的方案:
    • 用array_walk手动预处理数组,但仍需配合禁用类型检查,且多组数组和模型的手动转换过于繁琐。
    • 考虑过ReflectionClass处理,但资源消耗较高,不适用。

求高效、符合类型约束的解决方案。


内容的提问来源于stack exchange,提问作者Mitsukk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 12:15:41