Completed
Push — master ( e5d2f6...54b77c )
by Phil
02:08
created

AbstractSqlRepository::buildSortPart()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 7.7656

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 22
ccs 9
cts 12
cp 0.75
rs 6.9811
cc 7
eloc 11
nc 8
nop 2
crap 7.7656
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 2
    public function __construct(ExtendedPdoInterface $dbal)
39
    {
40 2
        $this->dbal = $dbal;
41 2
    }
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 1
    public function getFromRequest(ServerRequestInterface $request)
58
    {
59 1
        $rules = $this->parseQueryString($request->getUri()->getQuery());
60
61 1
        list($query, $params) = $this->buildQueryFromRules($rules);
62
63 1
        if (array_key_exists('sort', $rules) && ! array_key_exists('search', $rules)) {
64 1
            $query .= $this->buildSortPart($rules['sort'], $this->getTable());
65 1
        }
66
67 1
        if (array_key_exists('search', $rules)) {
68
            $query .= sprintf(' ORDER BY MATCH (%s) AGAINST (:match_bind) > :score_bind', $rules['search']['fields']);
69
        }
70
71 1
        if (array_key_exists('limit', $rules)) {
72 1
            $query .= ' LIMIT ';
73 1
            $query .= (array_key_exists('offset', $rules)) ? sprintf('%d,', $rules['offset']) : '';
74 1
            $query .= $rules['limit'];
75 1
        }
76
77 1
        $query = trim(preg_replace('!\s+!', ' ', $query));
78
79 1
        $collection = $this->buildCollection($this->dbal->fetchAll($query, $params))
80 1
                           ->setTotal($this->countFromRequest($request));
81
82 1
        $this->decorate($collection, StoreInterface::ON_READ);
83
84 1
        return $collection;
85
    }
86
87
    /**
88
     * Build the sort part of the query.
89
     *
90
     * @param array|string $sorts
91
     * @param string $table
92
     *
93
     * @return string
94
     */
95 1
    protected function buildSortPart($sorts, $table)
96
    {
97 1
        if (is_string($sorts) && $sorts === 'RAND()') {
98
            return ' ORDER BY RAND()';
99
        }
100
101 1
        if (! is_array($sorts)) {
102
            return '';
103
        }
104
105 1
        $fields = [];
106
107 1
        foreach ($sorts as $sort) {
108 1
            if (substr($sort['field'], 0, strlen($table)) !== $table) {
109
                continue;
110
            }
111
112 1
            $fields[] = sprintf('%s %s', $sort['field'], strtoupper($sort['direction']));
113 1
        }
114
115 1
        return (empty($fields)) ? '' : sprintf(' ORDER BY %s', implode(', ', $fields));
116
    }
117
118
    /**
119
     * Build a base query without sorting and limits from filter rules.
120
     *
121
     * @param array   $rules
122
     * @param boolean $count
123
     *
124
     * @return array
125
     */
126 1
    protected function buildQueryFromRules(array $rules, $count = false)
127
    {
128 1
        $start = ($count === false) ? 'SELECT * FROM ' : 'SELECT *, COUNT(*) as total FROM ';
129
130 1
        $query = $start . $this->getTable();
131
132 1
        $params = [];
133
134 1
        if (array_key_exists('filter', $rules)) {
135 1
            foreach ($rules['filter'] as $key => $where) {
136 1
                $keyword   = ($key === 0) ? ' WHERE' : ' AND';
137 1
                $delimiter = strtoupper($where['delimiter']);
138 1
                $binding   = (in_array($delimiter, ['IN', 'NOT IN'])) ? sprintf('(:%s)', $where['binding']) : ':' . $where['binding'];
139 1
                $query    .= sprintf('%s %s %s %s', $keyword, $where['field'], $delimiter, $binding);
140
141 1
                $params[$where['binding']] = $where['value'];
142 1
            }
143 1
        }
144
145 1
        if (array_key_exists('search', $rules)) {
146
            $keyword = (array_key_exists('filter', $rules)) ? ' AND' : ' WHERE';
147
            $query  .= sprintf('%s MATCH (%s) AGAINST (:match_bind IN BOOLEAN MODE)', $keyword, $rules['search']['columns']);
148
            $query  .= sprintf(' HAVING MATCH (%s) AGAINST (:match_bind) > :score_bind', $rules['search']['columns']);
149
150
            $params['match_bind'] = $rules['search']['term'];
151
            $params['score_bind'] = (array_key_exists('minscore', $rules)) ? $rules['minscore'] : 0;
152
        }
153
154 1
        return [$query, $params];
155
    }
