Completed
Push — master ( 6b6ec6...bf6c0c )
by James
02:08
created

AbstractSqlRepository::buildQueryFromRules()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 19
ccs 13
cts 13
cp 1
rs 8.8571
cc 5
eloc 11
nc 2
nop 2
crap 5
1
<?php
2
3
namespace Percy\Repository;
4
5
use Aura\Sql\ExtendedPdoInterface;
6
use InvalidArgumentException;
7
use Percy\Entity\Collection;
8
use Percy\Entity\CollectionBuilderTrait;
9
use Percy\Entity\EntityInterface;
10
use Percy\Http\QueryStringParserTrait;
11
use Psr\Http\Message\ServerRequestInterface;
12
use RuntimeException;
13
14
abstract class AbstractSqlRepository implements RepositoryInterface
15
{
16
    use CollectionBuilderTrait;
17
    use QueryStringParserTrait;
18
19
    /**
20
     * @var \Aura\Sql\ExtendedPdoInterface
21
     */
22
    protected $dbal;
23
24
    /**
25
     *
26
     * @var mixed
27
     */
28
    protected $relationships = [];
29
30
    /**
31
     * Construct.
32
     *
33
     * @param \Aura\Sql\ExtendedPdoInterface $dbal
34
     */
35 2
    public function __construct(ExtendedPdoInterface $dbal)
36
    {
37 2
        $this->dbal = $dbal;
38 2
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43 1
    public function countFromRequest(ServerRequestInterface $request)
44
    {
45 1
        $rules = $this->parseQueryString($request->getUri()->getQuery());
46 1
        list($query, $params) = $this->buildQueryFromRules($rules, 'SELECT COUNT(*) as total FROM ');
47
48 1
        return (int) $this->dbal->fetchOne($query, $params)['total'];
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 1
    public function getFromRequest(ServerRequestInterface $request)
55
    {
56 1
        $rules = $this->parseQueryString($request->getUri()->getQuery());
57
58 1
        list($query, $params) = $this->buildQueryFromRules($rules);
59
60 1
        if (array_key_exists('sort', $rules)) {
61 1
            $query .= sprintf(' ORDER BY %s ', $rules['sort']);
62 1
            $query .= (array_key_exists('sort_direction', $rules)) ? $rules['sort_direction'] : 'ASC';
63 1
        }
64
65 1
        if (array_key_exists('limit', $rules)) {
66 1
            $query .= ' LIMIT ';
67 1
            $query .= (array_key_exists('offset', $rules)) ? sprintf('%d,', $rules['offset']) : '';
68 1
            $query .= $rules['limit'];
69 1
        }
70
71 1
        return $this->buildCollection($this->dbal->fetchAll($query, $params))
72 1
                    ->setTotal($this->countFromRequest($request));
73
    }
74
75
    /**
76
     * Build a base query without sorting and limits from filter rules.
77
     *
78
     * @param array  $rules
79
     * @param string $start
80
     *
81
     * @return array
82
     */
83 1
    protected function buildQueryFromRules(array $rules, $start = 'SELECT * FROM ')
84
    {
85 1
        $query = $start . $this->getTable();
86
87 1
        $params = [];
88
89 1
        if (array_key_exists('filter', $rules)) {
90 1
            foreach ($rules['filter'] as $key => $where) {
91 1
                $keyword   = ($key === 0) ? ' WHERE' : ' AND';
92 1
                $delimiter = strtoupper($where['delimiter']);
93 1
                $binding   = (in_array($delimiter, ['IN', 'NOT IN'])) ? sprintf('(:%s)', $where['binding']) : ':' . $where['binding'];
94 1
                $query    .= sprintf('%s %s %s %s', $keyword, $where['field'], $delimiter, $binding);
95
96 1
                $params[$where['binding']] = $where['value'];
97 1
            }
98 1
        }
99
100 1
        return [$query, $params];
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106 1
    public function countByField($field, $value)
107
    {
108 1
        $query = sprintf('SELECT COUNT(*) as total FROM %s WHERE %s IN (:%s)', $this->getTable(), $field, $field);
109
110
        $params = [
111 1
            $field => implode(',', (array) $value)
112 1
        ];
113
114 1
        return (int) $this->dbal->fetchOne($query, $params)['total'];
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 1
    public function getByField($field, $value)
121
    {
122 1
        $query = sprintf('SELECT * FROM %s WHERE %s IN (:%s)', $this->getTable(), $field, $field);
123
124
        $params = [
125 1
            $field => implode(',', (array) $value)
126 1
        ];
127
128 1
        return $this->buildCollection($this->dbal->fetchAll($query, $params))
129 1
                    ->setTotal($this->countByField($field, $value));
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135
    public function getRelationshipsFor(Collection $collection, array $relationships = [])
136
    {
137
        $relCollection = new Collection;
138
139
        foreach ($collection->getIterator() as $entity) {
140
            $rels = $entity->getRelationships();
141
            array_walk($rels, [$this, 'getEntityRelationships'], [
142
                'entity'     => $entity,
143
                'collection' => $relCollection,
144
                'include'    => $relationships
145
            ]);
146
        }
147
148
        return $relCollection;
149
    }
150
151
    /**
152
     * Attach relationships to a specific entity.
153
     *
154
     * @param string $entityType
155
     * @param string $relationship
156
     * @param array  $userData
157
     *
158
     * @return void
159
     */
160
    protected function getEntityRelationships($entityType, $relationship, array $userData)
161
    {
162
        $collection = $userData['collection'];
163
        $include    = $userData['include'];
164
        $entity     = $userData['entity'];
165
        $map        = $this->getRelationshipMap($relationship);
166
167
        if (! in_array($relationship, $include)) {
168
            return false;
169
        }
170
171
        $query = sprintf(
172
            'SELECT * FROM %s LEFT JOIN %s ON %s.%s = %s.%s WHERE %s = :%s',
173
            $map['defined_in']['table'],
174
            $map['target']['table'],
175
            $map['target']['table'],
176
            $map['target']['primary'],
177
            $map['defined_in']['table'],
178
            $map['target']['relationship'],
179
            $map['defined_in']['primary'],
180
            $map['defined_in']['entity']
181
        );
182
183
        $result = $this->dbal->fetchAll($query, [
184
            $map['defined_in']['entity'] => $entity[$map['defined_in']['entity']]
185
        ]);
186
187
        $remove = [$map['defined_in']['primary'], $map['target']['relationship']];
188
189
        foreach ($result as $resource) {
190
            $resource = array_filter($resource, function ($key) use ($remove) {
191
                return (! in_array($key, $remove));
192
            }, ARRAY_FILTER_USE_KEY);
193
194
            $collection->addEntity((new $entityType)->hydrate($resource));
195
        }
196
    }
197
198
    /**
199
     * Get possible relationships and the properties attached to them.
200
     *
201
     * @param string $relationship
202
     *
203
     * @throws \InvalidArgumentException when requested relationship is not defined
204
     * @throws \RuntimeException when map structure is defined incorrectly
205
     *
206
     * @return array
207
     */
208
    public function getRelationshipMap($relationship)
209
    {
210
        if (! array_key_exists($relationship, $this->relationships)) {
211
            throw new InvalidArgumentException(
212
                sprintf('(%s) is not defined in the relationship map on (%s)', $relationship, get_class($this))
213
            );
214
        }
215
216
        $map = $this->relationships[$relationship];
217
218
        foreach ([
219
            'defined_in' => ['table', 'primary', 'entity'],
220
            'target'     => ['table', 'primary', 'relationship']
221
        ] as $key => $value) {
222
            if (! array_key_exists($key, $map) || ! is_array($map[$key])) {
223
                throw new RuntimeException(
224
                    sprintf(
225
                        'Relationship (%s) should contain the (%s) key and should be of type array on (%s)',
226
                        $relationship, $key, get_class($this)
227
                    )
228
                );
229
            }
230
231
            if (! empty(array_diff($value, array_keys($map[$key])))) {
232
                throw new RuntimeException(
233
                    sprintf(
234
                        '(%s) for relationship (%s) should contain keys (%s) on (%s)',
235
                        $key, $relationship, implode(', ', $value), get_class($this)
236
                    )
237
                );
238
            }
239
        }
240
241
        return $map;
242
    }
243
244
    /**
245
     * Returns table that repository is reading from.
246
     *
247
     * @return string
248
     */
249
    abstract protected function getTable();
250
}
251