Cancelled
Pull Request — master (#1569)
by
unknown
10:16 queued 55s
created

PaginateElasticaQuerySubscriber::getSort()   B

Complexity

Conditions 7
Paths 25

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 13
cts 13
cp 1
rs 8.5706
c 0
b 0
f 0
cc 7
nc 25
nop 2
crap 7
1
<?php
2
3
/*
4
 * This file is part of the FOSElasticaBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\ElasticaBundle\Subscriber;
13
14
use FOS\ElasticaBundle\Paginator\PaginatorAdapterInterface;
15
use FOS\ElasticaBundle\Paginator\PartialResultsInterface;
16
use Knp\Component\Pager\Event\ItemsEvent;
17
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\RequestStack;
20
21
class PaginateElasticaQuerySubscriber implements EventSubscriberInterface
22
{
23
    /**
24
     * @var RequestStack
25
     */
26
    private $requestStack;
27
28 10
    public function __construct(RequestStack $requestStack)
29
    {
30 10
        $this->requestStack = $requestStack;
31 10
    }
32
33 10
    public function items(ItemsEvent $event)
34
    {
35 10
        if ($event->target instanceof PaginatorAdapterInterface) {
36
            // Add sort to query
37 10
            $this->setSorting($event);
38
39
            /** @var $results PartialResultsInterface */
40 7
            $results = $event->target->getResults($event->getOffset(), $event->getLimit());
41
42 7
            $event->count = $results->getTotalHits();
43 7
            $event->items = $results->toArray();
44 7
            $aggregations = $results->getAggregations();
45 7
            if (null != $aggregations) {
46
                $event->setCustomPaginationParameter('aggregations', $aggregations);
47
            }
48
49 7
            $event->stopPropagation();
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Component\EventD...vent::stopPropagation() has been deprecated with message: since Symfony 4.3, use "Symfony\Contracts\EventDispatcher\Event" instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
50
        }
51 7
    }
52
53
    /**
54
     * @return array
55
     */
56
    public static function getSubscribedEvents()
57
    {
58
        return [
59
            'knp_pager.items' => ['items', 1],
60
        ];
61
    }
62
63
    /**
64
     * Adds knp paging sort to query.
65
     *
66
     * @param ItemsEvent $event
67
     */
68 10
    protected function setSorting(ItemsEvent $event)
69
    {
70 10
        $options = $event->options;
71 10
        $sortField = $this->getFromRequest($options['sortFieldParameterName']);
72
73 8
        if (!$sortField && isset($options['defaultSortFieldName'])) {
74 1
            $sortField = $options['defaultSortFieldName'];
75
        }
76
77 8
        if (!empty($sortField)) {
78 8
            $event->target->getQuery()->setSort([
79 8
                $sortField => $this->getSort($sortField, $options),
80
            ]);
81
        }
82 7
    }
83
84 8
    protected function getSort($sortField, array $options = [])
85
    {
86
        $sort = [
87 8
            'order' => $this->getSortDirection($sortField, $options),
88
        ];
89
90 7
        if (isset($options['sortNestedPath'])) {
91 4
            $path = is_callable($options['sortNestedPath']) ?
92 4
                $options['sortNestedPath']($sortField) : $options['sortNestedPath'];
93
94 4
            if (!empty($path)) {
95 4
                $sort['nested_path'] = $path;
96
            }
97
        }
98
99 7
        if (isset($options['sortNestedFilter'])) {
100 2
            $filter = is_callable($options['sortNestedFilter']) ?
101 2
                $options['sortNestedFilter']($sortField) : $options['sortNestedFilter'];
102
103 2
            if (!empty($filter)) {
104 2
                $sort['nested_filter'] = $filter;
105
            }
106
        }
107
108 7
        return $sort;
109
    }
110
111 8
    protected function getSortDirection($sortField, array $options = [])
112
    {
113 8
        $dir = 'asc';
114 8
        $sortDirection = $this->getFromRequest($options['sortDirectionParameterName']);
115
116 8
        if (empty($sortDirection) && isset($options['defaultSortDirection'])) {
117
            $sortDirection = $options['defaultSortDirection'];
118
        }
119
120 8
        if ('desc' === strtolower($sortDirection)) {
121 1
            $dir = 'desc';
122
        }
123
124
        // check if the requested sort field is in the sort whitelist
125 8
        if (isset($options['sortFieldWhitelist']) && !in_array($sortField, $options['sortFieldWhitelist'], true)) {
126 1
            throw new \UnexpectedValueException(sprintf('Cannot sort by: [%s] this field is not in whitelist', $sortField));
127
        }
128
129 7
        return $dir;
130
    }
131
132 8
    private function getRequest(): ?Request
133
    {
134 8
        return $this->requestStack->getCurrentRequest();
135
    }
136
137
    /**
138
     * @return mixed|null
139
     */
140 8
    private function getFromRequest(?string $key)
141
    {
142 8
        if (null !== $key && null !== $request = $this->getRequest()) {
143 8
            return $request->get($key);
144
        }
145
146
        return null;
147
    }
148
}
149