CompileClassMetaInfo::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 22
rs 9.8333
cc 4
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Package\Compiler;
6
7
use BEAR\Resource\Exception\ParameterException;
8
use BEAR\Resource\NamedParameterInterface;
9
use ReflectionClass;
10
11
use function in_array;
12
use function is_callable;
13
use function sprintf;
14
use function str_starts_with;
15
16
final class CompileClassMetaInfo
17
{
18
    /**
19
     * Save attribute and method meta information
20
     *
21
     * @param class-string<T> $className
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
22
     *
23
     * @template T of object
24
     */
25
    public function __invoke(NamedParameterInterface $namedParams, string $className): void
26
    {
27
        $class = new ReflectionClass($className);
28
        $instance = $class->newInstanceWithoutConstructor();
29
30
        $methods = $class->getMethods();
31
        $log = sprintf('M %s:', $className);
32
        foreach ($methods as $method) {
33
            $methodName = $method->getName();
34
            if ($this->isMagicMethod($methodName)) {
35
                continue;
36
            }
37
38
            if (str_starts_with($methodName, 'on')) {
39
                $log .= sprintf(' %s', $methodName);
40
                $this->saveNamedParam($namedParams, $instance, $methodName);
41
            }
42
43
            $log .= sprintf('@ %s', $methodName);
44
        }
45
46
        unset($log); // break here to see the $log
47
    }
48
49
    private function isMagicMethod(string $method): bool
50
    {
51
        return in_array($method, ['__sleep', '__wakeup', 'offsetGet', 'offsetSet', 'offsetExists', 'offsetUnset', 'count', 'ksort', 'asort', 'jsonSerialize'], true);
52
    }
53
54
    private function saveNamedParam(NamedParameterInterface $namedParameter, object $instance, string $method): void
55
    {
56
        // named parameter
57
        if (! in_array($method, ['onGet', 'onPost', 'onPut', 'onPatch', 'onDelete', 'onHead'], true)) {
58
            return;  // @codeCoverageIgnore
59
        }
60
61
        $callable = [$instance, $method];
62
        if (! is_callable($callable)) {
63
            return;  // @codeCoverageIgnore
64
        }
65
66
        try {
67
            $namedParameter->getParameters($callable, []);
68
        } catch (ParameterException) {
69
            return;
70
        }
71
    }
72
}
73