Completed
Push — master ( b1e76f...33be5a )
by James
02:05
created

AbstractSqlRepository   C

Complexity

Total Complexity 63

Size/Duplication

Total Lines 430
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 51.71%

Importance

Changes 40
Bugs 7 Features 3
Metric Value
wmc 63
c 40
b 7
f 3
lcom 1
cbo 7
dl 0
loc 430
ccs 106
cts 205
cp 0.5171
rs 5.8893

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