审查生成的运费报价

来自 PHP 8.0 新特性
PHP 8.3.33 高级 6分钟 找出 5处问题

在这段生成的运费报价处理器用于 HTTP 端点前,对它进行审查。

接收经过验证的正数重量与已知的 local 或 remote 区域,执行元数据声明的 staff 角色,并返回报价,同时避免每次请求重复反射。

php
<?php
#[Attribute(Attribute::TARGET_METHOD)]
final class RequiresRole {
    public function __construct(public string $role) {}
}
final class QuoteRequest {
    public function __construct(public int|float $weight, public string $zone) {}
}
final class ShippingController {
    #[RequiresRole('staff')]
    public function quote(array $payload, string $actorRole): string {
        $method = new ReflectionMethod($this, __FUNCTION__);
        $required = $method->getAttributes(RequiresRole::class)[0]->newInstance();
        $request = new QuoteRequest(weight: $payload['weight'], zone: $payload['zone']);
        $rate = match ($request->zone) {
            'local' => 1.2,
            default => 2.0,
        };
        return number_format($request->weight * $rate, 2, '.', '');
    }
}

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

在试验场中打开
报告错误