1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Cycle\ORM\Promise\Declaration\Extractor; |
5
|
|
|
|
6
|
|
|
use PhpParser\Node; |
7
|
|
|
|
8
|
|
|
final class Methods |
9
|
|
|
{ |
10
|
|
|
private const MAGIC_METHOD_NAMES = [ |
11
|
|
|
'__construct', |
12
|
|
|
'__destruct', |
13
|
|
|
'__call', |
14
|
|
|
'__callstatic', |
15
|
|
|
'__get', |
16
|
|
|
'__set', |
17
|
|
|
'__isset', |
18
|
|
|
'__unset', |
19
|
|
|
'__sleep', |
20
|
|
|
'__wakeup', |
21
|
|
|
'__toString', |
22
|
|
|
'__invoke', |
23
|
|
|
'__set_state', |
24
|
|
|
'__clone', |
25
|
|
|
'__debuginfo', |
26
|
|
|
]; |
27
|
|
|
|
28
|
|
|
public function getMethods(\ReflectionClass $reflection): array |
29
|
|
|
{ |
30
|
|
|
$methods = []; |
31
|
|
|
|
32
|
|
|
foreach ($reflection->getMethods() as $method) { |
33
|
|
|
if ($this->isIgnoredMethod($method)) { |
34
|
|
|
continue; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$flags = $this->makeNodeFlags($method); |
38
|
|
|
$returnType = $this->makeReturnType($method); |
39
|
|
|
|
40
|
|
|
$methods[] = new Node\Stmt\ClassMethod($method->getName(), compact('flags', 'returnType')); |
|
|
|
|
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return $methods; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
private function isIgnoredMethod(\ReflectionMethod $method): bool |
47
|
|
|
{ |
48
|
|
|
return $method->isPrivate() || $method->isStatic() || $method->isFinal() || $method->isAbstract() || $this->isMagicMethod($method->getName()); |
|
|
|
|
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private function isMagicMethod(string $name): bool |
52
|
|
|
{ |
53
|
|
|
return in_array($name, self::MAGIC_METHOD_NAMES, true); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function makeNodeFlags(\ReflectionMethod $method): int |
57
|
|
|
{ |
58
|
|
|
$flags = []; |
59
|
|
|
if ($method->isPublic()) { |
60
|
|
|
$flags[] = Node\Stmt\Class_::MODIFIER_PUBLIC; |
61
|
|
|
} elseif ($method->isProtected()) { |
62
|
|
|
$flags[] = Node\Stmt\Class_::MODIFIER_PROTECTED; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return array_reduce($flags, function ($a, $b) { |
66
|
|
|
return $a | $b; |
67
|
|
|
}, 0); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
private function makeReturnType(\ReflectionMethod $method): ?Node |
71
|
|
|
{ |
72
|
|
|
if (!$method->hasReturnType()) { |
73
|
|
|
return null; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
$returnType = $method->getReturnType(); |
77
|
|
|
|
78
|
|
|
if ($returnType === null) { |
79
|
|
|
return null; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
$name = $returnType->getName(); |
83
|
|
|
|
84
|
|
|
if (!$returnType->isBuiltin()) { |
85
|
|
|
$name = '\\' . $name; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
if ($returnType->allowsNull()) { |
89
|
|
|
$name = '?' . $name; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
return new Node\Identifier($name); |
93
|
|
|
} |
94
|
|
|
} |