UnitOfWork::registerDataMapper()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Behavioral;
6
7
use SplObjectStorage;
8
use DataSource\Connection;
9
use DataSource\DataMapper\AbstractMapper;
10
use BasePatterns\LayerSupertype\DomainObject;
11
12
class UnitOfWork
13
{
14
    private SplObjectStorage $newObjects;
15
16
    private SplObjectStorage $dirtyObjects;
17
18
    private SplObjectStorage $removedObjects;
19
20
    private array $mappers = [];
21
22
    private Connection $connection;
23
24 1
    public function __construct(Connection $connection)
25
    {
26 1
        $this->newObjects = new SplObjectStorage();
27 1
        $this->dirtyObjects = new SplObjectStorage();
28 1
        $this->removedObjects = new SplObjectStorage();
29 1
        $this->connection = $connection;
30 1
    }
31
32
    public function registerNew(DomainObject $object): void
33
    {
34
        $this->newObjects->attach($object);
35
    }
36
37
    public function registerDirty(DomainObject $object): void
38
    {
39
        if (!$this->removedObjects->contains($object)
40
            && !$this->dirtyObjects->contains($object)
41
            && !$this->newObjects->contains($object)
42
        ) {
43
            $this->dirtyObjects->attach($object);
44
        }
45
    }
46
47
    public function registerRemoved(DomainObject $object): void
48
    {
49
        if ($this->newObjects->contains($object)) {
50
            $this->newObjects->detach($object);
51
52
            return;
53
        }
54
55
        $this->dirtyObjects->detach($object);
56
        if (!$this->removedObjects->contains($object)) {
57
            $this->removedObjects->attach($object);
58
        }
59
    }
60
61 1
    public function registerDataMapper(string $className, string $mapperClassName): void
62
    {
63 1
        $this->mappers[$className] = new $mapperClassName($this->connection);
64 1
    }
65
66 1
    public function getDataMapper(string $className): AbstractMapper
67
    {
68 1
        if (\array_key_exists($className, $this->mappers)) {
69 1
            return $this->mappers[$className];
70
        }
71
72
        throw new \DomainException(
73
            \sprintf("Unable to find mapper for class `%s`", $className)
74
        );
75
    }
76
}
77