DoctrineDBAL::getCountQuery()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/**
3
 * @company MTE Telecom, Ltd.
4
 * @author Roman Malashin <[email protected]>
5
 */
6
7
namespace Nnx\DataGrid\Adapter;
8
9
use Doctrine\Common\Persistence\ObjectManager;
10
use Doctrine\DBAL\Query\QueryBuilder;
11
use Doctrine\ORM\EntityManagerInterface;
12
use Traversable;
13
14
/**
15
 * Class DoctrineDBAL
16
 * @package Nnx\DataGrid\Adapter
17
 */
18
class DoctrineDBAL extends AbstractAdapter implements EntityManagerAwareInterface, PaginatorAdapterInterface
19
{
20
    use PaginatorAdapterTrait;
21
22
    /**
23
     * Запрос данных
24
     * @var QueryBuilder
25
     */
26
    protected $query;
27
28
    /**
29
     * Запрос на подсчет данных
30
     * @var QueryBuilder
31
     */
32
    protected $countQuery;
33
34
    /**
35
     * Параметры сортировки
36
     * @var array
37
     */
38
    protected $order;
39
40
    /**
41
     * @var int
42
     */
43
    protected $limit = 25;
44
45
    /**
46
     * @var int
47
     */
48
    protected $offset = 0;
49
50
    /**
51
     * Alias корневой сущности
52
     * @var string
53
     */
54
    protected $rootAlias;
55
56
    /**
57
     * @var EntityManagerInterface
58
     */
59
    protected $entityManager;
60
61
    /**
62
     * Проверяет корректность запроса
63
     * @throws Exception\RuntimeException
64
     */
65
    protected function validateQuery()
66
    {
67
        if (!$this->getQuery()) {
68
            throw new Exception\RuntimeException('Не задан query');
69
        }
70
        $query = $this->getQuery();
71
        if (!$query instanceof QueryBuilder) {
72
            throw new Exception\RuntimeException(sprintf('Query должен наследоваться от %s', QueryBuilder::class));
73
        }
74
    }
75
76
    /**
77
     * Возвращает данные для грида
78
     * @return array
79
     * @throws Exception\RuntimeException
80
     */
81
    public function getData()
82
    {
83
        $this->validateQuery();
84
        $query = $this->getQuery();
85
        if ($this->getCount()) {
86
            $query = clone $query;
87
        }
88
        $order = $this->getOrder();
89
        if ((is_array($order) || $order instanceof Traversable) && 0 !== count($order)) {
90
            $query->resetQueryPart('orderBy');
91
            foreach ($order as $orderPart) {
92
                if (array_key_exists('field', $orderPart) && $orderPart['field']) {
93
                    $query->addOrderBy($orderPart['field'],
94
                        array_key_exists('order', $orderPart) && $orderPart['order'] ? $orderPart['order'] : null);
95
                }
96
            }
97
        }
98
        $query = $this->prepareConditions($query);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
99
        $result = $query->setMaxResults($this->getLimit())
100
            ->setFirstResult($this->getOffset())
101
            ->execute();
102
103
        return $result->fetchAll();
104
    }
105
106
    /**
107
     * @param QueryBuilder $query
108
     * @return QueryBuilder
109
     */
110
    protected function prepareConditions($query)
111
    {
112
        $i = 0;
113
        if (count($this->getConditions()) !== 0) {
114
            foreach ($this->getConditions() as $condition) {
115
                $conditionKey = 'NNXGridCondition_' . $i;
116
                $query->andWhere($condition->getKey() . ' ' . $condition->getCriteria() . ' :' . $conditionKey);
117
                $query->setParameter($conditionKey, $condition->getValue());
118
                $i++;
119
            }
120
        }
121
122
        return $query;
123
    }
124
125
    /**
126
     * @return int
127
     * @throws Exception\RuntimeException
128
     */
129
    public function getCount()
130
    {
131
        if ($this->count !== null) {
132
            $res = $this->count;
133
        } else {
134
            if (!$this->getCountQuery() && !$this->getQuery()) {
135
                throw new Exception\RuntimeException('Не задан query для адаптера Grid');
136
            } elseif (!$this->getCountQuery()) {
137
                $query = $this->getQuery();
138
                if (!$query instanceof QueryBuilder) {
139
                    throw new Exception\RuntimeException(sprintf('Query должен наследоваться от %s', QueryBuilder::class));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
140
                }
141
                $query = clone $query;
142
                $this->setCountQuery($query
143
                    ->select('COUNT(DISTINCT ' . $this->getRootAlias() . '.id) AS total_results')
144
                    ->resetQueryParts(['groupBy', 'orderBy'])
145
                    ->setMaxResults(1)
146
                );
147
            }
148
            $stmt = $this->getCountQuery()->execute();
149
            $res = $this->count = (int)$stmt->fetchColumn(0);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
150
        }
151
152
        return $res;
153
    }
154
155
    /**
156
     * @return mixed
157
     */
158
    public function init()
159
    {
160
    }
161
162
163
    /**
164
     * @return QueryBuilder
165
     */
166
    public function getQuery()
167
    {
168
        return $this->query;
169
    }
170
171
    /**
172
     * @param QueryBuilder $query
173
     * @return $this
174
     */
175
    public function setQuery($query)
176
    {
177
        $this->query = $query;
178
        return $this;
179
    }
180
181
    /**
182
     * @return array
183
     */
184
    public function getOrder()
185
    {
186
        return $this->order;
187
    }
188
189
    /**
190
     * [['field'=> 'u.username', 'order' => 'DESC'],['field' => 'u.create_date_time']]
191
     * @param array | Traversable $order
192
     * @return $this
193
     */
194
    public function setOrder($order)
195
    {
196
        $this->order = $order;
197
        return $this;
198
    }
199
200
    /**
201
     * @return int
202
     */
203
    public function getLimit()
204
    {
205
        return $this->limit;
206
    }
207
208
    /**
209
     * @param int $limit
210
     * @return $this
211
     */
212
    public function setLimit($limit)
213
    {
214
        $this->limit = $limit;
215
        return $this;
216
    }
217
218
    /**
219
     * @return int
220
     */
221
    public function getOffset()
222
    {
223
        return $this->offset;
224
    }
225
226
    /**
227
     * @param int $offset
228
     * @return $this
229
     */
230
    public function setOffset($offset)
231
    {
232
        $this->offset = $offset;
233
        return $this;
234
    }
235
236
    /**
237
     * @return QueryBuilder
238
     */
239
    public function getCountQuery()
240
    {
241
        return $this->countQuery;
242
    }
243
244
    /**
245
     * @param QueryBuilder $countQuery
246
     * @return $this
247
     */
248
    public function setCountQuery($countQuery)
249
    {
250
        $this->countQuery = $countQuery;
251
        return $this;
252
    }
253
254
    /**
255
     * @return string
256
     */
257
    public function getRootAlias()
258
    {
259
        return $this->rootAlias;
260
    }
261
262
    /**
263
     * @param string $rootAlias
264
     * @return $this
265
     */
266
    public function setRootAlias($rootAlias)
267
    {
268
        $this->rootAlias = $rootAlias;
269
        return $this;
270
    }
271
272
    /**
273
     * @return EntityManagerInterface
274
     */
275
    public function getEntityManager()
276
    {
277
        return $this->entityManager;
278
    }
279
280
    /**
281
     * @param ObjectManager|EntityManagerInterface $entityManager
282
     * @return $this
283
     */
284
    public function setEntityManager(EntityManagerInterface $entityManager)
285
    {
286
        $this->entityManager = $entityManager;
287
        return $this;
288
    }
289
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
290