Passed
Push — 1.x ( 90de9d...e2e7a5 )
by Akihito
05:28 queued 03:04
created

PhpClassInvoker::invoke()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
nc 5
nop 1
dl 0
loc 27
rs 9.4222
c 1
b 0
f 0
1
<?php
2
// phpcs:ignoreFile
3
4
namespace BEAR\Resource;
5
6
use BEAR\Resource\Exception\BadRequestException;
7
use Throwable;
8
use function call_user_func_array;
9
use function is_callable;
10
use function ucfirst;
11
12
/** @psalm-import-type Query from Types */
13
final readonly class PhpClassInvoker implements InvokerInterface
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_READONLY, expecting T_CLASS on line 13 at column 6
Loading history...
14
{
15
    public function __construct(
16
        private NamedParameterInterface $params,
17
        private ExtraMethodInvoker $extraMethod,
18
        private LoggerInterface $logger,
19
    ) {
20
    }
21
22
    /**
23
     * {@inheritdoc}
24
     */
25
    #[\Override]
26
    public function invoke(AbstractRequest $request): ResourceObject
27
    {
28
        $callable = [$request->resourceObject, 'on' . ucfirst($request->method)];
29
        if (! is_callable($callable)) {
30
            // OPTIONS or HEAD
31
            return ($this->extraMethod)($request, $this);
32
        }
33
34
        $params = $this->params->getParameters($callable, $request->query);
35
        /** @psalm-suppress MixedAssignment */
36
        try {
37
            $response = call_user_func_array($callable, $params);
38
        } catch (Throwable $e) {
39
            if ($e::class === \TypeError::class) {
40
                throw new BadRequestException('Invalid parameter type', Code::BAD_REQUEST, $e);
41
            }
42
            throw $e;
43
        }
44
        if (! $response instanceof ResourceObject) {
45
            $request->resourceObject->body = $response;
46
            $response = $request->resourceObject;
47
        }
48
49
        ($this->logger)($response);
50
51
        return $response;
52
    }
53
}
54