1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Stratadox\EntityState\Internal; |
5
|
|
|
|
6
|
|
|
use function array_key_exists as alreadyCached; |
7
|
|
|
use function get_class as theClassOfThe; |
8
|
|
|
use ReflectionClass; |
9
|
|
|
use ReflectionException; |
10
|
|
|
use ReflectionObject; |
11
|
|
|
use Stratadox\ImmutableCollection\ImmutableCollection; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* ReflectionProperties collection. |
15
|
|
|
* |
16
|
|
|
* @internal |
17
|
|
|
* @author Stratadox |
18
|
|
|
*/ |
19
|
|
|
final class ReflectionProperties extends ImmutableCollection |
20
|
|
|
{ |
21
|
|
|
private static $cache = []; |
22
|
|
|
|
23
|
|
|
private function __construct(ReflectionProperty ...$reflectionProperties) |
24
|
|
|
{ |
25
|
|
|
parent::__construct(...$reflectionProperties); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Retrieves the collection of ReflectionProperties for the object. |
30
|
|
|
* |
31
|
|
|
* @param object $object The object to retrieve the properties for. |
32
|
|
|
* @return ReflectionProperties The collection of reflection properties. |
33
|
|
|
*/ |
34
|
|
|
public static function ofThe(object $object): self |
35
|
|
|
{ |
36
|
|
|
$theClass = theClassOfThe($object); |
37
|
|
|
if (!alreadyCached($theClass, ReflectionProperties::$cache)) { |
38
|
|
|
$reflection = new ReflectionObject($object); |
39
|
|
|
$properties = []; |
40
|
|
|
$level = 0; |
41
|
|
|
do { |
42
|
|
|
$properties = self::addTo($properties, $level, $reflection); |
43
|
|
|
++$level; |
44
|
|
|
$reflection = $reflection->getParentClass(); |
45
|
|
|
} while($reflection); |
46
|
|
|
ReflectionProperties::$cache[$theClass] = new self(...$properties); |
47
|
|
|
} |
48
|
|
|
return ReflectionProperties::$cache[$theClass]; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** @inheritdoc */ |
52
|
|
|
public function current(): ReflectionProperty |
53
|
|
|
{ |
54
|
|
|
return parent::current(); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private static function addTo( |
58
|
|
|
array $properties, |
59
|
|
|
int $level, |
60
|
|
|
ReflectionClass $reflection |
61
|
|
|
): array { |
62
|
|
|
foreach ($reflection->getProperties() as $property) { |
63
|
|
|
try { |
64
|
|
|
$properties[] = ReflectionProperty::from($property, $level); |
65
|
|
|
} catch (ReflectionException $exception) { |
66
|
|
|
// skip inaccessible properties |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
return $properties; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|