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 Doctrine\Common\Annotations\Reader; |
10
|
|
|
use ReflectionClass; |
11
|
|
|
|
12
|
|
|
use function in_array; |
13
|
|
|
use function is_callable; |
14
|
|
|
use function sprintf; |
15
|
|
|
use function str_starts_with; |
16
|
|
|
|
17
|
|
|
final class CompileClassMetaInfo |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Save annotation and method meta information |
21
|
|
|
* |
22
|
|
|
* @param class-string<T> $className |
|
|
|
|
23
|
|
|
* |
24
|
|
|
* @template T of object |
25
|
|
|
*/ |
26
|
|
|
public function __invoke(Reader $reader, NamedParameterInterface $namedParams, string $className): void |
27
|
|
|
{ |
28
|
|
|
$class = new ReflectionClass($className); |
29
|
|
|
$instance = $class->newInstanceWithoutConstructor(); |
30
|
|
|
|
31
|
|
|
$reader->getClassAnnotations($class); |
32
|
|
|
$methods = $class->getMethods(); |
33
|
|
|
$log = sprintf('M %s:', $className); |
34
|
|
|
foreach ($methods as $method) { |
35
|
|
|
$methodName = $method->getName(); |
36
|
|
|
if ($this->isMagicMethod($methodName)) { |
37
|
|
|
continue; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
if (str_starts_with($methodName, 'on')) { |
41
|
|
|
$log .= sprintf(' %s', $methodName); |
42
|
|
|
$this->saveNamedParam($namedParams, $instance, $methodName); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
// method annotation |
46
|
|
|
$reader->getMethodAnnotations($method); |
47
|
|
|
$log .= sprintf('@ %s', $methodName); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
unset($log); // break here to see the $log |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
private function isMagicMethod(string $method): bool |
54
|
|
|
{ |
55
|
|
|
return in_array($method, ['__sleep', '__wakeup', 'offsetGet', 'offsetSet', 'offsetExists', 'offsetUnset', 'count', 'ksort', 'asort', 'jsonSerialize'], true); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
private function saveNamedParam(NamedParameterInterface $namedParameter, object $instance, string $method): void |
59
|
|
|
{ |
60
|
|
|
// named parameter |
61
|
|
|
if (! in_array($method, ['onGet', 'onPost', 'onPut', 'onPatch', 'onDelete', 'onHead'], true)) { |
62
|
|
|
return; // @codeCoverageIgnore |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$callable = [$instance, $method]; |
66
|
|
|
if (! is_callable($callable)) { |
67
|
|
|
return; // @codeCoverageIgnore |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
try { |
71
|
|
|
$namedParameter->getParameters($callable, []); |
72
|
|
|
} catch (ParameterException) { |
73
|
|
|
return; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|