Completed
Push — master ( de794a...d36be2 )
by James
9s
created

AbstractSqlRepository::countByField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

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