Complex classes like AbstractSqlRepository often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use AbstractSqlRepository, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 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 | 3 | public function __construct(ExtendedPdoInterface $dbal) |
|
| 42 | |||
| 43 | /** |
||
| 44 | * {@inheritdoc} |
||
| 45 | */ |
||
| 46 | 1 | public function countFromRequest(ServerRequestInterface $request) |
|
| 53 | |||
| 54 | /** |
||
| 55 | * {@inheritdoc} |
||
| 56 | */ |
||
| 57 | 2 | public function getFromRequest(ServerRequestInterface $request) |
|
| 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 | $keyword = ($key === 0) ? ' WHERE' : ' AND'; |
|
| 166 | 1 | $delimiter = strtoupper($where['delimiter']); |
|
| 167 | 1 | $binding = (in_array($delimiter, ['IN', 'NOT IN'])) ? sprintf('(:%s)', $where['binding']) : ':' . $where['binding']; |
|
| 168 | 1 | $query .= sprintf('%s %s %s %s', $keyword, $where['field'], $delimiter, $binding); |
|
| 169 | |||
| 170 | 1 | $params[$where['binding']] = $where['value']; |
|
| 171 | 1 | } |
|
| 172 | 1 | } |
|
| 173 | |||
| 174 | 2 | if (array_key_exists('search', $rules) && $this->acceptableField($rules['search']['fields'])) { |
|
| 175 | 1 | $keyword = (array_key_exists('filter', $rules)) ? ' AND' : ' WHERE'; |
|
| 176 | 1 | $query .= sprintf('%s MATCH (%s) AGAINST (:match_bind IN BOOLEAN MODE)', $keyword, $rules['search']['fields']); |
|
| 177 | 1 | $query .= sprintf(' HAVING MATCH (%s) AGAINST (:match_bind) > :score_bind', $rules['search']['fields']); |
|
| 178 | |||
| 179 | 1 | $params['match_bind'] = $rules['search']['term']; |
|
| 180 | 1 | $params['score_bind'] = (array_key_exists('minscore', $rules)) ? $rules['minscore'] : 0; |
|
| 181 | 1 | } |
|
| 182 | |||
| 183 | 2 | return [$query, $params]; |
|
| 184 | } |
||
| 185 | |||
| 186 | /** |
||
| 187 | * Asserts that a field is acceptable to filter on. |
||
| 188 | * |
||
| 189 | * @param string $name |
||
| 190 | * |
||
| 191 | * @return boolean |
||
| 192 | */ |
||
| 193 | 2 | protected function acceptableField($name) |
|
| 194 | { |
||
| 195 | 2 | $entity = $this->getEntityType(); |
|
| 196 | 2 | $entity = new $entity; |
|
| 197 | |||
| 198 | 2 | foreach (explode(',', $name) as $field) { |
|
| 199 | 2 | if (! array_key_exists($name, $entity->getMapping())) { |
|
| 200 | 1 | throw new InvalidArgumentException( |
|
| 201 | 1 | sprintf('(%s) is not a whitelisted field to filter, search or sort by', $name) |
|
| 202 | 1 | ); |
|
| 203 | } |
||
| 204 | 1 | } |
|
| 205 | |||
| 206 | 1 | return true; |
|
| 207 | } |
||
| 208 | |||
| 209 | /** |
||
| 210 | * {@inheritdoc} |
||
| 211 | */ |
||
| 212 | 1 | public function countByField($field, $value, ServerRequestInterface $request = null) |
|
| 213 | { |
||
| 214 | 1 | $query = sprintf( |
|
| 215 | 1 | "SELECT COUNT(*) as total FROM %s WHERE %s.%s IN (:%s)", |
|
| 216 | 1 | $this->getTable(), |
|
| 217 | 1 | $this->getTable(), |
|
| 218 | 1 | $field, |
|
| 219 | $field |
||
| 220 | 1 | ); |
|
| 221 | |||
| 222 | $params = [ |
||
| 223 | $field => $value |
||
| 224 | 1 | ]; |
|
| 225 | |||
| 226 | 1 | return (int) $this->dbal->fetchOne($query, $params)['total']; |
|
| 227 | } |
||
| 228 | |||
| 229 | /** |
||
| 230 | * {@inheritdoc} |
||
| 231 | */ |
||
| 232 | 1 | public function getByField($field, $value, ServerRequestInterface $request = null) |
|
| 233 | { |
||
| 234 | 1 | $query = sprintf( |
|
| 235 | 1 | 'SELECT * FROM %s WHERE %s.%s IN (:%s)', |
|
| 236 | 1 | $this->getTable(), |
|
| 237 | 1 | $this->getTable(), |
|
| 238 | 1 | $field, |
|
| 239 | $field |
||
| 240 | 1 | ); |
|
| 241 | |||
| 242 | // @todo - allow extra filtering from request |
||
| 243 | |||
| 244 | $params = [ |
||
| 245 | $field => $value |
||
| 246 | 1 | ]; |
|
| 247 | |||
| 248 | 1 | $collection = $this->buildCollection($this->dbal->fetchAll($query, $params)) |
|
| 249 | 1 | ->setTotal($this->countByField($field, $value)); |
|
| 250 | |||
| 251 | 1 | $this->decorate($collection, StoreInterface::ON_READ); |
|
| 252 | |||
| 253 | 1 | return $collection; |
|
| 254 | } |
||
| 255 | |||
| 256 | /** |
||
| 257 | * {@inheritdoc} |
||
| 258 | */ |
||
| 259 | public function attachRelationships( |
||
| 260 | Collection $collection, |
||
| 261 | $include = null, |
||
| 262 | ServerRequestInterface $request = null |
||
| 263 | ) { |
||
| 264 | if (is_null($include)) { |
||
| 265 | return; |
||
| 266 | } |
||
| 267 | |||
| 268 | $rels = $collection->getIterator()->current()->getRelationshipMap(); |
||
| 269 | |||
| 270 | $rules = ($request instanceof ServerRequestInterface) |
||
| 271 | ? $this->parseQueryString($request->getUri()->getQuery()) |
||
| 272 | : []; |
||
| 273 | |||
| 274 | foreach ($this->getRelationshipMap() as $key => $map) { |
||
| 275 | if (is_array($include) && ! in_array($key, $include)) { |
||
| 276 | continue; |
||
| 277 | } |
||
| 278 | |||
| 279 | $binds = $this->getRelationshipBinds($collection, $key, $map['defined_in']['entity']); |
||
| 280 | |||
| 281 | if (empty($binds)) { |
||
| 282 | continue; |
||
| 283 | } |
||
| 284 | |||
| 285 | $query = sprintf( |
||
| 286 | 'SELECT * FROM %s LEFT JOIN %s ON %s.%s = %s.%s WHERE %s.%s IN (%s)', |
||
| 287 | $map['defined_in']['table'], |
||
| 288 | $map['target']['table'], |
||
| 289 | $map['target']['table'], |
||
| 290 | $map['target']['primary'], |
||
| 291 | $map['defined_in']['table'], |
||
| 292 | $map['target']['relationship'], |
||
| 293 | $map['defined_in']['table'], |
||
| 294 | $map['defined_in']['primary'], |
||
| 295 | implode(',', $binds) |
||
| 296 | ); |
||
| 297 | |||
| 298 | // @todo allow for further filtering of rels via request |
||
| 299 | |||
| 300 | if (array_key_exists('sort', $rules)) { |
||
| 301 | $whitelist = []; |
||
| 302 | |||
| 303 | if (array_key_exists($key, $rels)) { |
||
| 304 | $entity = $rels[$key]; |
||
| 305 | $entity = new $entity; |
||
| 306 | $mapping = $entity->getMapping(); |
||
| 307 | $whitelist = array_keys($mapping); |
||
| 308 | } |
||
| 309 | |||
| 310 | $query .= $this->buildSortPart($rules['sort'], $map['target']['table'], $whitelist); |
||
| 311 | } |
||
| 312 | |||
| 313 | $result = $this->dbal->fetchAll($query, []); |
||
| 314 | |||
| 315 | $this->attachRelationshipsToCollection($collection, $key, $result); |
||
| 316 | } |
||
| 317 | } |
||
| 318 | |||
| 319 | /** |
||
| 320 | * Iterate a result set and attach the relationship to it's correct entity |
||
| 321 | * within a collection. |
||
| 322 | * |
||
| 323 | * @param \Percy\Entity\Collection $collection |
||
| 324 | * @param string $relationship |
||
| 325 | * @param array $data |
||
| 326 | * |
||
| 327 | * @return void |
||
| 328 | */ |
||
| 329 | protected function attachRelationshipsToCollection(Collection $collection, $relationship, array $data) |
||
| 330 | { |
||
| 331 | $map = $this->getRelationshipMap($relationship); |
||
| 332 | $relationships = array_column($data, $map['defined_in']['primary']); |
||
| 333 | |||
| 334 | $remove = [$map['defined_in']['primary'], $map['target']['relationship']]; |
||
| 335 | |||
| 336 | foreach ($data as &$resource) { |
||
| 337 | $resource = array_filter($resource, function ($key) use ($remove) { |
||
| 338 | return (! in_array($key, $remove)); |
||
| 339 | }, ARRAY_FILTER_USE_KEY); |
||
| 340 | } |
||
| 341 | |||
| 342 | foreach ($collection->getIterator() as $entity) { |
||
| 343 | $entityRels = $entity->getRelationshipMap(); |
||
| 344 | |||
| 345 | if (! array_key_exists($relationship, $entityRels)) { |
||
| 346 | continue; |
||
| 347 | } |
||
| 348 | |||
| 349 | $keys = array_keys(preg_grep("/{$entity[$map['defined_in']['entity']]}/", $relationships)); |
||
| 350 | $rels = array_filter($data, function ($key) use ($keys) { |
||
| 351 | return in_array($key, $keys); |
||
| 352 | }, ARRAY_FILTER_USE_KEY); |
||
| 353 | |||
| 354 | $rels = $this->buildCollection($rels, $entityRels[$relationship])->setTotal(count($rels)); |
||
| 355 | $this->decorate($rels, StoreInterface::ON_READ); |
||
| 356 | |||
| 357 | $entity->addRelationship($relationship, $rels); |
||
| 358 | } |
||
| 359 | } |
||
| 360 | |||
| 361 | /** |
||
| 362 | * Return relationship bind conditional. |
||
| 363 | * |
||
| 364 | * @param \Percy\Entity\Collection $collection |
||
| 365 | * @param string $relationship |
||
| 366 | * @param string $key |
||
| 367 | * |
||
| 368 | * @return string |
||
| 369 | */ |
||
| 370 | protected function getRelationshipBinds(Collection $collection, $relationship, $key) |
||
| 371 | { |
||
| 372 | $primaries = []; |
||
| 373 | |||
| 374 | foreach ($collection->getIterator() as $entity) { |
||
| 375 | if (! array_key_exists($relationship, $entity->getRelationshipMap())) { |
||
| 376 | continue; |
||
| 377 | } |
||
| 378 | |||
| 379 | $primaries[] = "'{$entity[$key]}'"; |
||
| 380 | } |
||
| 381 | |||
| 382 | return $primaries; |
||
| 383 | } |
||
| 384 | |||
| 385 | /** |
||
| 386 | * Get possible relationships and the properties attached to them. |
||
| 387 | * |
||
| 388 | * @param string $relationship |
||
| 389 | * |
||
| 390 | * @throws \InvalidArgumentException when requested relationship is not defined |
||
| 391 | * @throws \RuntimeException when map structure is defined incorrectly |
||
| 392 | * |
||
| 393 | * @return array |
||
| 394 | */ |
||
| 395 | public function getRelationshipMap($relationship = null) |
||
| 396 | { |
||
| 397 | if (is_null($relationship)) { |
||
| 398 | return $this->relationships; |
||
| 399 | } |
||
| 400 | |||
| 401 | if (! array_key_exists($relationship, $this->relationships)) { |
||
| 402 | throw new InvalidArgumentException( |
||
| 403 | sprintf('(%s) is not defined in the relationship map on (%s)', $relationship, get_class($this)) |
||
| 404 | ); |
||
| 405 | } |
||
| 406 | |||
| 407 | $map = $this->relationships[$relationship]; |
||
| 408 | |||
| 409 | foreach ([ |
||
| 410 | 'defined_in' => ['table', 'primary', 'entity'], |
||
| 411 | 'target' => ['table', 'primary', 'relationship'] |
||
| 412 | ] as $key => $value) { |
||
| 413 | if (! array_key_exists($key, $map) || ! is_array($map[$key])) { |
||
| 414 | throw new RuntimeException( |
||
| 415 | sprintf( |
||
| 416 | 'Relationship (%s) should contain the (%s) key and should be of type array on (%s)', |
||
| 417 | $relationship, $key, get_class($this) |
||
| 418 | ) |
||
| 419 | ); |
||
| 420 | } |
||
| 421 | |||
| 422 | if (! empty(array_diff($value, array_keys($map[$key])))) { |
||
| 423 | throw new RuntimeException( |
||
| 424 | sprintf( |
||
| 425 | '(%s) for relationship (%s) should contain keys (%s) on (%s)', |
||
| 426 | $key, $relationship, implode(', ', $value), get_class($this) |
||
| 427 | ) |
||
| 428 | ); |
||
| 429 | } |
||
| 430 | } |
||
| 431 | |||
| 432 | return $map; |
||
| 433 | } |
||
| 434 | |||
| 435 | /** |
||
| 436 | * Returns table that repository is reading from. |
||
| 437 | * |
||
| 438 | * @return string |
||
| 439 | */ |
||
| 440 | abstract protected function getTable(); |
||
| 441 | } |
||
| 442 |