Completed
Push — master ( d36be2...7f9690 )
by Phil
8s
created

AbstractSqlRepository::buildQueryFromRules()   C

Complexity

Conditions 16
Paths 60

Size

Total Lines 61
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 38.4677

Importance

Changes 13
Bugs 1 Features 1
Metric Value
c 13
b 1
f 1
dl 0
loc 61
ccs 25
cts 45
cp 0.5556
rs 6.2087
cc 16
eloc 38
nc 60
nop 2
crap 38.4677

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Percy\Repository;
4
5
use Aura\Sql\ExtendedPdoInterface;
6
use InvalidArgumentException;
7
use Percy\Decorator\DecoratorTrait;
8
use Percy\Entity\Collection;
9
use Percy\Entity\CollectionBuilderTrait;
10
use Percy\Entity\EntityInterface;
11
use Percy\Http\QueryStringParserTrait;
12
use Percy\Store\StoreInterface;
13
use Psr\Http\Message\ServerRequestInterface;
14
use RuntimeException;
15
16
abstract class AbstractSqlRepository implements RepositoryInterface
17
{
18
    use CollectionBuilderTrait;
19
    use DecoratorTrait;
20
    use QueryStringParserTrait;
21
22
    /**
23
     * @var \Aura\Sql\ExtendedPdoInterface
24
     */
25
    protected $dbal;
26
27
    /**
28
     *
29
     * @var mixed
30
     */
31
    protected $relationships = [];
32
33
    /**
34
     * Construct.
35
     *
36
     * @param \Aura\Sql\ExtendedPdoInterface $dbal
37
     */
38 4
    public function __construct(ExtendedPdoInterface $dbal)
39
    {
40 4
        $this->dbal = $dbal;
41 4
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 1
    public function countFromRequest(ServerRequestInterface $request)
47
    {
48 1
        $rules = $this->parseQueryString($request->getUri()->getQuery());
49 1
        list($query, $params) = $this->buildQueryFromRules($rules, true);
50
51 1
        return (int) $this->dbal->fetchOne($query, $params)['total'];
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 2
    public function getFromRequest(ServerRequestInterface $request)
58
    {
59 2
        $rules = $this->parseQueryString($request->getUri()->getQuery());
60
61 2
        list($query, $params) = $this->buildQueryFromRules($rules);
62
63 2
        if (array_key_exists('sort', $rules) && ! array_key_exists('search', $rules)) {
64 2
            $entity    = $this->getEntityType();
65 2
            $entity    = new $entity;
66 2
            $mapping   = $entity->getMapping();
67 2
            $whitelist = array_keys($mapping);
68
69 2
            $query .= $this->buildSortPart($rules['sort'], $this->getTable(), $whitelist);
70 1
        }
71
72 1
        if (array_key_exists('search', $rules) && $this->acceptableField($rules['search']['fields'])) {
73 1
            $query .= sprintf(' ORDER BY MATCH (%s) AGAINST (:match_bind) > :score_bind', $rules['search']['fields']);
74 1
        }
75
76 1
        if (array_key_exists('limit', $rules)) {
77 1
            $query .= ' LIMIT ';
78 1
            $query .= (array_key_exists('offset', $rules)) ? sprintf('%d,', $rules['offset']) : '';
79 1
            $query .= sprintf('%d', $rules['limit']);
80 1
        }
81
82 1
        $query = trim(preg_replace('!\s+!', ' ', $query));
83
84 1
        $collection = $this->buildCollection($this->dbal->fetchAll($query, $params))
85 1
                           ->setTotal($this->countFromRequest($request));
86
87 1
        $this->decorate($collection, StoreInterface::ON_READ);
88
89 1
        return $collection;
90
    }
91
92
    /**
93
     * Build the sort part of the query.
94
     *
95
     * @param array|string $sorts
96
     * @param string       $table
97
     * @param array        $whitelist
98
     *
99
     * @return string
100
     */
101 2
    protected function buildSortPart($sorts, $table, array $whitelist)
102
    {
103 2
        if (is_string($sorts) && $sorts === 'RAND()') {
104 1
            return ' ORDER BY RAND()';
105
        }
106
107 2
        if (! is_array($sorts)) {
108
            return '';
109
        }
110
111 2
        $fields = [];
112
113 2
        foreach ($sorts as $sort) {
114 2
            $field = explode('.', $sort['field']);
115
116 2
            if (count($field) !== 2) {
117 1
                throw new InvalidArgumentException('Sort paramater is formatted incorrectly');
118
            }
119
120 2
            if ($field[0] !== $table && count($sorts) > 1) {
121 1
                continue;
122
            }
123
124 2
            if ($field[0] !== $table && count($sorts) < 2 && $field[0] === $this->getTable()) {
125
                continue;
126
            }
127
128 2
            if ($field[0] !== $table && count($sorts) < 2) {
129 1
                throw new InvalidArgumentException(
130 1
                    sprintf('(%s) is not a whitelisted field to sort by', $sort['field'])
131 1
                );
132
            }
133
134 2
            if (! in_array($field[1], $whitelist)) {
135 1
                throw new InvalidArgumentException(
136 1
                    sprintf('(%s) is not a whitelisted field to sort by', $sort['field'])
137 1
                );
138
            }
139
140 1
            $fields[] = sprintf('%s %s', $sort['field'], strtoupper($sort['direction']));
141 1
        }
142
143 1
        return (empty($fields)) ? '' : sprintf(' ORDER BY %s', implode(', ', $fields));
144
    }
145
146
    /**
147
     * Build a base query without sorting and limits from filter rules.
148
     *
149
     * @param array   $rules
150
     * @param boolean $count
151
     *
152
     * @return array
153
     */
154 2
    protected function buildQueryFromRules(array $rules, $count = false)
155
    {
156 2
        $start = ($count === false) ? 'SELECT * FROM ' : 'SELECT *, COUNT(*) as total FROM ';
157 2
        $query = $start . $this->getTable();
158
159 2
        $params = [];
160
161 2
        if (array_key_exists('filter', $rules)) {
162 2
            foreach ($rules['filter'] as $key => $where) {
163 2
                $this->acceptableField($where['field']);
164
165 1
                $isNull = ($where['value'] === 'null') ? true : false;
166
167 1
                $keyword   = ($key === 0) ? ' WHERE' : ' AND';
168 1
                $delimiter = strtoupper($where['delimiter']);
169 1
                $binding   = (in_array($delimiter, ['IN', 'NOT IN'])) ? sprintf('(:%s)', $where['binding']) : ':' . $where['binding'];
170
171 1
                if ($isNull === true) {
172
                    $delimiter = ($delimiter === '=') ? 'IS' : 'IS NOT';
173
                    $binding   = 'null';
174
                }
175
176 1
                $query .= sprintf('%s %s %s %s', $keyword, $where['field'], $delimiter, $binding);
177
178 1
                $params[$where['binding']] = $where['value'];
179 1
            }
180 1
        }
181
182 2
        if (array_key_exists('has', $rules)) {
183
            $keyword = (array_key_exists('filter', $rules)) ? ' AND' : ' WHERE';
184
185
            foreach ($rules['has'] as $has) {
186
                $relationship = $this->getRelationshipMap($has);
187
188
                $query .= sprintf(
189
                    '%s (SELECT COUNT(%s.%s) FROM %s WHERE %s.%s = %s.%s) > 0',
190
                    $keyword,
191
                    $relationship['defined_in']['table'],
192
                    $relationship['defined_in']['primary'],
193
                    $relationship['defined_in']['table'],
194
                    $relationship['defined_in']['table'],
195
                    $relationship['defined_in']['primary'],
196
                    $this->getTable(),
197
                    $relationship['defined_in']['entity']
198
                );
199
200
                $keyword = ' AND';
201
            }
202
        }
203
204 2
        if (array_key_exists('search', $rules) && $this->acceptableField($rules['search']['fields'])) {
205 1
            $keyword = (array_key_exists('filter', $rules)) ? ' AND' : ' WHERE';
206 1
            $query  .= sprintf('%s MATCH (%s) AGAINST (:match_bind IN BOOLEAN MODE)', $keyword, $rules['search']['fields']);
207 1
            $query  .= sprintf(' HAVING MATCH (%s) AGAINST (:match_bind) > :score_bind', $rules['search']['fields']);
208
209 1
            $params['match_bind'] = $rules['search']['term'];
210 1
            $params['score_bind'] = (array_key_exists('minscore', $rules)) ? $rules['minscore'] : 0;
211 1
        }
212
213 2
        return [$query, $params];
214
    }
215
216
    /**
217
     * Asserts that a field is acceptable to filter on.
218
     *
219
     * @param string $name
220
     *
221
     * @return boolean
222
     */
223 2
    protected function acceptableField($name)
224
    {
225 2
        $entity = $this->getEntityType();
226 2
        $entity = new $entity;
227
228 2
        foreach (explode(',', $name) as $field) {
229 2
            if (! array_key_exists($name, $entity->getMapping())) {
230 1
                throw new InvalidArgumentException(
231 1
                    sprintf('(%s) is not a whitelisted field to filter, search or sort by', $name)
232 1
                );
233
            }
234 1
        }
235
236 1
        return true;
237
    }
238
239
    /**
240
     * {@inheritdoc}
241
     */
242 1
    public function countByField($field, $value, ServerRequestInterface $request = null)
243
    {
244 1
        $query = sprintf(
245 1
            "SELECT COUNT(*) as total FROM %s WHERE %s.%s IN (:%s)",
246 1
            $this->getTable(),
247 1
            $this->getTable(),
248 1
            $field,
249
            $field
250 1
        );
251
252
        $params = [
253
            $field => $value
254 1
        ];
255
256 1
        return (int) $this->dbal->fetchOne($query, $params)['total'];
257
    }
258
259
    /**
260
     * {@inheritdoc}
261
     */
262 1
    public function getByField($field, $value, ServerRequestInterface $request = null)
263
    {
264 1
        $query = sprintf(
265 1
            'SELECT * FROM %s WHERE %s.%s IN (:%s)',
266 1
            $this->getTable(),
267 1
            $this->getTable(),
268 1
            $field,
269
            $field
270 1
        );
271
272
        // @todo - allow extra filtering from request
273
274
        $params = [
275
            $field => $value
276 1
        ];
277
278 1
        $collection = $this->buildCollection($this->dbal->fetchAll($query, $params))
279 1
                           ->setTotal($this->countByField($field, $value));
280
281 1
        $this->decorate($collection, StoreInterface::ON_READ);
282
283 1
        return $collection;
284
    }
285
286
    /**
287
     * {@inheritdoc}
288
     */
289 1
    public function attachRelationships(
290
        Collection $collection,
291
        $include                        = null,
292
        ServerRequestInterface $request = null
293
    ) {
294 1
        if (count($collection) === 0) {
295 1
            return;
296
        }
297
298
        if (is_null($include)) {
299
            return;
300
        }
301
302
        $rels = $collection->getIterator()->current()->getRelationshipMap();
303
304
        $rules = ($request instanceof ServerRequestInterface)
305
               ? $this->parseQueryString($request->getUri()->getQuery())
306
               : [];
307
308
        foreach ($this->getRelationshipMap() as $key => $map) {
309
            if (is_array($include) && ! in_array($key, $include)) {
310
                continue;
311
            }
312
313
            $binds = $this->getRelationshipBinds($collection, $key, $map['defined_in']['entity']);
314
315
            if (empty($binds)) {
316
                continue;
317
            }
318
319
            $query = sprintf(
320
                'SELECT * FROM %s LEFT JOIN %s ON %s.%s = %s.%s WHERE %s.%s IN (:relationships)',
321
                $map['defined_in']['table'],
322
                $map['target']['table'],
323
                $map['target']['table'],
324
                $map['target']['primary'],
325
                $map['defined_in']['table'],
326
                $map['target']['relationship'],
327
                $map['defined_in']['table'],
328
                $map['defined_in']['primary']
329
            );
330
331
            // @todo allow for further filtering of rels via request
332
333
            if (array_key_exists('sort', $rules)) {
334
                $whitelist = [];
335
336
                if (array_key_exists($key, $rels)) {
337
                    $entity    = $rels[$key];
338
                    $entity    = new $entity;
339
                    $mapping   = $entity->getMapping();
340
                    $whitelist = array_keys($mapping);
341
                }
342
343
                $query .= $this->buildSortPart($rules['sort'], $map['target']['table'], $whitelist);
344
            }
345
346
            $result = $this->dbal->fetchAll($query, ['relationships' => $binds]);
347
348
            $this->attachRelationshipsToCollection($collection, $key, $result);
349
        }
350
    }
351
352
    /**
353
     * Iterate a result set and attach the relationship to it's correct entity
354
     * within a collection.
355
     *
356
     * @param \Percy\Entity\Collection $collection
357
     * @param string                   $relationship
358
     * @param array                    $data
359
     *
360
     * @return void
361
     */
362
    protected function attachRelationshipsToCollection(Collection $collection, $relationship, array $data)
363
    {
364
        $map           = $this->getRelationshipMap($relationship);
365
        $relationships = array_column($data, $map['defined_in']['primary']);
366
367
        $remove = [$map['defined_in']['primary'], $map['target']['relationship']];
368
369
        foreach ($data as &$resource) {
370
            $resource = array_filter($resource, function ($key) use ($remove) {
371
                return (! in_array($key, $remove));
372
            }, ARRAY_FILTER_USE_KEY);
373
        }
374
375
        foreach ($collection->getIterator() as $entity) {
376
            $entityRels = $entity->getRelationshipMap();
377
378
            if (! array_key_exists($relationship, $entityRels)) {
379
                continue;
380
            }
381
382
            $keys = array_keys(preg_grep("/{$entity[$map['defined_in']['entity']]}/", $relationships));
383
            $rels = array_filter($data, function ($key) use ($keys) {
384
                return in_array($key, $keys);
385
            }, ARRAY_FILTER_USE_KEY);
386
387
            $rels = $this->buildCollection($rels, $entityRels[$relationship])->setTotal(count($rels));
388
            $this->decorate($rels, StoreInterface::ON_READ);
389
390
            $entity->addRelationship($relationship, $rels);
391
        }
392
    }
393
394
    /**
395
     * Return relationship bind conditional.
396
     *
397
     * @param \Percy\Entity\Collection $collection
398
     * @param string                   $relationship
399
     * @param string                   $key
400
     *
401
     * @return string
402
     */
403
    protected function getRelationshipBinds(Collection $collection, $relationship, $key)
404
    {
405
        $primaries = [];
406
407
        foreach ($collection->getIterator() as $entity) {
408
            if (! array_key_exists($relationship, $entity->getRelationshipMap())) {
409
                continue;
410
            }
411
412
            $primaries[] = $entity[$key];
413
        }
414
415
        return $primaries;
416
    }
417
418
    /**
419
     * Get possible relationships and the properties attached to them.
420
     *
421
     * @param string $relationship
422
     *
423
     * @throws \InvalidArgumentException when requested relationship is not defined
424
     * @throws \RuntimeException when map structure is defined incorrectly
425
     *
426
     * @return array
427
     */
428
    public function getRelationshipMap($relationship = null)
429
    {
430
        if (is_null($relationship)) {
431
            return $this->relationships;
432
        }
433
434
        if (! array_key_exists($relationship, $this->relationships)) {
435
            throw new InvalidArgumentException(
436
                sprintf('(%s) is not defined in the relationship map on (%s)', $relationship, get_class($this))
437
            );
438
        }
439
440
        $map = $this->relationships[$relationship];
441
442
        foreach ([
443
            'defined_in' => ['table', 'primary', 'entity'],
444
            'target'     => ['table', 'primary', 'relationship']
445
        ] as $key => $value) {
446
            if (! array_key_exists($key, $map) || ! is_array($map[$key])) {
447
                throw new RuntimeException(
448
                    sprintf(
449
                        'Relationship (%s) should contain the (%s) key and should be of type array on (%s)',
450
                        $relationship, $key, get_class($this)
451
                    )
452
                );
453
            }
454
455
            if (! empty(array_diff($value, array_keys($map[$key])))) {
456
                throw new RuntimeException(
457
                    sprintf(
458
                        '(%s) for relationship (%s) should contain keys (%s) on (%s)',
459
                        $key, $relationship, implode(', ', $value), get_class($this)
460
                    )
461
                );
462
            }
463
        }
464
465
        return $map;
466
    }
467
468
    /**
469
     * Returns table that repository is reading from.
470
     *
471
     * @return string
472
     */
473
    abstract protected function getTable();
474
}
475