Completed
Push — master ( 935528...703206 )
by Philip
06:30
created

MySQLData::hasManySet()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 3

Importance

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