Review generated shipping quote

from PHP 8.0 features
PHP 8.3.33 advanced 6 min 5 issues to find

Review this generated shipping quote handler before it is used by an HTTP endpoint.

Accept a validated positive weight and a known local or remote zone, enforce the staff role declared in metadata, and return a quote without repeated reflection on every request.

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, '.', '');
    }
}

generated code is illustrative, not from any one model

Open in playground
Report an error