FileSnapshotStore   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 54
wmc 5
lcom 1
cbo 3
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B get() 0 29 2
A save() 0 14 2
1
<?php
2
3
namespace Domain\Snapshotting;
4
5
use Symfony\Component\Finder\Finder;
6
use Domain\Identity\Identity;
7
use Domain\Aggregates\AggregateRoot;
8
use Domain\Snapshotting\Exception\IdenticalSnapshot;
9
10
/**
11
 * @author Sebastiaan Hilbers <[email protected]>
12
 */
13
class FileSnapshotStore implements SnapshotStore
14
{
15
    private $dataPath;
16
17
    public function __construct($dataPath)
18
    {
19
        $this->dataPath = $dataPath;
20
    }
21
22
    public function get(Identity $id, $criteria = null)
23
    {
24
        $it = Finder::create()
25
            ->files()
26
            ->name((string) $id . '-*')
27
            ->in($this->dataPath);
28
29
        $files = iterator_to_array($it);
30
31
        if (empty($files)) {
32
            throw new \Exception;
33
        }
34
35
        $match = end($files);
36
37
        $time = $match->getMTime();
38
        $creation = new \DateTime;
39
        $creation->setTimestamp($time);
40
41
        $aggregate = unserialize(file_get_contents($match));
42
43
        $snapshot = new Snapshot(
44
            $aggregate,
45
            $aggregate->getVersion(),
46
            $creation
47
        );
48
49
        return $snapshot;
50
    }
51
52
    public function save(AggregateRoot $root)
53
    {
54
        $aggregateId = (string) $root->getIdentity();
55
        $versionFile = $aggregateId . '-' . $root->getVersion();
56
57
        if (file_exists($this->dataPath . '/' . $versionFile)) {
58
            throw new IdenticalSnapshot;
59
        }
60
61
        $stream = fopen($this->dataPath . '/' . $versionFile, 'w');
62
63
        fwrite($stream, serialize($root));
64
        fclose($stream);
65
    }
66
}
67