SnapshotAggregateRepository::saveSnapshot()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
/**
4
 * This file is part of the Cubiche package.
5
 *
6
 * Copyright (c) Cubiche
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Cubiche\Domain\EventSourcing\Snapshot;
13
14
use Cubiche\Domain\EventSourcing\AggregateRepository;
15
use Cubiche\Domain\EventSourcing\EventSourcedAggregateRootInterface;
16
use Cubiche\Domain\EventSourcing\EventStore\EventStoreInterface;
17
use Cubiche\Domain\EventSourcing\Snapshot\Policy\SnapshottingPolicyInterface;
18
use Cubiche\Domain\Model\IdInterface;
19
20
/**
21
 * SnapshotAggregateRepository class.
22
 *
23
 * @author Ivannis Suárez Jerez <[email protected]>
24
 */
25
class SnapshotAggregateRepository extends AggregateRepository
26
{
27
    /**
28
     * @var SnapshotStoreInterface
29
     */
30
    protected $snapshotStore;
31
32
    /**
33
     * @var SnapshottingPolicyInterface
34
     */
35
    protected $snapshottingPolicy;
36
37
    /**
38
     * AggregateRepository constructor.
39
     *
40
     * @param EventStoreInterface         $eventStore
41
     * @param SnapshotStoreInterface      $snapshotStore
42
     * @param SnapshottingPolicyInterface $snapshottingPolicy
43
     * @param string                      $aggregateClassName
44
     */
45
    public function __construct(
46
        EventStoreInterface $eventStore,
47
        SnapshotStoreInterface $snapshotStore,
48
        SnapshottingPolicyInterface $snapshottingPolicy,
49
        $aggregateClassName
50
    ) {
51
        parent::__construct($eventStore, $aggregateClassName);
52
53
        $this->snapshotStore = $snapshotStore;
54
        $this->snapshottingPolicy = $snapshottingPolicy;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function get(IdInterface $id)
61
    {
62
        $snapshot = $this->loadSnapshot($id);
63
        if ($snapshot !== null) {
64
            return $this->snapshotToAggregateRoot($snapshot);
65
        }
66
67
        return parent::get($id);
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function persist($element)
74
    {
75 View Code Duplication
        if (!$element instanceof EventSourcedAggregateRootInterface) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
76
            throw new \InvalidArgumentException(sprintf(
77
                'The object must be an instance of %s. Instance of %s given',
78
                EventSourcedAggregateRootInterface::class,
79
                is_object($element) ? get_class($element) : gettype($element)
80
            ));
81
        }
82
83
        if ($this->snapshottingPolicy->shouldCreateSnapshot($element)) {
84
            $this->saveSnapshot($element);
85
        }
86
87
        parent::persist($element);
88
    }
89
90
    /**
91
     * Load a aggregate snapshot from the storage.
92
     *
93
     * @param IdInterface $id
94
     *
95
     * @return Snapshot|null
96
     */
97
    protected function loadSnapshot(IdInterface $id)
98
    {
99
        return $this->snapshotStore->load($this->streamName($id));
100
    }
101
102
    /**
103
     * Save the aggregate snapshot.
104
     *
105
     * @param EventSourcedAggregateRootInterface $aggregateRoot
106
     */
107
    protected function saveSnapshot(EventSourcedAggregateRootInterface $aggregateRoot)
108
    {
109
        $snapshot = new Snapshot($this->streamName($aggregateRoot->id()), $aggregateRoot);
110
111
        $this->snapshotStore->persist($snapshot);
112
    }
113
114
    /**
115
     * @param Snapshot $snapshot
116
     *
117
     * @return EventSourcedAggregateRootInterface
118
     */
119
    protected function snapshotToAggregateRoot(Snapshot $snapshot)
120
    {
121
        $history = $this->eventStore->load(
122
            $this->streamName($snapshot->aggregate()->id()),
123
            $snapshot->version()
124
        );
125
126
        $aggregateRoot = $snapshot->aggregate();
127
128
        $aggregateRoot->setVersion($snapshot->version());
129
        $aggregateRoot->replay($history);
0 ignored issues
show
Bug introduced by
It seems like $history defined by $this->eventStore->load(..., $snapshot->version()) on line 121 can be null; however, Cubiche\Domain\EventSour...RootInterface::replay() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
130
131
        return $aggregateRoot;
132
    }
133
}
134