Issues (141)

src/InputParam.php (1 issue)

Labels
Severity
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource;
6
7
use InvalidArgumentException;
8
use Override;
9
use Ray\Di\InjectorInterface;
10
use Ray\InputQuery\InputQueryInterface;
11
use ReflectionNamedType;
12
use ReflectionParameter;
13
14
use function array_key_exists;
15
use function assert;
16
use function class_exists;
17
18
/** @psalm-import-type Query from Types */
19
final readonly class InputParam implements ParamInterface
0 ignored issues
show
A parse error occurred: Syntax error, unexpected T_READONLY, expecting T_CLASS on line 19 at column 6
Loading history...
20
{
21
    /** @param InputQueryInterface<object> $inputQuery */
22
    public function __construct(
23
        private InputQueryInterface $inputQuery,
24
        private ReflectionParameter $parameter,
25
    ) {
26
    }
27
28
    /**
29
     * {@inheritDoc}
30
     *
31
     * @psalm-taint-source input
32
     */
33
    #[Override]
34
    public function __invoke(string $varName, array $query, InjectorInterface $injector)
35
    {
36
        $type = $this->parameter->getType();
37
        if ($type instanceof ReflectionNamedType && ! $type->isBuiltin()) {
38
            $inputClass = $type->getName();
39
            assert(class_exists($inputClass));
40
41
            return $this->inputQuery->newInstance($inputClass, $query);
42
        }
43
44
        // For built-in types, handle missing values explicitly
45
        if (array_key_exists($varName, $query)) {
46
            return $query[$varName];
47
        }
48
49
        $type = $this->parameter->getType();
50
        $isRequired = true;
51
        if ($type instanceof ReflectionNamedType && $type->allowsNull()) {
52
            $isRequired = false;
53
        }
54
55
        if ($this->parameter->isDefaultValueAvailable()) {
56
            $isRequired = false;
57
        }
58
59
        if ($isRequired) {
60
            throw new InvalidArgumentException("Missing required parameter: {$varName}");
61
        }
62
63
        return null;
64
    }
65
}
66