156
157
    /**
158
     * {@inheritdoc}
159
     */
160 1
    public function countByField($field, $value, ServerRequestInterface $request = null)
161
    {
162 1
        $query = sprintf(
163 1
            "SELECT COUNT(*) as total FROM %s WHERE %s.%s IN (:%s)",
164 1
            $this->getTable(),
165 1
            $this->getTable(),
166 1
            $field,
167
            $field
168 1
        );
169
170
        $params = [
171 1
            $field => implode(',', (array) $value)
172 1
        ];
173
174 1
        return (int) $this->dbal->fetchOne($query, $params)['total'];
175
    }
176
177
    /**
178
     * {@inheritdoc}
179
     */
180 1
    public function getByField($field, $value, ServerRequestInterface $request = null)
181
    {
182 1
        $query = sprintf(
183 1
            'SELECT * FROM %s WHERE %s.%s IN (:%s)',
184 1
            $this->getTable(),
185 1
            $this->getTable(),
186 1
            $field,
187
            $field
188 1
        );
189
190
        // @todo - allow extra filtering from request
191
192
        $params = [
193 1
            $field => implode(',', (array) $value)
194 1
        ];
195
196 1
        $collection = $this->buildCollection($this->dbal->fetchAll($query, $params))
197 1
                           ->setTotal($this->countByField($field, $value));
198
199 1
        $this->decorate($collection, StoreInterface::ON_READ);
200
201 1
        return $collection;
202
    }
203
204
    /**
205
     * {@inheritdoc}
206
     */
207
    public function attachRelationships(
208
        Collection $collection,
209
        $include                        = null,
210
        ServerRequestInterface $request = null
211
    ) {
212
        if (is_null($include)) {
213
            return;
214
        }
215
216
        $rules = ($request instanceof ServerRequestInterface)
217
               ? $this->parseQueryString($request->getUri()->getQuery())
218
               : [];
219
220
        foreach ($this->getRelationshipMap() as $key => $map) {
221
            if (is_array($include) && ! in_array($key, $include)) {
222
                continue;
223
            }
224
225
            $binds = $this->getRelationshipBinds($collection, $key, $map['defined_in']['entity']);
226
227
            if (empty($binds)) {
228
                continue;
229
            }
230
231
            $query = sprintf(
232
                'SELECT * FROM %s LEFT JOIN %s ON %s.%s = %s.%s WHERE %s.%s IN (%s)',
233
                $map['defined_in']['table'],
234
                $map['target']['table'],
235
                $map['target']['table'],
236
                $map['target']['primary'],
237
                $map['defined_in']['table'],
238
                $map['target']['relationship'],
239
                $map['defined_in']['table'],
240
                $map['defined_in']['primary'],
241
                implode(',', $binds)
242
            );
243
244
            if (array_key_exists('sort', $rules)) {
245
                $query .= $this->buildSortPart($rules['sort'], $map['target']['table']);
246
            }
247
248
            $result = $this->dbal->fetchAll($query, []);
249
250
            $this->attachRelationshipsToCollection($collection, $key, $result);
251
        }
252
    }
253
254
    /**
255
     * Iterate a result set and attach the relationship to it's correct entity
256
     * within a collection.
257
     *
258
     * @param \Percy\Entity\Collection $collection
259
     * @param string                   $relationship
260
     * @param array                    $data
261
     *
262
     * @return void
263
     */
