Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 21 | class PaginateElasticaQuerySubscriber implements EventSubscriberInterface |
||
| 22 | { |
||
| 23 | /** |
||
| 24 | * @var RequestStack |
||
| 25 | */ |
||
| 26 | private $requestStack; |
||
| 27 | |||
| 28 | /** |
||
| 29 | * @param RequestStack $requestStack |
||
| 30 | */ |
||
| 31 | 9 | public function __construct(RequestStack $requestStack) |
|
| 35 | |||
| 36 | /** |
||
| 37 | * @param ItemsEvent $event |
||
| 38 | */ |
||
| 39 | public function items(ItemsEvent $event) |
||
| 40 | { |
||
| 41 | if ($event->target instanceof PaginatorAdapterInterface) { |
||
| 42 | // Add sort to query |
||
| 43 | $this->setSorting($event); |
||
| 44 | |||
| 45 | /** @var $results PartialResultsInterface */ |
||
| 46 | $results = $event->target->getResults($event->getOffset(), $event->getLimit()); |
||
| 47 | |||
| 48 | $event->count = $results->getTotalHits(); |
||
| 49 | $event->items = $results->toArray(); |
||
| 50 | $aggregations = $results->getAggregations(); |
||
| 51 | if (null != $aggregations) { |
||
| 52 | $event->setCustomPaginationParameter('aggregations', $aggregations); |
||
| 53 | } |
||
| 54 | |||
| 55 | $event->stopPropagation(); |
||
| 56 | } |
||
| 57 | } |
||
| 58 | |||
| 59 | /** |
||
| 60 | * @return array |
||
| 61 | */ |
||
| 62 | public static function getSubscribedEvents() |
||
| 68 | |||
| 69 | /** |
||
| 70 | * Adds knp paging sort to query. |
||
| 71 | * |
||
| 72 | * @param ItemsEvent $event |
||
| 73 | */ |
||
| 74 | protected function setSorting(ItemsEvent $event) |
||
| 89 | |||
| 90 | protected function getSort($sortField, array $options = []) |
||
| 116 | |||
| 117 | protected function getSortDirection($sortField, array $options = []) |
||
| 137 | |||
| 138 | /** |
||
| 139 | * @return Request|null |
||
| 140 | */ |
||
| 141 | private function getRequest() |
||
| 145 | } |
||
| 146 |