Base::getFunctionArgs()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 15
c 2
b 1
f 0
dl 0
loc 22
rs 9.7666
cc 3
nc 2
nop 1
1
<?php
2
3
namespace Jasny\Controller\Traits;
4
5
use Jasny\Controller\Parameter\Parameter;
6
use Jasny\Controller\Parameter\PathParam;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
10
/**
11
 * Base methods for controller and guard.
12
 */
13
trait Base
14
{
15
    private ServerRequestInterface $request;
16
    private ResponseInterface $response;
17
18
    /**
19
     * Get request, set for controller
20
     */
21
    protected function getRequest(): ServerRequestInterface
22
    {
23
        if (!isset($this->request)) {
24
            throw new \LogicException("Request not set " . __CLASS__ . " has not been invoked"); // @codeCoverageIgnore
25
        }
26
27
        return $this->request;
28
    }
29
30
    /**
31
     * Get response, set for controller
32
     */
33
    protected function getResponse(): ResponseInterface
34
    {
35
        if (!isset($this->response)) {
36
            throw new \LogicException("Response not set " . __CLASS__ . " has not been invoked"); // @codeCoverageIgnore
37
        }
38
39
        return $this->response;
40
    }
41
42
    /**
43
     * Set the response
44
     */
45
    protected function setResponse(ResponseInterface $response): void
46
    {
47
        $this->response = $response;
48
    }
49
50
51
    /**
52
     * Get the arguments for a function from a route using reflection.
53
     */
54
    protected function getFunctionArgs(\ReflectionFunctionAbstract $refl): array
55
    {
56
        $args = [];
57
58
        foreach ($refl->getParameters() as $param) {
59
            [$argRefl] = $param->getAttributes(
60
                Parameter::class,
61
                \ReflectionAttribute::IS_INSTANCEOF
62
            ) + [null];
63
            $attribute = $argRefl?->newInstance() ?? new PathParam();
64
65
            $type = $param->getType();
66
67
            $args[] = $attribute->getValue(
68
                $this->request,
69
                $param->getName(),
70
                $type instanceof \ReflectionNamedType ? $type->getName() : null,
71
                !$param->isOptional(),
72
            ) ?? $param->getDefaultValue();
73
        }
74
75
        return $args;
76
    }
77
}
78