Completed
Push — master ( 24ed3a...5b7e22 )
by Philip
02:21
created

MySQLData::getReferenceIds()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file is part of the CRUDlex package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[email protected]>
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 CRUDlex;
13
14
use Doctrine\DBAL\Connection;
15
use Doctrine\DBAL\Query\QueryBuilder;
16
17
/**
18
 * MySQL Data implementation using a given Doctrine DBAL instance.
19
 */
20
class MySQLData extends AbstractData {
21
22
    /**
23
     * Holds the Doctrine DBAL instance.
24
     */
25
    protected $database;
26
27
    /**
28
     * Flag whether to use UUIDs as primary key.
29
     */
30
    protected $useUUIDs;
31
32
    /**
33
     * Sets the values and parameters of the upcoming given query according
34
     * to the entity.
35
     *
36
     * @param Entity $entity
37
     * the entity with its fields and values
38
     * @param QueryBuilder $queryBuilder
39
     * the upcoming query
40
     * @param string $setMethod
41
     * what method to use on the QueryBuilder: 'setValue' or 'set'
42
     */
43
    protected function setValuesAndParameters(Entity $entity, QueryBuilder $queryBuilder, $setMethod) {
44
        $formFields = $this->getFormFields();
45
        $count      = count($formFields);
46
        for ($i = 0; $i < $count; ++$i) {
47
            $type  = $this->definition->getType($formFields[$i]);
48
            $value = $entity->get($formFields[$i]);
49
            if ($type == 'boolean') {
50
                $value = $value ? 1 : 0;
51
            }
52
            if ($type == 'reference' && is_array($value)) {
53
                $value = $value['id'];
54
            }
55
            $queryBuilder->$setMethod('`'.$formFields[$i].'`', '?');
56
            $queryBuilder->setParameter($i, $value);
57
        }
58
    }
59
60
    /**
61
     * Checks whether the by id given entity still has children referencing it.
62
     *
63
     * @param integer $id
64
     * the current entities id
65
     *
66
     * @return boolean
67
     * true if the entity still has children
68
     */
69
    protected function hasChildren($id) {
70
        foreach ($this->definition->getChildren() as $child) {
71
            $queryBuilder = $this->database->createQueryBuilder();
72
            $queryBuilder
73
                ->select('COUNT(id)')
74
                ->from('`'.$child[0].'`', '`'.$child[0].'`')
75
                ->where('`'.$child[1].'` = ?')
76
                ->andWhere('deleted_at IS NULL')
77
                ->setParameter(0, $id);
78
            $queryResult = $queryBuilder->execute();
79
            $result      = $queryResult->fetch(\PDO::FETCH_NUM);
80
            if ($result[0] > 0) {
81
                return true;
82
            }
83
        }
84
        return false;
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    protected function doDelete(Entity $entity, $deleteCascade) {
91
        $result = $this->shouldExecuteEvents($entity, 'before', 'delete');
92
        if (!$result) {
93
            return static::DELETION_FAILED_EVENT;
94
        }
95
        $id = $entity->get('id');
96
        if ($deleteCascade) {
97
            $this->deleteChildren($id, $deleteCascade);
98
        } elseif ($this->hasChildren($id)) {
99
            return static::DELETION_FAILED_STILL_REFERENCED;
100
        }
101
102
        $query = $this->database->createQueryBuilder();
103
        $query
104
            ->update('`'.$this->definition->getTable().'`')
105
            ->set('deleted_at', 'UTC_TIMESTAMP()')
106
            ->where('id = ?')
107
            ->setParameter(0, $id);
108
109
        $query->execute();
110
        $this->shouldExecuteEvents($entity, 'after', 'delete');
111
        return static::DELETION_SUCCESS;
112
    }
113
114
    /**
115
     * Gets all possible many-to-many ids existing for this definition.
116
     *
117
     * @param array $fields
118
     * the many field names to fetch for
119
     * @param $params
120
     * the parameters the possible many field values to fetch for
121
     * @return array
122
     * an array of this many-to-many ids
123
     */
124
    protected function getManyIds(array $fields, array $params) {
125
        $manyIds = [];
126
        foreach ($fields as $field) {
127
            $thisField    = $this->definition->getSubTypeField($field, 'many', 'thisField');
128
            $thatField    = $this->definition->getSubTypeField($field, 'many', 'thatField');
129
            $queryBuilder = $this->database->createQueryBuilder();
130
            $queryBuilder
131
                ->select('`'.$thisField.'`')
132
                ->from($field)
133
                ->where('`'.$thatField.'` IN (?)')
134
                ->setParameter(0, array_column($params[$field], 'id'), Connection::PARAM_STR_ARRAY)
135
                ->groupBy('`'.$thisField.'`')
136
            ;
137
            $queryResult = $queryBuilder->execute();
138
            $manyResults = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
139
            $manyIds     = array_merge($manyIds, array_column($manyResults, $thisField));
140
141
        }
142
        return $manyIds;
143
    }
144
145
    /**
146
     * Adds sorting parameters to the query.
147
     *
148
     * @param QueryBuilder $queryBuilder
149
     * the query
150
     * @param $filter
151
     * the filter all resulting entities must fulfill, the keys as field names
152
     * @param $filterOperators
153
     * the operators of the filter like "=" defining the full condition of the field
154
     */
155
    protected function addFilter(QueryBuilder $queryBuilder, array $filter, array $filterOperators) {
156
        $i          = 0;
157
        $manyFields = [];
158
        foreach ($filter as $field => $value) {
159
            if ($this->definition->getType($field) === 'many') {
160
                $manyFields[] = $field;
161
                continue;
162
            }
163
            if ($value === null) {
164
                $queryBuilder->andWhere('`'.$field.'` IS NULL');
165
            } else {
166
                $operator = array_key_exists($field, $filterOperators) ? $filterOperators[$field] : '=';
167
                $queryBuilder
168
                    ->andWhere('`'.$field.'` '.$operator.' ?')
169
                    ->setParameter($i, $value, \PDO::PARAM_STR);
170
            }
171
            $i++;
172
        }
173
        $idsToInclude = $this->getManyIds($manyFields, $filter);
174
        if (!empty($idsToInclude)) {
175
            $queryBuilder
176
                ->andWhere('id IN (?)')
177
                ->setParameter($i, $idsToInclude, Connection::PARAM_STR_ARRAY)
178
            ;
179
        }
180
    }
181
182
    /**
183
     * Adds pagination parameters to the query.
184
     *
185
     * @param QueryBuilder $queryBuilder
186
     * the query
187
     * @param integer|null $skip
188
     * the rows to skip
189
     * @param integer|null $amount
190
     * the maximum amount of rows
191
     */
192
    protected function addPagination(QueryBuilder $queryBuilder, $skip, $amount) {
193
        $queryBuilder->setMaxResults(9999999999);
194
        if ($amount !== null) {
195
            $queryBuilder->setMaxResults(abs(intval($amount)));
196
        }
197
        if ($skip !== null) {
198
            $queryBuilder->setFirstResult(abs(intval($skip)));
199
        }
200
    }
201
202
    /**
203
     * Adds sorting parameters to the query.
204
     *
205
     * @param QueryBuilder $queryBuilder
206
     * the query
207
     * @param string|null $sortField
208
     * the sort field
209
     * @param boolean|null $sortAscending
210
     * true if sort ascending, false if descending
211
     */
212
    protected function addSort(QueryBuilder $queryBuilder, $sortField, $sortAscending) {
213
        if ($sortField !== null) {
214
215
            $type = $this->definition->getType($sortField);
216
            if ($type === 'many') {
217
                $sortField = $this->definition->getInitialSortField();
218
            }
219
220
            $order = $sortAscending === true ? 'ASC' : 'DESC';
221
            $queryBuilder->orderBy('`'.$sortField.'`', $order);
222
        }
223
    }
224
225
    /**
226
     * Adds the id and name of referenced entities to the given entities. The
227
     * reference field is before the raw id of the referenced entity and after
228
     * the fetch, it's an array with the keys id and name.
229
     *
230
     * @param Entity[] &$entities
231
     * the entities to fetch the references for
232
     * @param string $field
233
     * the reference field
234
     */
235
    protected function fetchReferencesForField(array &$entities, $field) {
236
        $nameField    = $this->definition->getSubTypeField($field, 'reference', 'nameField');
237
        $queryBuilder = $this->database->createQueryBuilder();
238
239
        $ids = $this->getReferenceIds($entities, $field);
240
241
        $referenceEntity = $this->definition->getSubTypeField($field, 'reference', 'entity');
242
        $table           = $this->definition->getServiceProvider()->getData($referenceEntity)->getDefinition()->getTable();
243
        $queryBuilder
244
            ->from('`'.$table.'`', '`'.$table.'`')
245
            ->where('id IN (?)')
246
            ->andWhere('deleted_at IS NULL');
247
        if ($nameField) {
248
            $queryBuilder->select('id', $nameField);
249
        } else {
250
            $queryBuilder->select('id');
251
        }
252
253
        $queryBuilder->setParameter(0, $ids, Connection::PARAM_STR_ARRAY);
254
255
        $queryResult = $queryBuilder->execute();
256
        $rows        = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
257
        $amount      = count($entities);
258
        foreach ($rows as $row) {
259
            for ($i = 0; $i < $amount; ++$i) {
260
                if ($entities[$i]->get($field) == $row['id']) {
261
                    $value = ['id' => $entities[$i]->get($field)];
262
                    if ($nameField) {
263
                        $value['name'] = $row[$nameField];
264
                    }
265
                    $entities[$i]->set($field, $value);
266
                }
267
            }
268
        }
269
    }
270
271
    /**
272
     * Generates a new UUID.
273
     *
274
     * @return string|null
275
     * the new UUID or null if this instance isn't configured to do so
276
     */
277
    protected function generateUUID() {
278
        $uuid = null;
279
        if ($this->useUUIDs) {
280
            $sql    = 'SELECT UUID() as id';
281
            $result = $this->database->fetchAssoc($sql);
282
            $uuid   = $result['id'];
283
        }
284
        return $uuid;
285
    }
286
287
    /**
288
     * Enriches the given mapping of entity id to raw entity data with some many-to-many data.
289
     *
290
     * @param array $idToData
291
     * a reference to the map entity id to raw entity data
292
     * @param $manyField
293
     * the many field to enrich data with
294
     */
295
    protected function enrichWithManyField(&$idToData, $manyField) {
296
        $queryBuilder = $this->database->createQueryBuilder();
297
        $nameField    = $this->definition->getSubTypeField($manyField, 'many', 'nameField');
298
        $thisField    = $this->definition->getSubTypeField($manyField, 'many', 'thisField');
299
        $thatField    = $this->definition->getSubTypeField($manyField, 'many', 'thatField');
300
        $entity       = $this->definition->getSubTypeField($manyField, 'many', 'entity');
301
        $entityTable  = $this->definition->getServiceProvider()->getData($entity)->getDefinition()->getTable();
302
        $nameSelect   = $nameField !== null ? ', t2.`'.$nameField.'` AS name' : '';
303
        $queryBuilder
304
            ->select('t1.`'.$thisField.'` AS this, t1.`'.$thatField.'` AS id'.$nameSelect)
305
            ->from('`'.$manyField.'`', 't1')
306
            ->leftJoin('t1', '`'.$entityTable.'`', 't2', 't2.id = t1.`'.$thatField.'`')
307
            ->where('t1.`'.$thisField.'` IN (?)')
308
            ->andWhere('t2.deleted_at IS NULL');
309
        $queryBuilder->setParameter(0, array_keys($idToData), Connection::PARAM_STR_ARRAY);
310
        $queryResult    = $queryBuilder->execute();
311
        $manyReferences = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
312
        foreach ($manyReferences as $manyReference) {
313
            $entityId = $manyReference['this'];
314
            unset($manyReference['this']);
315
            $idToData[$entityId][$manyField][] = $manyReference;
316
        }
317
    }
318
319
    /**
320
     * First, deletes all to the given entity related many-to-many entries from the DB
321
     * and then writes them again.
322
     *
323
     * @param Entity $entity
324
     * the entity to save the many-to-many entries of
325
     */
326
    protected function saveMany(Entity $entity) {
327
        $manyFields = $this->getManyFields();
328
        $id         = $entity->get('id');
329
        foreach ($manyFields as $manyField) {
330
            $thisField = $this->definition->getSubTypeField($manyField, 'many', 'thisField');
331
            $thatField = $this->definition->getSubTypeField($manyField, 'many', 'thatField');
332
            $this->database->delete($manyField, [$thisField => $id]);
333
            $manyValues = $entity->get($manyField) ?: [];
334
            foreach ($manyValues as $thatId) {
335
                $this->database->insert($manyField, [
336
                    $thisField => $id,
337
                    $thatField => $thatId['id']
338
                ]);
339
            }
340
        }
341
    }
342
343
    /**
344
     * Adds the id and name of referenced entities to the given entities. Each
345
     * reference field is before the raw id of the referenced entity and after
346
     * the fetch, it's an array with the keys id and name.
347
     *
348
     * @param Entity[] &$entities
349
     * the entities to fetch the references for
350
     *
351
     * @return void
352
     */
353
    protected function enrichWithReference(array &$entities) {
354
        if (empty($entities)) {
355
            return;
356
        }
357
        foreach ($this->definition->getFieldNames() as $field) {
358
            if ($this->definition->getType($field) !== 'reference') {
359
                continue;
360
            }
361
            $this->fetchReferencesForField($entities, $field);
362
        }
363
    }
364
365
    /**
366
     * Constructor.
367
     *
368
     * @param EntityDefinition $definition
369
     * the entity definition
370
     * @param FileProcessorInterface $fileProcessor
371
     * the file processor to use
372
     * @param $database
373
     * the Doctrine DBAL instance to use
374
     * @param boolean $useUUIDs
375
     * flag whether to use UUIDs as primary key
376
     */
377
    public function __construct(EntityDefinition $definition, FileProcessorInterface $fileProcessor, $database, $useUUIDs) {
378
        $this->definition    = $definition;
379
        $this->fileProcessor = $fileProcessor;
380
        $this->database      = $database;
381
        $this->useUUIDs      = $useUUIDs;
382
    }
383
384
    /**
385
     * {@inheritdoc}
386
     */
387
    public function get($id) {
388
        $entities = $this->listEntries(['id' => $id]);
389
        if (count($entities) == 0) {
390
            return null;
391
        }
392
        return $entities[0];
393
    }
394
395
    /**
396
     * {@inheritdoc}
397
     */
398
    public function listEntries(array $filter = [], array $filterOperators = [], $skip = null, $amount = null, $sortField = null, $sortAscending = null) {
399
        $fieldNames = $this->definition->getFieldNames();
400
401
        $queryBuilder = $this->database->createQueryBuilder();
402
        $table        = $this->definition->getTable();
403
        $queryBuilder
404
            ->select('`'.implode('`,`', $fieldNames).'`')
405
            ->from('`'.$table.'`', '`'.$table.'`')
406
            ->where('deleted_at IS NULL');
407
408
        $this->addFilter($queryBuilder, $filter, $filterOperators);
409
        $this->addPagination($queryBuilder, $skip, $amount);
410
        $this->addSort($queryBuilder, $sortField, $sortAscending);
411
412
        $queryResult = $queryBuilder->execute();
413
        $rows        = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
414
        $rows        = $this->enrichWithMany($rows);
415
        $entities    = [];
416
        foreach ($rows as $row) {
417
            $entities[] = $this->hydrate($row);
418
        }
419
        $this->enrichWithReference($entities);
420
        return $entities;
421
    }
422
423
    /**
424
     * {@inheritdoc}
425
     */
426
    public function create(Entity $entity) {
427
428
        $result = $this->shouldExecuteEvents($entity, 'before', 'create');
429
        if (!$result) {
430
            return false;
431
        }
432
433
        $queryBuilder = $this->database->createQueryBuilder();
434
        $queryBuilder
435
            ->insert('`'.$this->definition->getTable().'`')
436
            ->setValue('created_at', 'UTC_TIMESTAMP()')
437
            ->setValue('updated_at', 'UTC_TIMESTAMP()')
438
            ->setValue('version', 0);
439
440
441
        $this->setValuesAndParameters($entity, $queryBuilder, 'setValue');
442
443
        $id = $this->generateUUID();
444
        if ($this->useUUIDs) {
445
            $queryBuilder->setValue('`id`', '?');
446
            $uuidI = count($this->getFormFields());
447
            $queryBuilder->setParameter($uuidI, $id);
448
        }
449
450
        $queryBuilder->execute();
451
452
        if (!$this->useUUIDs) {
453
            $id = $this->database->lastInsertId();
454
        }
455
456
        $this->enrichEntityWithMetaData($id, $entity);
457
        $this->saveMany($entity);
458
        $entities = [$entity];
459
        $this->enrichWithReference($entities);
460
461
        $this->shouldExecuteEvents($entity, 'after', 'create');
462
463
        return true;
464
    }
465
466
    /**
467
     * {@inheritdoc}
468
     */
469
    public function update(Entity $entity) {
470
471
        if (!$this->shouldExecuteEvents($entity, 'before', 'update')) {
472
            return false;
473
        }
474
475
        $queryBuilder = $this->database->createQueryBuilder();
476
        $queryBuilder->update('`'.$this->definition->getTable().'`')
477
            ->set('updated_at', 'UTC_TIMESTAMP()')
478
            ->set('version', 'version + 1')
479
            ->where('id = ?')
480
            ->setParameter(count($this->getFormFields()), $entity->get('id'));
481
482
        $this->setValuesAndParameters($entity, $queryBuilder, 'set');
483
        $affected = $queryBuilder->execute();
484
485
        $this->saveMany($entity);
486
        $entities = [$entity];
487
        $this->enrichWithReference($entities);
488
489
        $this->shouldExecuteEvents($entity, 'after', 'update');
490
491
        return $affected;
492
    }
493
494
    /**
495
     * {@inheritdoc}
496
     */
497
    public function getIdToNameMap($entity, $nameField) {
498
        $nameSelect   = $nameField !== null ? ',`'.$nameField.'`' : '';
499
        $drivingField = $nameField ?: 'id';
500
501
        $table        = $this->definition->getServiceProvider()->getData($entity)->getDefinition()->getTable();
502
        $queryBuilder = $this->database->createQueryBuilder();
503
        $queryBuilder
504
            ->select('id'.$nameSelect)
505
            ->from('`'.$table.'`', 't1')
506
            ->where('deleted_at IS NULL')
507
            ->orderBy($drivingField)
508
        ;
509
        $queryResult    = $queryBuilder->execute();
510
        $manyReferences = $queryResult->fetchAll(\PDO::FETCH_ASSOC);
511
        $result         = array_reduce($manyReferences, function(&$carry, $manyReference) use ($drivingField) {
512
            $carry[$manyReference['id']] = $manyReference[$drivingField];
513
            return $carry;
514
        }, []);
515
        return $result;
516
    }
517
518
    /**
519
     * {@inheritdoc}
520
     */
521
    public function countBy($table, array $params, array $paramsOperators, $excludeDeleted) {
522
        $queryBuilder = $this->database->createQueryBuilder();
523
        $queryBuilder
524
            ->select('COUNT(id)')
525
            ->from('`'.$table.'`', '`'.$table.'`')
526
        ;
527
528
        $deletedExcluder = 'where';
529
        $i               = 0;
530
        $manyFields      = [];
531
        foreach ($params as $name => $value) {
532
            if ($this->definition->getType($name) === 'many') {
533
                $manyFields[] = $name;
534
                continue;
535
            }
536
            $queryBuilder
537
                ->andWhere('`'.$name.'` '.$paramsOperators[$name].' ?')
538
                ->setParameter($i, $value, \PDO::PARAM_STR)
539
            ;
540
            $i++;
541
            $deletedExcluder = 'andWhere';
542
        }
543
544
        $idsToInclude = $this->getManyIds($manyFields, $params);
545
        if (!empty($idsToInclude)) {
546
            $queryBuilder
547
                ->andWhere('id IN (?)')
548
                ->setParameter($i, $idsToInclude, Connection::PARAM_STR_ARRAY)
549
            ;
550
            $deletedExcluder = 'andWhere';
551
        }
552
553
        if ($excludeDeleted) {
554
            $queryBuilder->$deletedExcluder('deleted_at IS NULL');
555
        }
556
557
        $queryResult = $queryBuilder->execute();
558
        $result      = $queryResult->fetch(\PDO::FETCH_NUM);
559
        return intval($result[0]);
560
    }
561
562
    /**
563
     * {@inheritdoc}
564
     */
565
    public function hasManySet($field, array $thatIds, $excludeId = null) {
566
        $thisField    = $this->definition->getSubTypeField($field, 'many', 'thisField');
567
        $thatField    = $this->definition->getSubTypeField($field, 'many', 'thatField');
568
        $thatEntity   = $this->definition->getSubTypeField($field, 'many', 'entity');
569
        $entityTable  = $this->definition->getServiceProvider()->getData($thatEntity)->getDefinition()->getTable();
570
        $queryBuilder = $this->database->createQueryBuilder();
571
        $queryBuilder->select('t1.`'.$thisField.'` AS this, t1.`'.$thatField.'` AS that')
572
            ->from('`'.$field.'`', 't1')
573
            ->leftJoin('t1', '`'.$entityTable.'`', 't2', 't2.id = t1.`'.$thatField.'`')
574
            ->where('t2.deleted_at IS NULL')
575
            ->orderBy('this, that');
576
        if ($excludeId !== null) {
577
            $queryBuilder->andWhere('t1.`'.$thisField.'` != ?')->setParameter(0, $excludeId);
578
        }
579
        $existingMany = $queryBuilder->execute()->fetchAll(\PDO::FETCH_ASSOC);
580
        $existingMap  = array_reduce($existingMany, function(&$carry, $existing) {
581
            $carry[$existing['this']][] = $existing['that'];
582
            return $carry;
583
        }, []);
584
        sort($thatIds);
585
        return in_array($thatIds, array_values($existingMap));
586
    }
587
588
}
589