Completed
Push — master ( db9f4a...505dbe )
by Alexis
02:20
created

ElasticaQuerySorter::getItemPerPage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Alpixel\Bundle\ElasticaQuerySorterBundle\Services;
4
5
use Elastica\Query;
6
use Elastica\Query\AbstractQuery;
7
use FOS\ElasticaBundle\Repository;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\HttpFoundation\RequestStack;
10
use Symfony\Component\HttpFoundation\Session\Session;
11
12
/**
13
 * Class used in order to sort and paginate an Abstract Query
14
 * obtained from an elastic search repository
15
 * Data is stored in session to remember user choice
16
 */
17
class ElasticaQuerySorter
18
{
19
20
    protected $session;
21
    protected $request;
22
    protected $sessionData;
23
24
    const NO_LIMIT = 99999;
25
26
    public function __construct(RequestStack $requestStack, Session $session, $configuration)
27
    {
28
        $this->session = $session;
29
        $this->request = $requestStack->getCurrentRequest();
30
        $this->configuration['item_per_page'] = $configuration;
0 ignored issues
show
Bug introduced by
The property configuration does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
31
32
        if (isset($this->request) && isset($this->request->query)) {
33
            if ($this->request->query->has('clear_sort')) {
34
                $this->session->remove('elastica_query_sorter');
35
            }
36
        }
37
38
        //Initializing the data in session
39
        if (!$this->session->has('elastica_query_sorter')) {
40
            $this->sessionData = [];
41
        } else {
42
            $this->sessionData = $this->session->get('elastica_query_sorter');
43
        }
44
    }
45
46
    public function sort(Repository $repository, Query $query, $nbPerPage = null)
47
    {
48
        if ($nbPerPage === null) {
49
            $nbPerPage = $this->getItemPerPage();
50
        }
51
52
        //Creating the main elastica query
53
        $query->setFields(['_id']);
54
55
        //Analysing the request and the session data to add sorting
56
        $this->addSort($query);
57
58
        //Creating the paginator with the given repository
59
        $paginator = $repository->findPaginated($query);
60
        //If this a new sortBy, then we reset the currentPage to 1
61
        $paginator->setCurrentPage($this->getCurrentPage());
62
63
        $paginator->setMaxPerPage($nbPerPage);
64
65
        return $paginator;
66
    }
67
68
    protected function getCurrentPage()
69
    {
70
        $page = 1;
71
72
        if (!empty($this->request) && $this->request->getRealMethod() === 'GET') {
73
            $page = $this->getPage();
74
        }
75
76
        return $page;
77
    }
78
79
    protected function getPage()
80
    {
81
        $nbPage = null;
82
        if ($this->request->query->has('page')) {
83
            $nbPage = $this->request->query->get('page');
84
        }
85
86
        if (empty($nbPage) || !is_numeric($nbPage)) {
87
            return 1;
88
        }
89
90
        return $nbPage;
91
    }
92
93
94
    protected function addSort(Query &$query)
95
    {
96
        $sortBy    = explode('-', $this->fetchData('sortBy'));
97
        $sortOrder = $this->fetchData('sortOrder');
98
99
        $sort = array();
100
        foreach ($sortBy as $element) {
101
            if (empty($element) === false && empty($sortOrder) === false) {
102
                $sort[$element] = array(
103
                    'order'     => strtolower($sortOrder),
104
                    'missing'   => '_last'
105
                );
106
            }
107
        }
108
109
        if (!empty($sort)) {
110
            $query->setSort($sort);
111
        }
112
113
        return $query;
114
    }
115
116
    public function fetchData($key)
117
    {
118
        $pageKey = (!empty($this->request)) ? $this->request->getPathInfo() : null;
119
        $query   = (!empty($this->request)) ? $this->request->query : null;
120
121
        if ($query === null) {
122
            return;
123
        }
124
125
        //Analyzing the session object to see if there is data in it
126
        //If data is given from Request, it will be override the session data
127
        if (array_key_exists($pageKey, $this->sessionData) && !$query->has($key)) {
128
            if (isset($this->sessionData[$pageKey][$key])) {
129
                return $this->sessionData[$pageKey][$key];
130
            }
131
        }
132
133
        if ($query->has('sortBy')) {
134
            $value = $query->get($key);
135
            $this->sessionData[$pageKey][$key] = $value;
136
            $this->storeSessionData();
137
            return $value;
138
        }
139
140
        return null;
141
    }
142
143
    public function storeSessionData()
144
    {
145
        $this->session->set('elastica_query_sorter', $this->sessionData);
146
    }
147
148
    /**
149
     * Gets the value of session.
150
     *
151
     * @return mixed
152
     */
153
    public function getSession()
154
    {
155
        return $this->session;
156
    }
157
158
    /**
159
     * Gets the value of request.
160
     *
161
     * @return mixed
162
     */
163
    public function getRequest()
164
    {
165
        return $this->request;
166
    }
167
168
    /**
169
     * Gets the value of sessionData.
170
     *
171
     * @return mixed
172
     */
173
    public function getSessionData()
174
    {
175
        return $this->sessionData;
176
    }
177
178
    public function getItemPerPage()
179
    {
180
        return $this->configuration['item_per_page'];
181
    }
182
}
183