Completed
Push — master ( 0b2a25...ebfed1 )
by Iqbal
02:30
created

Pdo::getTransactionLevel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/*
3
 * This file is part of the Borobudur-Cqrs package.
4
 *
5
 * (c) Hexacodelabs <http://hexacodelabs.com>
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 Borobudur\Cqrs\ReadModel\Storage\Pdo;
12
13
use Borobudur\Collection\Collection;
14
use Borobudur\Cqrs\Exception\InvalidArgumentException;
15
use Borobudur\Cqrs\ReadModel\ReadModelInterface;
16
use Borobudur\Cqrs\ReadModel\Storage\Finder\Expression\CompositeExpressionInterface;
17
use Borobudur\Cqrs\ReadModel\Storage\Pdo\Exception\PdoException;
18
use Borobudur\Cqrs\ReadModel\Storage\Pdo\Expression\PdoCompositeExpression;
19
use Borobudur\Cqrs\ReadModel\Storage\StorageInterface;
20
use Borobudur\Cqrs\Serializer\DataTypeCasterTrait;
21
use Borobudur\Serialization\StringInterface;
22
use Borobudur\Serialization\ValuableInterface;
23
use PDO as PhpPdo;
24
use PDOStatement;
25
26
/**
27
 * @author      Iqbal Maulana <[email protected]>
28
 * @created     8/18/15
29
 */
