Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
11 / 11 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| Analyzer | |
100.00% |
11 / 11 |
|
100.00% |
2 / 2 |
5 | |
100.00% |
1 / 1 |
| getPropertyAccessIfExists | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
| getAllProperties | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * Analyzer class implementation file |
| 4 | * @package Code\Property |
| 5 | * @author Felipe Gaspar <felipesouzalimagaspar@gmail.com> |
| 6 | */ |
| 7 | declare(strict_types=1); |
| 8 | namespace Code\Property; |
| 9 | /** |
| 10 | * Analyzer is a class for manipulating attributes using Reflection |
| 11 | * @final |
| 12 | */ |
| 13 | final class Analyzer { |
| 14 | /** |
| 15 | * Gets the ReflectionProperty of an object attribute if it exists |
| 16 | * @access public |
| 17 | * @param string $name Variable you want to get (The _ character is disregarded in the variable name) |
| 18 | * @param object $instance Object for variable access |
| 19 | * @return \ReflectionProperty|false ReflectionProperty fetched or false if attribute doesn't exist |
| 20 | */ |
| 21 | public static function getPropertyAccessIfExists(string $name, object $instance) : \ReflectionProperty|false { |
| 22 | $name = str_replace(["_"], '', strtolower($name)); |
| 23 | foreach ((new \ReflectionClass($instance))->getProperties() as $prop) |
| 24 | if($name === str_replace(["_"], '', strtolower($prop->getName()))) { |
| 25 | $prop->setAccessible(true); |
| 26 | return $prop; |
| 27 | } |
| 28 | return false; |
| 29 | } |
| 30 | /** |
| 31 | * Gets the ReflectionProperty of all attributes of an object |
| 32 | * @access public |
| 33 | * @param object $instance Object for accessing variables |
| 34 | * @return array<\ReflectionProperty> ReflectionProperty list of all object attributes |
| 35 | */ |
| 36 | public static function getAllProperties(object $instance) : array { |
| 37 | $props = []; |
| 38 | foreach ((new \ReflectionClass($instance))->getProperties() as $prop) { |
| 39 | $prop->setAccessible(true); |
| 40 | $props[] = $prop; |
| 41 | } |
| 42 | return $props; |
| 43 | } |
| 44 | } |