1 | <?php |
||
2 | declare(strict_types = 1); |
||
3 | |||
4 | namespace Innmind\Reflection\Visitor; |
||
5 | |||
6 | use Innmind\Reflection\Exception\PropertyNotFound; |
||
7 | |||
8 | final class AccessProperty |
||
9 | { |
||
10 | /** |
||
11 | * @throws PropertyNotFound |
||
12 | */ |
||
13 | public function __invoke(object $object, string $property): \ReflectionProperty |
||
14 | { |
||
15 | try { |
||
16 | 23 | return $this->byObject($object, $property); |
|
17 | } catch (PropertyNotFound $e) { |
||
18 | return $this->byClass(\get_class($object), $property); |
||
19 | 23 | } |
|
20 | 12 | } |
|
21 | 12 | ||
22 | private function byObject(object $object, string $property): \ReflectionProperty |
||
23 | { |
||
24 | $refl = new \ReflectionObject($object); |
||
25 | 23 | ||
26 | if ($refl->hasProperty($property)) { |
||
27 | 23 | return $refl->getProperty($property); |
|
28 | } |
||
29 | 23 | ||
30 | 13 | throw new PropertyNotFound($property); |
|
31 | } |
||
32 | |||
33 | 12 | /** |
|
34 | * @param class-string $class |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
![]() |
|||
35 | */ |
||
36 | 12 | private function byClass(string $class, string $property): \ReflectionProperty |
|
37 | { |
||
38 | 12 | $refl = new \ReflectionClass($class); |
|
39 | |||
40 | 12 | if ($refl->hasProperty($property)) { |
|
41 | 4 | return $refl->getProperty($property); |
|
42 | } |
||
43 | |||
44 | 12 | if ($refl->getParentClass()) { |
|
45 | 4 | return $this->byClass( |
|
46 | 4 | $refl->getParentClass()->getName(), |
|
47 | 4 | $property, |
|
48 | ); |
||
49 | } |
||
50 | |||
51 | 8 | throw new PropertyNotFound($property); |
|
52 | } |
||
53 | } |
||
54 |