审查生成的订单输入映射器

来自 数据类型
PHP 8.3.33 高级 6分钟 找出 4处问题

在这个生成的请求映射器处理客户数据前,对它进行审查。

只接受 quantity、express 和 coupon_id;要求 quantity 是非负整数,解析布尔值或字符串 'true'/'false',让缺失的优惠券保持 null,并拒绝未知字段。

php
<?php
final class OrderInput
{
    public int $quantity;
    public bool $express;
    public ?int $couponId = null;

    public static function fromArray(array $input): self
    {
        $order = new self();
        foreach ($input as $field => $value) {
            $order->$field = $value;
        }

        $order->quantity = (int) ($input['quantity'] ?? null);
        $order->express = (bool) ($input['express'] ?? false);
        $order->couponId = (int) ($input['coupon_id'] ?? null);
        return $order;
    }
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误