Completed
Push — master ( edbe7e...742cca )
by Phil
04:24
created

AbstractSqlRepository   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 235
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 40.19%

Importance

Changes 20
Bugs 4 Features 1
Metric Value
wmc 24
c 20
b 4
f 1
lcom 1
cbo 6
dl 0
loc 235
ccs 43
cts 107
cp 0.4019
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A countFromRequest() 0 7 1
A countByField() 0 10 1
A getByField() 0 11 1
B getFromRequest() 0 20 5
A buildQueryFromRules() 0 17 4
A getRelationshipsFor() 0 15 2
B getEntityRelationships() 0 37 3
B getRelationshipMap() 0 35 6
getTable() 0 1 ?
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
                $query  .= sprintf('%s %s %s :%s', $keyword, $where['field'], $where['delimiter'], $where['field']);
93
94 1
                $params[$where['field']] = $where['value'];
95 1
            }
96 1
        }
97
98 1
        return [$query, $params];
99
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104 1
    public function countByField($field, $value)
105
    {
106 1
        $query = sprintf('SELECT COUNT(*) as total FROM %s WHERE %s IN (:%s)', $this->getTable(), $field, $field);
107
108
        $params = [
109 1
            $field => implode(',', (array) $value)
110 1
        ];
111
112 1
        return (int) $this->dbal->fetchOne($query, $params)['total'];
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118 1
    public function getByField($field, $value)
119
    {
120 1
        $query = sprintf('SELECT * FROM %s WHERE %s IN (:%s)', $this->getTable(), $field, $field);
121
122
        $params = [
123 1
            $field => implode(',', (array) $value)
124 1
        ];
125
126 1
        return $this->buildCollection($this->dbal->fetchAll($query, $params))
127 1
                    ->setTotal($this->countByField($field, $value));
128
    }
129
130
    /**
131
     * {@inheritdoc}
132
     */
133
    public function getRelationshipsFor(Collection $collection, array $relationships = [])
134
    {
135
        $relCollection = new Collection;
136
137
        foreach ($collection->getIterator() as $entity) {
138
            $rels = $entity->getRelationships();
139
            array_walk($rels, [$this, 'getEntityRelationships'], [
140
                'entity'     => $entity,
141
                'collection' => $relCollection,
142
                'include'    => $relationships
143
            ]);
144
        }
145
146
        return $relCollection;
147
    }
148
149
    /**
150
     * Attach relationships to a specific entity.
151
     *
152
     * @param string $entityType
153
     * @param string $relationship
154
     * @param array  $userData
155
     *
156
     * @return void
157
     */
158
    protected function getEntityRelationships($entityType, $relationship, array $userData)
159
    {
160
        $collection = $userData['collection'];
161
        $include    = $userData['include'];
162
        $entity     = $userData['entity'];
163
        $map        = $this->getRelationshipMap($relationship);
164
165
        if (! in_array($relationship, $include)) {
166
            return false;
167
        }
168
169
        $query = sprintf(
170
            'SELECT * FROM %s LEFT JOIN %s ON %s.%s = %s.%s WHERE %s = :%s',
171
            $map['defined_in']['table'],
172
            $map['target']['table'],
173
            $map['target']['table'],
174
            $map['target']['primary'],
175
            $map['defined_in']['table'],
176
            $map['target']['relationship'],
177
            $map['defined_in']['primary'],
178
            $map['defined_in']['entity']
179
        );
180
181
        $result = $this->dbal->fetchAll($query, [
182
            $map['defined_in']['entity'] => $entity[$map['defined_in']['entity']]
183
        ]);
184
185
        $remove = [$map['defined_in']['primary'], $map['target']['relationship']];
186
187
        foreach ($result as $resource) {
188
            $resource = array_filter($resource, function ($key) use ($remove) {
189
                return (! in_array($key, $remove));
190
            }, ARRAY_FILTER_USE_KEY);
191
192
            $collection->addEntity((new $entityType)->hydrate($resource));
193
        }
194
    }
195
196
    /**
197
     * Get possible relationships and the properties attached to them.
198
     *
199
     * @param string $relationship
200
     *
201
     * @throws \InvalidArgumentException when requested relationship is not defined
202
     * @throws \RuntimeException when map structure is defined incorrectly
203
     *
204
     * @return array
205
     */
206
    protected function getRelationshipMap($relationship)
207
    {
208
        if (! array_key_exists($relationship, $this->relationships)) {
209
            throw new InvalidArgumentException(
210
                sprintf('(%s) is not defined in the relationship map on (%s)', $relationship, get_class($this))
211
            );
212
        }
213
214
        $map = $this->relationships[$relationship];
215
216
        foreach ([
217
            'defined_in' => ['table', 'primary', 'entity'],
218
            'target'     => ['table', 'primary', 'relationship']
219
        ] as $key => $value) {
220
            if (! array_key_exists($key, $map) || ! is_array($map[$key])) {
221
                throw new RuntimeException(
222
                    sprintf(
223
                        'Relationship (%s) should contain the (%s) key and should be of type array on (%s)',
224
                        $relationship, $key, get_class($this)
225
                    )
226
                );
227
            }
228
229
            if (! empty(array_diff($value, array_keys($map[$key])))) {
230
                throw new RuntimeException(
231
                    sprintf(
232
                        '(%s) for relationship (%s) should contain keys (%s) on (%s)',
233
                        $key, $relationship, implode(', ', $value), get_class($this)
234
                    )
235
                );
236
            }
237
        }
238
239
        return $map;
240
    }
241
242
    /**
243
     * Returns table that repository is reading from.
244
     *
245
     * @return string
246
     */
247
    abstract protected function getTable();
248
}
249