Completed
Push — master ( ecc0ad...758469 )
by Phil
03:50
created

AbstractSqlRepository   C

Complexity

Total Complexity 71

Size/Duplication

Total Lines 470
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 48.94%

Importance

Changes 46
Bugs 8 Features 3
Metric Value
wmc 71
c 46
b 8
f 3
lcom 1
cbo 7
dl 0
loc 470
ccs 115
cts 235
cp 0.4894
rs 5.5904

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A countFromRequest() 0 7 1
C getFromRequest() 0 34 7
C buildSortPart() 0 44 15
C buildQueryFromRules() 0 63 17
A countByField() 0 16 1
A acceptableField() 0 15 3
B getByField() 0 32 2
C attachRelationships() 0 62 10
B attachRelationshipsToCollection() 0 31 4
A getRelationshipBinds() 0 14 3
C getRelationshipMap() 0 39 7
getTable() 0 1 ?

How to fix   Complexity   

Complex Class

Complex classes like AbstractSqlRepository often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractSqlRepository, and based on these observations, apply Extract Interface, too.

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'])) ? '(' . $this->dbal->quote(explode(',', $where['value'])) . ')' : ':' . $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
                if (! in_array($delimiter, ['IN', 'NOT IN'])) {
179 1
                    $params[$where['binding']] = $where['value'];
180 1
                }
181 1
            }
182 1
        }
183
184 2
        if (array_key_exists('has', $rules)) {
185
            $keyword = (array_key_exists('filter', $rules)) ? ' AND' : ' WHERE';
186
187
            foreach ($rules['has'] as $has) {
188
                $relationship = $this->getRelationshipMap($has);
189
190
                $query .= sprintf(
191
                    '%s (SELECT COUNT(%s.%s) FROM %s WHERE %s.%s = %s.%s) > 0',
192
                    $keyword,
193
                    $relationship['defined_in']['table'],
194
                    $relationship['defined_in']['primary'],
195
                    $relationship['defined_in']['table'],
196
                    $relationship['defined_in']['table'],
197
                    $relationship['defined_in']['primary'],
198
                    $this->getTable(),
199
                    $relationship['defined_in']['entity']
200
                );
201
202
                $keyword = ' AND';
203
            }
204
        }
205
206 2
        if (array_key_exists('search', $rules) && $this->acceptableField($rules['search']['fields'])) {
207 1
            $keyword = (array_key_exists('filter', $rules)) ? ' AND' : ' WHERE';
208 1
            $query  .= sprintf('%s MATCH (%s) AGAINST (:match_bind IN BOOLEAN MODE)', $keyword, $rules['search']['fields']);
209 1
            $query  .= sprintf(' HAVING MATCH (%s) AGAINST (:match_bind) > :score_bind', $rules['search']['fields']);
210
211 1
            $params['match_bind'] = $rules['search']['term'];
212 1
            $params['score_bind'] = (array_key_exists('minscore', $rules)) ? $rules['minscore'] : 0;
213 1
        }
214
215 2
        return [$query, $params];
216
    }
217
218
    /**
219
     * Asserts that a field is acceptable to filter on.
220
     *
221
     * @param string $name
222
     *
223
     * @return boolean
224
     */
225 2
    protected function acceptableField($name)