30
class Pdo implements StorageInterface
0 ignored issues
show
Bug introduced by
There is one abstract method getTransactionalLevel in this class; you could implement it, or declare this class as abstract.
Loading history...
31
{
32
    use DataTypeCasterTrait;
33
34
    /**
35
     * @var PhpPdo
36
     */
37
    protected $conn;
38
39
    /**
40
     * @var PdoConfig
41
     */
42
    protected $config;
43
44
    /**
45
     * @var array
46
     */
47
    protected $quoteMaps = array('mysql' => '`', 'pgsql' => '"');
48
49
    /**
50
     * @var string
51
     */
52
    protected $quote = '`';
53
54
    /**
55
     * @var int
56
     */
57
    protected $transactionLevel = 0;
58
59
    /**
60
     * @var bool
61
     */
62
    protected $transactional = false;
63
64
    /**
65
     * Constructor.
66
     *
67
     * @param PdoConfig $config
68
     */
69
    public function __construct(PdoConfig $config)
70
    {
71
        try {
72
            $this->conn = new PhpPdo($config->getDsn(), $config->getUser(), $config->getPass());
73
            $this->conn->setAttribute(PhpPdo::ATTR_ERRMODE, PhpPdo::ERRMODE_EXCEPTION);
74
        } catch (\PDOException $e) {
75
            throw new PdoException($e);
76
        }
77
78
        $this->config = $config;
79
80
        if (isset($this->quoteMaps[$config->getEngine()])) {
81
            $this->quote = $this->quoteMaps[$config->getEngine()];
82
        }
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function save(ReadModelInterface $model, $table)
89
    {
90
        $class = get_class($model);
91
        $id = $this->resolveValue($model->getId());
92
        if (null !== $prev = $this->findById($id, $table, $class)) {
93
            $values = $this->normalize(array_merge($prev->serialize(), $model->serialize()));
94
            $conditions = $this->normalize(array('id' => $id));
95
            unset($values['id']);
96
            $this->exec($this->buildUpdateQuery($values, $conditions, $table), array_merge($values, $conditions));
97
98
            return;
99
        }
100
101
        $values = $this->normalize($model->serialize());
102
        $values['id'] = $id;
103
        $this->exec($this->buildInsertQuery($values, $table), $values);
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109
    public function remove($id, $table)
110
    {
111
        $values = array('id' => $this->resolveValue($id));
112
        $this->exec(sprintf('DELETE FROM %s WHERE id = :id', $this->quote($table)), $values);
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118
    public function findById($id, $table, $class)
119
    {
120
        $finder = $this->finder($table, $class);
121
122
        return $finder->where($finder->expr()->equal('id', $this->resolveValue($id)))->first();
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128
    public function finder($table, $class)
129
    {
130
        return new PdoFinder($this, $table, $class, $this->config->getParser(), $this->quote);
131
    }
132
133
    /**
134
     * Execute query without statement.
135
     *
136
     * @param string $sql
137
     * @param array  $values
138
     */
139
    public function exec($sql, array $values = array())
140
    {
141
        if (!empty($values)) {
142
            $normalized = array();
143
            foreach ($values as $index => $value) {
144
                $normalized[':' . $index] = $value;
145
            }
146
147
            $values = $normalized;
148
        }
149
150
        try {
151
            $conn = $this->conn->prepare($sql);
152
            $conn->execute($values);
153
        } catch (\PDOException $e) {
154
            throw new PdoException($e);
155
        }
156
    }
157
158
    /**
159
     * Execute query with statement.
160
     *
161
     * @param string $sql
162
     * @param int    $mode
163
     *
164
     * @return PDOStatement
165
     */
166
    public function query($sql, $mode = PhpPdo::FETCH_ASSOC)
167
    {
168
        try {
169
            return $this->conn->query($sql, $mode);
170
        } catch (\PDOException $e) {
171
            throw new PdoException($e);
172
        }
173
    }
174
175
    /**
176
     * @return int
177
     */
178
    public function getTransactionLevel()
179
    {
180
        return $this->transactionLevel;
181
    }
182
183
    /**
184
     * @return boolean
185
     */
186
    public function isTransactional()
187
    {
188
        return $this->transactional;
189
    }
190
191
    /**
192
     * Begin transaction
193
     */
194
    public function beginTransaction()
195
    {
196
        $this->transactional = true;
197
        if (0 === $this->transactionLevel) {
198
            $this->conn->beginTransaction();
199
        }
200
201
        $this->transactionLevel += 1;
202
    }
203
204
    /**
205
     * Rollback transaction
206
     */
207
    public function rollback()
208
    {
209
        $this->transactionLevel = 0;
210
        $this->transactional = false;
211
        $this->conn->rollBack();
212
    }
213
214
    /**
215
     * Commit transaction.
216
     */
217
    public function commit()
218
    {
219
        $this->transactionLevel -= 1;
220
        $this->transactional = false;
221
        if (0 === $this->transactionLevel) {
222
            $this->conn->commit();
223
        }
224
    }
225
226
    /**
227
     * Compute fields to expressions.
228
     *
229
     * @param array     $fields
230
     * @param PdoFinder $finder
231
     *
232
     * @return PdoCompositeExpression
233
     */
234
    protected function computeFieldsExpression(array $fields, PdoFinder $finder)
235
    {
236
        $expressions = array();
237
        foreach ($fields as $name => $value) {
238
            $expressions[] = $finder->expr()->equal($name, $value);
239
        }
240
241
        return new PdoCompositeExpression(CompositeExpressionInterface::LOGICAL_AND, $expressions);
242
    }
243
244
    /**
245
     * Normalize value.
246
     *
247
     * @param array $values
248
     *
249
     * @return array
250
     */
251
    protected function normalize(array $values)
252
    {
253
        foreach ($values as $name => $value) {
254
            if (is_array($value)) {
255
                throw new InvalidArgumentException(
256
                    sprintf(
257
                        'Cannot parse value with named "%s", data should be flat array.',
258
                        $name
259
                    )
260
                );
261
            }
262
263
            if (is_bool($value)) {
264
                $value = true === $value ? 'true' : 'false';
265
            }
266
267
            $values[$name] = self::castType($value);
268
        }
269
270
        return $values;
271
    }
272
273
    /**
274
     * Build query update.
275
     *
276
     * @param array  $values
277
     * @param array  $conditions
278
     * @param string $table
279
     *
280
     * @return string
281
     */
282
    protected function buildUpdateQuery(array $values, array $conditions, $table)
283
    {
284
        $sets = $this->buildDataSets($values);
285
        $wheres = $this->buildDataSets($conditions);
286
287
        return
288
            'UPDATE ' . $this->quote($table) .
289
            ' SET ' . implode(', ', $sets) .
290
            ' WHERE ' . implode(' AND ', $wheres);
291
    }
292
293
    /**
294
     * Build insert query.
295
     *
296
     * @param array  $values
297
     * @param string $table
298
     *
299
     * @return string
300
     */
301
    public function buildInsertQuery(array $values, $table)
302
    {
303
        $keys = array_map(array($this, 'quote'), array_keys($values));
304
        $values = array_keys($values);
305
306
        return
307
            'INSERT INTO ' . $this->quote($table) .
308
            ' (' . implode(', ', $keys) . ') VALUES (:' . implode(', :', $values) . ')';
309
    }
310
311
    /**
312
     * Build data sets.
313
     *
314
     * @param array $parts
315
     *
316
     * @return array
317
     */
318
    protected function buildDataSets(array $parts)
319
    {
320
        $sets = array();
321
        foreach ($parts as $name => $value) {
322
            $sets[] = $this->quote($name) . '=:' . $name;
323
        }
324
325
        return $sets;
326
    }
327
328
    /**
329
     * Quote field.
330
     *
331
     * @param string $field
332
     *
333
     * @return string
334
     */
335
    protected function quote($field)
336
    {
337
        return $this->quote . $field . $this->quote;
338
    }
339
340
    /**
341
     * @param mixed $value
342
     *
343
     * @return mixed|null|string
344
     */
345
    protected function resolveValue($value)
346
    {
347
        if ($value instanceof ValuableInterface) {
348
            return $value->getValue();
349
        }
350
351
        if ($value instanceof StringInterface) {
352
            return (string) $value;
353
        }
354
355
        return $value;
356
    }
357
}
358