1 | <?php |
||
2 | /** |
||
3 | * Closure for Craft CMS |
||
4 | * |
||
5 | * Allows you to use arrow function closures in Twig |
||
6 | * |
||
7 | * @link https://nystudio107.com |
||
0 ignored issues
–
show
Coding Style
introduced
by
![]() |
|||
8 | * @copyright Copyright (c) 2022 nystudio107 |
||
0 ignored issues
–
show
|
|||
9 | */ |
||
0 ignored issues
–
show
|
|||
10 | |||
11 | namespace nystudio107\closure\helpers; |
||
12 | |||
13 | use ReflectionException; |
||
14 | use ReflectionObject; |
||
15 | use ReflectionProperty; |
||
16 | |||
17 | /** |
||
0 ignored issues
–
show
|
|||
18 | * @author nystudio107 |
||
0 ignored issues
–
show
Content of the @author tag must be in the form "Display Name <[email protected]>"
![]() |
|||
19 | * @package Closure |
||
0 ignored issues
–
show
|
|||
20 | * @since 1.0.0 |
||
0 ignored issues
–
show
|
|||
21 | */ |
||
0 ignored issues
–
show
|
|||
22 | class Reflection |
||
23 | { |
||
24 | // Public static Methods |
||
25 | // ========================================================================= |
||
26 | /** |
||
0 ignored issues
–
show
|
|||
27 | * @param object $object |
||
0 ignored issues
–
show
|
|||
28 | * @param string $propertyName |
||
0 ignored issues
–
show
|
|||
29 | * |
||
30 | * @return ReflectionProperty |
||
31 | * @throws ReflectionException |
||
32 | */ |
||
33 | public static function getReflectionProperty(object $object, string $propertyName): ReflectionProperty |
||
34 | { |
||
35 | $reflectionObject = new ReflectionObject($object); |
||
36 | |||
37 | $reflectionProperty = null; |
||
38 | |||
39 | if ($reflectionObject->hasProperty($propertyName)) { |
||
40 | $reflectionProperty = $reflectionObject->getProperty($propertyName); |
||
41 | } else { |
||
42 | |||
43 | // This is needed for private parent properties only. |
||
44 | $parent = $reflectionObject->getParentClass(); |
||
45 | while ($reflectionProperty === null && $parent !== false) { |
||
46 | if ($parent->hasProperty($propertyName)) { |
||
47 | $reflectionProperty = $parent->getProperty($propertyName); |
||
48 | } |
||
49 | |||
50 | $parent = $parent->getParentClass(); |
||
51 | } |
||
52 | } |
||
53 | |||
54 | if (!$reflectionProperty) { |
||
55 | throw new ReflectionException("Property not found: " . $propertyName); |
||
56 | } |
||
57 | |||
58 | return $reflectionProperty; |
||
59 | } |
||
60 | } |
||
61 |