1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Stratadox\EntityState; |
4
|
|
|
|
5
|
|
|
use ReflectionProperty; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Definition for new entities. |
9
|
|
|
* |
10
|
|
|
* @todo Provide a better way to extract the identifier |
11
|
|
|
* Current limitations: |
12
|
|
|
* - Identity must be in a single property (no compounds) |
13
|
|
|
* - Identity property cannot be located in a parent class |
14
|
|
|
* @author Stratadox |
15
|
|
|
*/ |
16
|
|
|
final class AnEntity implements DefinesEntityType |
17
|
|
|
{ |
18
|
|
|
private $class; |
19
|
|
|
private $identifierProperty; |
20
|
|
|
|
21
|
|
|
private function __construct( |
22
|
|
|
string $class, |
23
|
|
|
?ReflectionProperty $identifierProperty |
24
|
|
|
) { |
25
|
|
|
$this->class = $class; |
26
|
|
|
$this->identifierProperty = $identifierProperty; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param string $class The class to recognise. |
31
|
|
|
* @param string|null $identifierProperty The property to get the id from. |
32
|
|
|
* @return DefinesEntityType The new entity type definition. |
33
|
|
|
* @throws \ReflectionException When the property is inaccessible. |
34
|
|
|
*/ |
35
|
|
|
public static function whenEncountering( |
36
|
|
|
string $class, |
37
|
|
|
string $identifierProperty = null |
38
|
|
|
): DefinesEntityType { |
39
|
|
|
if (null === $identifierProperty) { |
40
|
|
|
return new self($class, null); |
41
|
|
|
} |
42
|
|
|
$property = new ReflectionProperty($class, $identifierProperty); |
43
|
|
|
$property->setAccessible(true); |
44
|
|
|
return new self($class, $property); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** @inheritdoc */ |
48
|
|
|
public function recognises(object $potentialEntity): bool |
49
|
|
|
{ |
50
|
|
|
return $potentialEntity instanceof $this->class; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** @inheritdoc */ |
54
|
|
|
public function idFor(object $recognisedEntity): ?string |
55
|
|
|
{ |
56
|
|
|
if (null === $this->identifierProperty) { |
57
|
|
|
return null; |
58
|
|
|
} |
59
|
|
|
return $this->identifierProperty->getValue($recognisedEntity); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|