Passed
Push — master ( 8f1ad4...65e262 )
by Daniel
06:10
created

DoctrineDbalEventStore::initialize()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 26
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 26
c 0
b 0
f 0
ccs 21
cts 21
cp 1
rs 8.8571
cc 2
eloc 19
nc 1
nop 0
crap 2
1
<?php
2
3
namespace DDDominio\EventSourcing\EventStore\Vendor;
4
5
use DDDominio\EventSourcing\Common\EventStream;
6
use DDDominio\EventSourcing\Common\EventStreamInterface;
7
use DDDominio\EventSourcing\EventStore\AbstractEventStore;
8
use DDDominio\EventSourcing\EventStore\ConcurrencyException;
9
use DDDominio\EventSourcing\EventStore\StoredEvent;
10
use Doctrine\DBAL\Connection;
11
use DDDominio\EventSourcing\Serialization\SerializerInterface;
12
use DDDominio\EventSourcing\Versioning\EventUpgrader;
13
use DDDominio\EventSourcing\Versioning\Version;
14
use Doctrine\DBAL\Schema\Schema;
15
use DDDominio\EventSourcing\EventStore\InitializableInterface;
16
17
class DoctrineDbalEventStore extends AbstractEventStore implements InitializableInterface
18
{
19
    const MAX_UNSIGNED_BIG_INT = 9223372036854775807;
20
    const STREAMS_TABLE = 'streams';
21
    const EVENTS_TABLE = 'events';
22
23
    /**
24
     * @var Connection
25
     */
26
    private $connection;
27
28
    /**
29
     * @param Connection $connection
30
     * @param SerializerInterface $serializer
31
     * @param EventUpgrader $eventUpgrader
32
     */
33 12
    public function __construct($connection, $serializer, $eventUpgrader)
34
    {
35 12
        parent::__construct($serializer, $eventUpgrader);
36 12
        $this->connection = $connection;
37 12
    }
38
39
    /**
40
     * @param string $streamId
41
     * @param int $start
42
     * @param int $count
43
     * @return EventStreamInterface
44
     */
45 4 View Code Duplication
    public function readStreamEvents($streamId, $start = 1, $count = null)
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...
46
    {
47 4
        if (!isset($count)) {
48 3
            $count = self::MAX_UNSIGNED_BIG_INT;
49
        }
50 4
        $stmt = $this->connection->prepare(
51
            'SELECT *
52
             FROM events
53
             WHERE stream_id = :streamId
54
             LIMIT :limit
55 4
             OFFSET :offset'
56
        );
57 4
        $stmt->bindValue(':streamId', $streamId);
58 4
        $stmt->bindValue(':offset', (int) $start - 1, \PDO::PARAM_INT);
59 4
        $stmt->bindValue(':limit', $count, \PDO::PARAM_INT);
60 4
        $stmt->execute();
61 4
        $results = $stmt->fetchAll();
62
63
        $storedEvents = array_map(function($result) {
64 3
            return new StoredEvent(
65 3
                $result['id'],
66 3
                $result['stream_id'],
67 3
                $result['type'],
68 3
                $result['event'],
69 3
                $result['metadata'],
70 3
                new \DateTimeImmutable($result['occurred_on']),
71 3
                Version::fromString($result['version'])
72
            );
73 4
        }, $results);
74
75 4
        return $this->domainEventStreamFromStoredEvents($storedEvents);
76
    }
77
78
    /**
79
     * @param string $streamId
80
     * @param \DateTimeImmutable $datetime
81
     * @param int $start
82
     * @return EventStreamInterface
83
     */
84
    public function readStreamEventsUntil($streamId, $datetime, $start = 1)
85
    {
86
        // TODO: Implement readStreamEventsUntil() method.
87
    }
88
89
    /**
90
     * @param string $streamId
91
     * @return EventStreamInterface
92
     */
93 6 View Code Duplication
    public function readFullStream($streamId)
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...
94
    {
95 6
        $stmt = $this->connection->prepare(
96
            'SELECT *
97
             FROM events
98 6
             WHERE stream_id = :streamId'
99
        );
100 6
        $stmt->bindValue(':streamId', $streamId);
101 6
        $stmt->execute();
102 6
        $results = $stmt->fetchAll();
103
104
        $storedEvents = array_map(function($result) {
105 5
            return new StoredEvent(
106 5
                $result['id'],
107 5
                $result['stream_id'],
108 5
                $result['type'],
109 5
                $result['event'],
110 5
                $result['metadata'],
111 5
                new \DateTimeImmutable($result['occurred_on']),
112 5
                Version::fromString($result['version'])
113
            );
114 6
        }, $results);
115
116 6
        return $this->domainEventStreamFromStoredEvents($storedEvents);
117
    }
118
119
    /**
120
     * @return EventStreamInterface[]
121
     */
122
    public function readAllStreams()
123
    {
124
        // TODO: Implement readAllStreams() method.
125
    }
126
127
    /**
128
     * @return EventStreamInterface
129
     */
130
    public function readAllEvents()
131
    {
132
        // TODO: Implement readAllEvents() method.
133
    }
134
135
    /**
136
     * @param string $type
137
     * @param Version $version
138
     * @return EventStreamInterface
139
     */
140 1 View Code Duplication
    protected function readStoredEventsOfTypeAndVersion($type, $version)
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...
141
    {
142 1
        $stmt = $this->connection->prepare(
143
            'SELECT *
144
             FROM events
145
             WHERE type = :type
146 1
             AND version = :version'
147
        );
148 1
        $stmt->bindValue(':type', $type);
149 1
        $stmt->bindValue(':version', $version);
150 1
        $stmt->execute();
151 1
        $results = $stmt->fetchAll();
152
153
        $storedEvents = array_map(function($result) {
154 1
            return new StoredEvent(
155 1
                $result['id'],
156 1
                $result['stream_id'],
157 1
                $result['type'],
158 1
                $result['event'],
159 1
                $result['metadata'],
160 1
                new \DateTimeImmutable($result['occurred_on']),
161 1
                Version::fromString($result['version'])
162
            );
163 1
        }, $results);
164
165 1
        return new EventStream($storedEvents);
166
    }
167
168
    /**
169
     * @param string $streamId
170
     * @param StoredEvent[] $storedEvents
171
     * @param int $expectedVersion
172
     */
173 7
    protected function appendStoredEvents($streamId, $storedEvents, $expectedVersion)
174
    {
175
        $this->connection->transactional(function() use ($streamId, $storedEvents, $expectedVersion) {
176 7 View Code Duplication
            if (!$this->streamExists($streamId)) {
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...
177 7
                $stmt = $this->connection
178 7
                    ->prepare('INSERT INTO streams (id) VALUES (:streamId)');
179 7
                $stmt->bindValue(':streamId', $streamId);
180 7
                $stmt->execute();
181
            }
182 7 View Code Duplication
            foreach ($storedEvents as $storedEvent) {
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...
183 7
                $stmt = $this->connection->prepare(
184
                    'INSERT INTO events (stream_id, type, event, metadata, occurred_on, version)
185 7
                 VALUES (:streamId, :type, :event, :metadata, :occurredOn, :version)'
186
                );
187 7
                $stmt->bindValue(':streamId', $streamId);
188 7
                $stmt->bindValue(':type', $storedEvent->type());
189 7
                $stmt->bindValue(':event', $storedEvent->data());
190 7
                $stmt->bindValue(':metadata', $storedEvent->metadata());
191 7
                $stmt->bindValue(':occurredOn', $storedEvent->occurredOn()->format('Y-m-d H:i:s'));
192 7
                $stmt->bindValue(':version', $storedEvent->version());
193 7
                $stmt->execute();
194
            }
195 7
            $streamFinalVersion = $this->streamVersion($streamId);
196 7
            if (count($storedEvents) !== $streamFinalVersion - $expectedVersion) {
197
                throw ConcurrencyException::fromVersions(
198
                    $this->streamVersion($streamId),
199
                    $expectedVersion
200
                );
201
            }
202 7
        });
203 7
    }
204
    /**
205
     * @param string $streamId
206
     * @return int
207
     */
208 7 View Code Duplication
    protected function streamVersion($streamId)
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...
209
    {
210 7
        $stmt = $this->connection
211 7
            ->prepare('SELECT COUNT(*) FROM events WHERE stream_id = :streamId');
212 7
        $stmt->bindValue(':streamId', $streamId);
213 7
        $stmt->execute();
214 7
        return intval($stmt->fetchColumn());
215
    }
216
217
    /**
218
     * @param string $streamId
219
     * @return bool
220
     */
221 8 View Code Duplication
    protected function streamExists($streamId)
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...
222
    {
223 8
        $stmt = $this->connection
224 8
            ->prepare('SELECT COUNT(*) FROM streams WHERE id = :streamId');
225 8
        $stmt->bindValue(':streamId', $streamId);
226 8
        $stmt->execute();
227 8
        return boolval($stmt->fetchColumn());
228
    }
229
230
    /**
231
     * Initialize the Event Store
232
     */
233 12
    public function initialize()
234
    {
235 12
        $schema = new Schema();
236
237 12
        $streamTable = $schema->createTable(self::STREAMS_TABLE);
238 12
        $streamTable->addColumn('id', 'string');
239 12
        $streamTable->setPrimaryKey(array("id"));
240
241 12
        $eventsTable = $schema->createTable(self::EVENTS_TABLE);
242 12
        $eventsTable->addColumn('id', 'integer', ['autoincrement' => true]);
243 12
        $eventsTable->addColumn('stream_id', 'string');
244 12
        $eventsTable->addColumn('type', 'string');
245 12
        $eventsTable->addColumn('event', 'text');
246 12
        $eventsTable->addColumn('metadata', 'text');
247 12
        $eventsTable->addColumn('occurred_on', 'datetime');
248 12
        $eventsTable->addColumn('version', 'string');
249 12
        $eventsTable->setPrimaryKey(['id']);
250 12
        $eventsTable->addForeignKeyConstraint($streamTable, ['stream_id'], ['id']);
251
252 12
        $queries = $schema->toSql($this->connection->getDatabasePlatform());
253 12
        $this->connection->transactional(function(Connection $connection) use ($queries) {
254 12
            foreach ($queries as $query) {
255 12
                $connection->exec($query);
256
            }
257 12
        });
258 12
    }
259
260
    /**
261
     * Check if the Event Store has been initialized
262
     *
263
     * @return bool
264
     */
265
    public function initialized()
266
    {
267
        return $this->connection->getSchemaManager()->tablesExist([self::STREAMS_TABLE]);
268
    }
269
270
    /**
271
     * @param string $streamId
272
     * @param \DateTimeImmutable $datetime
273
     * @return int
274
     */
275
    public function getStreamVersionAt($streamId, \DateTimeImmutable $datetime)
276
    {
277
        // TODO: Implement findStreamVersionAt() method.
278
    }
279
}
280