PaginateElasticaQuerySubscriber::getSort()   B
last analyzed

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 <https://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 9
            $results = $event->target->getResults($event->getOffset(), $event->getLimit());
41
42 9
            $event->count = $results->getTotalHits();
43 9
            $event->items = $results->toArray();
44 9
            $aggregations = $results->getAggregations();
45 9
            if (null != $aggregations) {
46
                $event->setCustomPaginationParameter('aggregations', $aggregations);
47
            }
48
49 9
            $event->stopPropagation();
50
        }
51 9
    }
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 10
    protected function setSorting(ItemsEvent $event)
67
    {
68
        // Bugfix for PHP 7.4 as options can be null and generate a "Trying to access array offset on value of type null" error
69 10
        $options = $event->options ?? [];
70 10
        $sortField = $this->getFromRequest($options['sortFieldParameterName'] ?? null);
71
72 10
        if (!$sortField && isset($options['defaultSortFieldName'])) {
73 1
            $sortField = $options['defaultSortFieldName'];
74
        }
75
76 10
        if (!empty($sortField)) {
77 8
            $event->target->getQuery()->setSort([
78 8
                $sortField => $this->getSort($sortField, $options),
79
            ]);
80
        }
81 9
    }
82
83 8
    protected function getSort($sortField, array $options = [])
84
    {
85
        $sort = [
86 8
            'order' => $this->getSortDirection($sortField, $options),
87
        ];
88
89 7
        if (isset($options['sortNestedPath'])) {
90 4
            $path = \is_callable($options['sortNestedPath']) ?
91 4
                $options['sortNestedPath']($sortField) : $options['sortNestedPath'];
92
93 4
            if (!empty($path)) {
94 4
                $sort['nested_path'] = $path;
95
            }
96
        }
97
98 7
        if (isset($options['sortNestedFilter'])) {
99 2
            $filter = \is_callable($options['sortNestedFilter']) ?
100 2
                $options['sortNestedFilter']($sortField) : $options['sortNestedFilter'];
101
102 2
            if (!empty($filter)) {
103 2
                $sort['nested_filter'] = $filter;
104
            }
105
        }
106
107 7
        return $sort;
108
    }
109
110 8
    protected function getSortDirection($sortField, array $options = [])
111
    {
112 8
        $dir = 'asc';
113 8
        $sortDirection = $this->getFromRequest($options['sortDirectionParameterName']);
114
115 8
        if (empty($sortDirection) && isset($options['defaultSortDirection'])) {
116
            $sortDirection = $options['defaultSortDirection'];
117
        }
118
119 8
        if ('desc' === \strtolower($sortDirection)) {
120 1
            $dir = 'desc';
121
        }
122
123
        // check if the requested sort field is in the sort whitelist
124 8
        if (isset($options['sortFieldWhitelist']) && !\in_array($sortField, $options['sortFieldWhitelist'], true)) {
125 1
            throw new \UnexpectedValueException(\sprintf('Cannot sort by: [%s] this field is not in whitelist', $sortField));
126
        }
127
128 7
        return $dir;
129
    }
130
131 8
    private function getRequest(): ?Request
132
    {
133 8
        return $this->requestStack->getCurrentRequest();
134
    }
135
136
    /**
137
     * @return mixed|null
138
     */
139 10
    private function getFromRequest(?string $key)
140
    {
141 10
        if (null !== $key && null !== $request = $this->getRequest()) {
142 8
            return $request->get($key);
143
        }
144
145 2
        return null;
146
    }
147
}
148