|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Stratadox\EntityState\Internal; |
|
4
|
|
|
|
|
5
|
|
|
use function is_object; |
|
6
|
|
|
use Stratadox\EntityState\DefinesEntityType; |
|
7
|
|
|
use Stratadox\EntityState\PropertyState; |
|
8
|
|
|
|
|
9
|
|
|
final class NewEntityDetector implements Extractor |
|
10
|
|
|
{ |
|
11
|
|
|
private $next; |
|
12
|
|
|
private $newEntitiesProcessor; |
|
13
|
|
|
private $entityTypes; |
|
14
|
|
|
|
|
15
|
|
|
private function __construct( |
|
16
|
|
|
Extractor $next, |
|
17
|
|
|
AcceptsNewEntities $newEntities, |
|
18
|
|
|
DefinesEntityType ...$entityTypes |
|
19
|
|
|
) { |
|
20
|
|
|
$this->next = $next; |
|
21
|
|
|
$this->newEntitiesProcessor = $newEntities; |
|
22
|
|
|
$this->entityTypes = $entityTypes; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
public static function with( |
|
26
|
|
|
AcceptsNewEntities $newEntities, |
|
27
|
|
|
Extractor $next, |
|
28
|
|
|
DefinesEntityType ...$asEntities |
|
29
|
|
|
): Extractor { |
|
30
|
|
|
return new self($next, $newEntities, ...$asEntities); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function extract( |
|
34
|
|
|
ExtractionRequest $request, |
|
35
|
|
|
Extractor $baseExtractor = null |
|
36
|
|
|
): array { |
|
37
|
|
|
$subject = $request->value(); |
|
38
|
|
|
if (!is_object($subject) || $request->pointsToAKnownEntity()) { |
|
39
|
|
|
return $this->next->extract($request, $baseExtractor ?: $this); |
|
40
|
|
|
} |
|
41
|
|
|
foreach ($this->entityTypes as $definition) { |
|
42
|
|
|
if ($definition->recognises($subject)) { |
|
43
|
|
|
$id = $definition->idFor($subject); |
|
44
|
|
|
$this->newEntitiesProcessor->addAsNewEntity($subject, $id); |
|
45
|
|
|
return [PropertyState::with( |
|
46
|
|
|
(string) $request->objectName(), |
|
47
|
|
|
$id |
|
48
|
|
|
)]; |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
return $this->next->extract($request, $baseExtractor ?: $this); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|