Completed
Pull Request — master (#255)
by Kristof
11:31
created

AggregateAwareDBALEventStore::load()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 17
rs 9.4285
cc 3
eloc 10
nc 4
nop 1
1
<?php
2
3
namespace CultuurNet\UDB3\EventSourcing\DBAL;
4
5
use Broadway\Domain\DateTime as BroadwayDateTime;
6
use Broadway\Domain\DomainEventStream;
7
use Broadway\Domain\DomainEventStreamInterface;
8
use Broadway\Domain\DomainMessage;
9
use Broadway\EventStore\DBALEventStoreException;
10
use Broadway\EventStore\EventStoreInterface;
11
use Broadway\EventStore\EventStreamNotFoundException;
12
use Broadway\Serializer\SerializerInterface;
13
use Doctrine\DBAL\Connection;
14
use Doctrine\DBAL\DBALException;
15
use Doctrine\DBAL\Schema\Schema;
16
use Doctrine\DBAL\Schema\Table;
17
18
class AggregateAwareDBALEventStore implements EventStoreInterface
19
{
20
    /**
21
     * @var Connection
22
     */
23
    private $connection;
24
25
    /**
26
     * @var SerializerInterface
27
     */
28
    private $payloadSerializer;
29
30
    /**
31
     * @var SerializerInterface
32
     */
33
    private $metadataSerializer;
34
35
    /**
36
     * @var null
37
     */
38
    private $loadStatement = null;
39
40
    /**
41
     * @var string
42
     */
43
    private $tableName;
44
45
    /**
46
     * @var string
47
     */
48
    private $aggregateType;
49
50
    /**
51
     * @param Connection $connection
52
     * @param SerializerInterface $payloadSerializer
53
     * @param SerializerInterface $metadataSerializer
54
     * @param string $tableName
55
     * @param string $aggregateType
56
     */
57
    public function __construct(
58
        Connection $connection,
59
        SerializerInterface $payloadSerializer,
60
        SerializerInterface $metadataSerializer,
61
        $tableName,
62
        $aggregateType
63
    ) {
64
        $this->connection         = $connection;
65
        $this->payloadSerializer  = $payloadSerializer;
66
        $this->metadataSerializer = $metadataSerializer;
67
        $this->tableName          = $tableName;
68
        $this->aggregateType      = $aggregateType;
69
    }
70
71
    /**
72
     * {@inheritDoc}
73
     */
74
    public function load($id)
75
    {
76
        $statement = $this->prepareLoadStatement();
77
        $statement->bindValue('uuid', $id);
78
        $statement->execute();
79
80
        $events = array();
81
        while ($row = $statement->fetch()) {
82
            $events[] = $this->deserializeEvent($row);
83
        }
84
85
        if (empty($events)) {
86
            throw new EventStreamNotFoundException(sprintf('EventStream not found for aggregate with id %s', $id));
87
        }
88
89
        return new DomainEventStream($events);
90
    }
91
92
    /**
93
     * {@inheritDoc}
94
     */
95
    public function append($id, DomainEventStreamInterface $eventStream)
96
    {
97
        // The original Broadway implementation did only check the type of $id.
98
        // It is better to test all uuids inside the event stream.
99
        $this->guardStream($eventStream);
0 ignored issues
show
Unused Code introduced by
The call to the method CultuurNet\UDB3\EventSou...entStore::guardStream() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
100
101
        // Make the transaction more robust by using the transactional statement.
102
        $this->connection->transactional(function (Connection $connection) use ($eventStream) {
103
            try {
104
                foreach ($eventStream as $domainMessage) {
105
                    $this->insertMessage($connection, $domainMessage);
106
                }
107
            } catch (DBALException $exception) {
108
                throw DBALEventStoreException::create($exception);
109
            }
110
        });
111
    }
112
113
    /**
114
     * @param Connection $connection
115
     * @param DomainMessage $domainMessage
116
     */
117
    private function insertMessage(Connection $connection, DomainMessage $domainMessage)
118
    {
119
        $data = array(
120
            'uuid'           => (string) $domainMessage->getId(),
121
            'playhead'       => $domainMessage->getPlayhead(),
122
            'metadata'       => json_encode($this->metadataSerializer->serialize($domainMessage->getMetadata())),
123
            'payload'        => json_encode($this->payloadSerializer->serialize($domainMessage->getPayload())),
124
            'recorded_on'    => $domainMessage->getRecordedOn()->toString(),
125
            'type'           => $domainMessage->getType(),
126
            'aggregate_type' => $this->aggregateType
127
        );
128
129
        $connection->insert($this->tableName, $data);
130
    }
131
132
    /**
133
     * @param Schema $schema
134
     * @return Table|null
135
     */
136
    public function configureSchema(Schema $schema)
137
    {
138
        if ($schema->hasTable($this->tableName)) {
139
            return null;
140
        }
141
142
        return $this->configureTable();
143
    }
144
145
    /**
146
     * @return mixed
147
     */
148
    public function configureTable()
149
    {
150
        $schema = new Schema();
151
152
        $table = $schema->createTable($this->tableName);
153
154
        $table->addColumn('id', 'integer', array('autoincrement' => true));
155
        $table->addColumn('uuid', 'guid', array('length' => 36,));
156
        $table->addColumn('playhead', 'integer', array('unsigned' => true));
157
        $table->addColumn('payload', 'text');
158
        $table->addColumn('metadata', 'text');
159
        $table->addColumn('recorded_on', 'string', array('length' => 32));
160
        $table->addColumn('type', 'string', array('length' => 128));
161
        $table->addColumn('aggregate_type', 'string', array('length' => 128));
162
163
        $table->setPrimaryKey(array('id'));
164
165
        $table->addUniqueIndex(array('uuid', 'playhead'));
166
167
        $table->addIndex(['type']);
168
        $table->addIndex(['aggregate_type']);
169
170
        return $table;
171
    }
172
173
    /**
174
     * @return \Doctrine\DBAL\Driver\Statement|null
175
     */
176
    private function prepareLoadStatement()
177
    {
178
        if (null === $this->loadStatement) {
179
            $queryBuilder = $this->connection->createQueryBuilder();
180
181
            $queryBuilder->select(
182
                ['uuid', 'playhead', 'metadata', 'payload', 'recorded_on']
183
            )
184
                ->from($this->tableName)
185
                ->where('uuid = :uuid')
186
                ->orderBy('playhead', 'ASC');
187
188
            $this->loadStatement = $this->connection->prepare(
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->connection->prepa...queryBuilder->getSQL()) of type object<Doctrine\DBAL\Driver\Statement> is incompatible with the declared type null of property $loadStatement.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
189
                $queryBuilder->getSQL()
190
            );
191
        }
192
193
        return $this->loadStatement;
194
    }
195
196
    /**
197
     * @param $row
198
     * @return DomainMessage
199
     */
200 View Code Duplication
    private function deserializeEvent($row)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
201
    {
202
        return new DomainMessage(
203
            $row['uuid'],
204
            $row['playhead'],
205
            $this->metadataSerializer->deserialize(json_decode($row['metadata'], true)),
206
            $this->payloadSerializer->deserialize(json_decode($row['payload'], true)),
207
            BroadwayDateTime::fromString($row['recorded_on'])
208
        );
209
    }
210
211
    /**
212
     * @param DomainEventStreamInterface $eventStream
213
     */
214
    private function guardStream(DomainEventStreamInterface $eventStream)
215
    {
216
        foreach ($eventStream as $domainMessage) {
217
            /** @var DomainMessage $domainMessage */
218
            $id = (string) $domainMessage->getId();
0 ignored issues
show
Unused Code introduced by
$id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
219
        }
220
    }
221
}
222