264
    protected function attachRelationshipsToCollection(Collection $collection, $relationship, array $data)
265
    {
266
        $map           = $this->getRelationshipMap($relationship);
267
        $relationships = array_column($data, $map['defined_in']['primary']);
268
269
        $remove = [$map['defined_in']['primary'], $map['target']['relationship']];
270
271
        foreach ($data as &$resource) {
272
            $resource = array_filter($resource, function ($key) use ($remove) {
273
                return (! in_array($key, $remove));
274
            }, ARRAY_FILTER_USE_KEY);
275
        }
276
277
        foreach ($collection->getIterator() as $entity) {
278
            $entityRels = $entity->getRelationshipMap();
279
280
            if (! array_key_exists($relationship, $entityRels)) {
281
                continue;
282
            }
283
284
            $keys = array_keys(preg_grep("/{$entity[$map['defined_in']['entity']]}/", $relationships));
285
            $rels = array_filter($data, function ($key) use ($keys) {
286
                return in_array($key, $keys);
287
            }, ARRAY_FILTER_USE_KEY);
288
289
            $rels = $this->buildCollection($rels, $entityRels[$relationship])->setTotal(count($rels));
290
            $this->decorate($rels, StoreInterface::ON_READ);
291
292
            $entity->addRelationship($relationship, $rels);
293
        }
294
    }
295
296
    /**
297
     * Return relationship bind conditional.
298
     *
299
     * @param \Percy\Entity\Collection $collection
300
     * @param string                   $relationship
301
     * @param string                   $key
302
     *
303
     * @return string
304
     */
305
    protected function getRelationshipBinds(Collection $collection, $relationship, $key)
306
    {
307
        $primaries = [];
308
309
        foreach ($collection->getIterator() as $entity) {
310
            if (! array_key_exists($relationship, $entity->getRelationshipMap())) {
311
                continue;
312
            }
313
314
            $primaries[] = "'{$entity[$key]}'";
315
        }
316
317
        return $primaries;
318
    }
319
320
    /**
321
     * Get possible relationships and the properties attached to them.
322
     *
323
     * @param string $relationship
324
     *
325
     * @throws \InvalidArgumentException when requested relationship is not defined
326
     * @throws \RuntimeException when map structure is defined incorrectly
327
     *
328
     * @return array
329
     */
330
    public function getRelationshipMap($relationship = null)
331
    {
332
        if (is_null($relationship)) {
333
            return $this->relationships;
334
        }
335
336
        if (! array_key_exists($relationship, $this->relationships)) {
337
            throw new InvalidArgumentException(
338
                sprintf('(%s) is not defined in the relationship map on (%s)', $relationship, get_class($this))
339
            );
340
        }
341
342
        $map = $this->relationships[$relationship];
343
344
        foreach ([
345
            'defined_in' => ['table', 'primary', 'entity'],
346
            'target'     => ['table', 'primary', 'relationship']
347
        ] as $key => $value) {
348
            if (! array_key_exists($key, $map) || ! is_array($map[$key])) {
349
                throw new RuntimeException(
350
                    sprintf(
351
                        'Relationship (%s) should contain the (%s) key and should be of type array on (%s)',
352
                        $relationship, $key, get_class($this)
353
                    )
354
                );
355
            }
356
357
            if (! empty(array_diff($value, array_keys($map[$key])))) {
358
                throw new RuntimeException(
359
                    sprintf(
360
                        '(%s) for relationship (%s) should contain keys (%s) on (%s)',
361
                        $key, $relationship, implode(', ', $value), get_class($this)
362
                    )
363
                );
364
            }
365
        }
366
367
        return $map;
368
    }
369
370
    /**
371
     * Returns table that repository is reading from.
372
     *
373
     * @return string
374
     */
375
    abstract protected function getTable();
376
}
377