shouldCreateSnapshot()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 3
nop 1
1
<?php
2
/**
3
 * This file is part of the Cubiche package.
4
 *
5
 * Copyright (c) Cubiche
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cubiche\Domain\EventSourcing\Snapshot\Policy;
12
13
use Cubiche\Domain\EventSourcing\EventSourcedAggregateRootInterface;
14
use Cubiche\Domain\EventSourcing\Snapshot\Snapshot;
15
use Cubiche\Domain\EventSourcing\Snapshot\SnapshotStoreInterface;
16
use Cubiche\Domain\EventSourcing\Utils\NameResolver;
17
use Cubiche\Domain\Model\IdInterface;
18
19
/**
20
 * TimeBasedSnapshottingPolicy class.
21
 *
22
 * @author Ivannis Suárez Jerez <[email protected]>
23
 */
24
class TimeBasedSnapshottingPolicy implements SnapshottingPolicyInterface
25
{
26
    /**
27
     * @var SnapshotStoreInterface
28
     */
29
    protected $snapshotStore;
30
31
    /**
32
     * @var string
33
     */
34
    protected $threshold;
35
36
    /**
37
     * @var string
38
     */
39
    protected $aggregateClassName;
40
41
    /**
42
     * TimeBasedSnapshottingPolicy constructor.
43
     *
44
     * @param SnapshotStoreInterface $snapshotStore
45
     * @param string                 $aggregateClassName
46
     * @param string                 $threshold
47
     */
48
    public function __construct(SnapshotStoreInterface $snapshotStore, $aggregateClassName, $threshold = '1 hour')
49
    {
50
        $this->snapshotStore = $snapshotStore;
51
        $this->threshold = $threshold;
52
53
        $this->aggregateClassName = $aggregateClassName;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function shouldCreateSnapshot(EventSourcedAggregateRootInterface $eventSourcedAggregateRoot)
60
    {
61
        $recordedEvents = $eventSourcedAggregateRoot->recordedEvents();
62
63
        if (count($recordedEvents) > 0) {
64
            $lastSnapshot = $this->loadSnapshot($eventSourcedAggregateRoot->id());
65
            $threshold = new \DateTime(date('c', strtotime('-'.$this->threshold)));
66
67
            if ($lastSnapshot !== null && $lastSnapshot->createdAt() < $threshold) {
68
                return true;
69
            }
70
        }
71
72
        return false;
73
    }
74
75
    /**
76
     * Load a aggregate snapshot from the storage.
77
     *
78
     * @param IdInterface $id
79
     *
80
     * @return Snapshot|null
81
     */
82
    protected function loadSnapshot(IdInterface $id)
83
    {
84
        return $this->snapshotStore->load($this->streamName($id));
85
    }
86
87
    /**
88
     * @return string
89
     */
90
    protected function streamName(IdInterface $id)
91
    {
92
        return NameResolver::resolve($this->aggregateClassName, $id);
93
    }
94
}
95