NewEntityDetector   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 43
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
B extract() 0 19 7
A with() 0 6 1
A __construct() 0 8 1
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