bearsunday /
BEAR.Package
| 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
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 |