226
    {
227 2
        $entity = $this->getEntityType();
228 2
        $entity = new $entity;
229
230 2
        foreach (explode(',', $name) as $field) {
231 2
            if (! array_key_exists($field, $entity->getMapping())) {
232 1
                throw new InvalidArgumentException(
233 1
                    sprintf('(%s) is not a whitelisted field to filter, search or sort by', $field)
234 1
                );
235
            }
236 1
        }
237
238 1
        return true;
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244 1
    public function countByField($field, $value, ServerRequestInterface $request = null)
245
    {
246 1
        $query = sprintf(
247 1
            "SELECT COUNT(*) as total FROM %s WHERE %s.%s IN (:%s)",
248 1
            $this->getTable(),
249 1
            $this->getTable(),
250 1
            $field,
251
            $field
252 1
        );
253
254
        $params = [
255
            $field => $value
256 1
        ];
257
258 1
        return (int) $this->dbal->fetchOne($query, $params)['total'];
259
    }
260
261
    /**
262
     * {@inheritdoc}
263
     */
264 1
    public function getByField($field, $value, ServerRequestInterface $request = null)
265
    {
266 1
        $query = sprintf(
267 1
            'SELECT * FROM %s WHERE %s.%s IN (:%s)',
268 1
            $this->getTable(),
269 1
            $this->getTable(),
270 1
            $field,
271
            $field
272 1
        );
273
        
274 1
        if (is_array($value)) {
275
            $query .= sprintf(
276
                ' ORDER BY FIND_IN_SET(%s.%s, ' . $this->dbal->quote(implode(',', $value)) . ')',
277
                $this->getTable(),
278
                $field
279
            );
280
        }
281
282
283
        // @todo - allow extra filtering from request
284
285
        $params = [
286
            $field => $value
287 1
        ];
288
289 1
        $collection = $this->buildCollection($this->dbal->fetchAll($query, $params))
290 1
                           ->setTotal($this->countByField($field, $value));
291
292 1
        $this->decorate($collection, StoreInterface::ON_READ);
293
294 1
        return $collection;
295
    }
296
297
    /**
298
     * {@inheritdoc}
299
     */
300 1
    public function attachRelationships(
301
        Collection $collection,
302
        $include                        = null,
303
        ServerRequestInterface $request = null
304
    ) {
305 1
        if (count($collection) === 0) {
306 1
            return;
307
        }
308
309
        if (is_null($include)) {
310
            return;
311
        }
312
313
        $rels = $collection->getIterator()->current()->getRelationshipMap();
314
315
        $rules = ($request instanceof ServerRequestInterface)
316
               ? $this->parseQueryString($request->getUri()->getQuery())
317
               : [];
318
319
        foreach ($this->getRelationshipMap() as $key => $map) {
320
            if (is_array($include) && ! in_array($key, $include)) {
321
                continue;
322
            }
323
324
            $binds = $this->getRelationshipBinds($collection, $key, $map['defined_in']['entity']);
325
326
            if (empty($binds)) {
327
                continue;
328
            }
329
330
            $query = sprintf(
331
                'SELECT * FROM %s LEFT JOIN %s ON %s.%s = %s.%s WHERE %s.%s IN (:relationships)',
332
                $map['defined_in']['table'],
333
                $map['target']['table'],
334
                $map['target']['table'],
335
                $map['target']['primary'],
336
                $map['defined_in']['table'],
337
                $map['target']['relationship'],
338
                $map['defined_in']['table'],
339
                $map['defined_in']['primary']
340
            );
341
342
            // @todo allow for further filtering of rels via request
343
344
            if (array_key_exists('sort', $rules)) {
345
                $whitelist = [];
346
347
                if (array_key_exists($key, $rels)) {
348
                    $entity    = $rels[$key];
349
                    $entity    = new $entity;
350
                    $mapping   = $entity->getMapping();
351
                    $whitelist = array_keys($mapping);
352
                }
353
354
                $query .= $this->buildSortPart($rules['sort'], $map['target']['table'], $whitelist);
355
            }
356
357
            $result = $this->dbal->fetchAll($query, ['relationships' => $binds]);
358
359
            $this->attachRelationshipsToCollection($collection, $key, $result);
360
        }
361
    }
362
363
    /**
364
     * Iterate a result set and attach the relationship to it's correct entity
365
     * within a collection.
366
     *
367
     * @param \Percy\Entity\Collection $collection
368
     * @param string                   $relationship
369
     * @param array                    $data
370
     *
371
     * @return void
372
     */
373
    protected function attachRelationshipsToCollection(Collection $collection, $relationship, array $data)
374
    {
375
        $map           = $this->getRelationshipMap($relationship);
376
        $relationships = array_column($data, $map['defined_in']['primary']);
377
378
        $remove = [$map['defined_in']['primary'], $map['target']['relationship']];
379
380
        foreach ($data as &$resource) {
381
            $resource = array_filter($resource, function ($key) use ($remove) {
382
                return (! in_array($key, $remove));
383
            }, ARRAY_FILTER_USE_KEY);
384
        }
385
386
        foreach ($collection->getIterator() as $entity) {
387
            $entityRels = $entity->getRelationshipMap();
388
389
            if (! array_key_exists($relationship, $entityRels)) {
390
                continue;
391
            }
392
393
            $keys = array_keys(preg_grep("/{$entity[$map['defined_in']['entity']]}/", $relationships));
394
            $rels = array_filter($data, function ($key) use ($keys) {
395
                return in_array($key, $keys);
396
            }, ARRAY_FILTER_USE_KEY);
397
398
            $rels = $this->buildCollection($rels, $entityRels[$relationship])->setTotal(count($rels));
399
            $this->decorate($rels, StoreInterface::ON_READ);
400
401
            $entity->addRelationship($relationship, $rels);
402
        }
403
    }
404
405
    /**
406
     * Return relationship bind conditional.
407
     *
408
     * @param \Percy\Entity\Collection $collection
409
     * @param string                   $relationship
410
     * @param string                   $key
411
     *
412
     * @return string
413
     */
414
    protected function getRelationshipBinds(Collection $collection, $relationship, $key)
415
    {
416
        $primaries = [];
417
418
        foreach ($collection->getIterator() as $entity) {
419
            if (! array_key_exists($relationship, $entity->getRelationshipMap())) {
420
                continue;
421
            }
422
423
            $primaries[] = $entity[$key];
424
        }
425
426
        return $primaries;
427
    }
428
429
    /**
430
     * Get possible relationships and the properties attached to them.
431
     *
432
     * @param string $relationship
433
     *
434
     * @throws \InvalidArgumentException when requested relationship is not defined
435
     * @throws \RuntimeException when map structure is defined incorrectly
436
     *
437
     * @return array
438
     */
439
    public function getRelationshipMap($relationship = null)
440
    {
441
        if (is_null($relationship)) {
442
            return $this->relationships;
443
        }
444
445
        if (! array_key_exists($relationship, $this->relationships)) {
446
            throw new InvalidArgumentException(
447
                sprintf('(%s) is not defined in the relationship map on (%s)', $relationship, get_class($this))
448
            );
449
        }
450
451
        $map = $this->relationships[$relationship];
452
453
        foreach ([
454
            'defined_in' => ['table', 'primary', 'entity'],
455
            'target'     => ['table', 'primary', 'relationship']
456
        ] as $key => $value) {
457
            if (! array_key_exists($key, $map) || ! is_array($map[$key])) {
458
                throw new RuntimeException(
459
                    sprintf(
460
                        'Relationship (%s) should contain the (%s) key and should be of type array on (%s)',
461
                        $relationship, $key, get_class($this)
462
                    )
463
                );
464
            }
465
466
            if (! empty(array_diff($value, array_keys($map[$key])))) {
467
                throw new RuntimeException(
468
                    sprintf(
469
                        '(%s) for relationship (%s) should contain keys (%s) on (%s)',
470
                        $key, $relationship, implode(', ', $value), get_class($this)
471
                    )
472
                );
473
            }
474
        }
475
476
        return $map;
477
    }
478
479
    /**
480
     * Returns table that repository is reading from.
481
     *
482
     * @return string
483
     */
484
    abstract protected function getTable();
485
}
486