Completed
Push — master ( 793531...6c04ca )
by Phil
03:45
created

AbstractSqlRepository::attachRelationships()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4286
cc 2
eloc 5
nc 2
nop 2
crap 2
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 6
    public function __construct(ExtendedPdoInterface $dbal)
36
    {
37 6
        $this->dbal = $dbal;
38 6
    }
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 4
    public function attachRelationships(Collection $collection, array $relationships = [])
134
    {
135 4
        foreach ($collection->getIterator() as $entity) {
136 4
            $rels = $entity->getRelationships();
137
            // @todo sort filtering of requested relationships
138 4
            array_walk($rels, [$this, 'attachEntityRelationships'], $entity);
139 1
        }
140
141 1
        return $collection;
142
    }
143
144
    /**
145
     * Attach relationships to a specific entity.
146
     *
147
     * @param string                        $entityType
148
     * @param string                        $relationship
149
     * @param \Percy\Entity\EntityInterface $entity
150
     *
151
     * @throws \RuntimeException when relationship has not been properly defined
152
     *
153
     * @return void
154
     */
155 4
    protected function attachEntityRelationships($entityType, $relationship, EntityInterface $entity)
156
    {
157 4
        $map = $this->getRelationshipMap($relationship);
158
159 1
        $query = sprintf(
160 1
            'SELECT * FROM %s LEFT JOIN %s ON %s.%s = %s.%s WHERE %s = :%s',
161 1
            $map['defined_in']['table'],
162 1
            $map['target']['table'],
163 1
            $map['target']['table'],
164 1
            $map['target']['primary'],
165 1
            $map['defined_in']['table'],
166 1
            $map['target']['relationship'],
167 1
            $map['defined_in']['primary'],
168 1
            $map['defined_in']['entity']
169 1
        );
170
171 1
        $result = $this->dbal->fetchAll($query, [
172 1
            $map['defined_in']['entity'] => $entity[$map['defined_in']['entity']]
173 1
        ]);
174
175 1
        $remove = [$map['defined_in']['primary'], $map['target']['relationship']];
176
177 1
        foreach ($result as &$resource) {
178
            $resource = array_filter($resource, function ($key) use ($remove) {
179
                return (! in_array($key, $remove));
180
            }, ARRAY_FILTER_USE_KEY);
181 1
        }
182
183 1
        $entity[$relationship] = $this->buildCollection($result, $entityType);
184 1
    }
185
186
    /**
187
     * Get possible relationships and the properties attached to them.
188
     *
189
     * @param string $relationship
190
     *
191
     * @throws \InvalidArgumentException when requested relationship is not defined
192
     * @throws \RuntimeException when map structure is defined incorrectly
193
     *
194
     * @return array
195
     */
196 4
    protected function getRelationshipMap($relationship)
197
    {
198 4
        if (! array_key_exists($relationship, $this->relationships)) {
199 1
            throw new InvalidArgumentException(
200 1
                sprintf('(%s) is not defined in the relationship map on (%s)', $relationship, get_class($this))
201 1
            );
202
        }
203
204 3
        $map = $this->relationships[$relationship];
205
206
        foreach ([
207 3
            'defined_in' => ['table', 'primary', 'entity'],
208 3
            'target'     => ['table', 'primary', 'relationship']
209 3
        ] as $key => $value) {
210 3
            if (! array_key_exists($key, $map) || ! is_array($map[$key])) {
211 1
                throw new RuntimeException(
212 1
                    sprintf(
213 1
                        'Relationship (%s) should contain the (%s) key and should be of type array on (%s)',
214 1
                        $relationship, $key, get_class($this)
215 1
                    )
216 1
                );
217
            }
218
219 2
            if (! empty(array_diff($value, array_keys($map[$key])))) {
220 1
                throw new RuntimeException(
221 1
                    sprintf(
222 1
                        '(%s) for relationship (%s) should contain keys (%s) on (%s)',
223 1
                        $key, $relationship, implode(', ', $value), get_class($this)
224 1
                    )
225 1
                );
226
            }
227 1
        }
228
229 1
        return $map;
230
    }
231
232
    /**
233
     * Returns table that repository is reading from.
234
     *
235
     * @return string
236
     */
237
    abstract protected function getTable();
238
}
239