PhpClassInvoker::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 2
b 0
f 0
nc 1
nop 3
dl 0
loc 5
rs 10
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 class PhpClassInvoker implements InvokerInterface
14
{
15
    public function __construct(
16
        private readonly NamedParameterInterface $params,
17
        private readonly ExtraMethodInvoker $extraMethod,
18
        private readonly 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