Completed
Push — master ( 136cb7...59b361 )
by Nekrasov
02:22
created

ElementQuery::count()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 15
Ratio 100 %

Importance

Changes 0
Metric Value
dl 15
loc 15
rs 9.4285
c 0
b 0
f 0
nc 2
cc 2
eloc 8
nop 0
1
<?php
2
3
namespace Arrilot\BitrixModels\Queries;
4
5
use Arrilot\BitrixCacher\Cache;
6
use CIBlock;
7
use Illuminate\Support\Collection;
8
use Arrilot\BitrixModels\Models\ElementModel;
9
use Exception;
10
11
/**
12
 * @method ElementQuery active()
13
 * @method ElementQuery sortByDate(string $sort = 'desc')
14
 * @method ElementQuery fromSectionWithId(int $id)
15
 * @method ElementQuery fromSectionWithCode(string $code)
16
 */
17
class ElementQuery extends OldCoreQuery
18
{
19
    /**
20
     * CIblock object or test double.
21
     *
22
     * @var object.
23
     */
24
    public static $cIblockObject;
25
26
    /**
27
     * Query sort.
28
     *
29
     * @var array
30
     */
31
    public $sort = ['SORT' => 'ASC'];
32
33
    /**
34
     * Query group by.
35
     *
36
     * @var array
37
     */
38
    public $groupBy = false;
39
40
    /**
41
     * Iblock id.
42
     *
43
     * @var int
44
     */
45
    protected $iblockId;
46
47
    /**
48
     * Iblock version.
49
     *
50
     * @var int
51
     */
52
    protected $iblockVersion;
53
54
    /**
55
     * List of standard entity fields.
56
     *
57
     * @var array
58
     */
59
    protected $standardFields = [
60
        'ID',
61
        'TIMESTAMP_X',
62
        'TIMESTAMP_X_UNIX',
63
        'MODIFIED_BY',
64
        'DATE_CREATE',
65
        'DATE_CREATE_UNIX',
66
        'CREATED_BY',
67
        'IBLOCK_ID',
68
        'IBLOCK_SECTION_ID',
69
        'ACTIVE',
70
        'ACTIVE_FROM',
71
        'ACTIVE_TO',
72
        'SORT',
73
        'NAME',
74
        'PREVIEW_PICTURE',
75
        'PREVIEW_TEXT',
76
        'PREVIEW_TEXT_TYPE',
77
        'DETAIL_PICTURE',
78
        'DETAIL_TEXT',
79
        'DETAIL_TEXT_TYPE',
80
        'SEARCHABLE_CONTENT',
81
        'IN_SECTIONS',
82
        'SHOW_COUNTER',
83
        'SHOW_COUNTER_START',
84
        'CODE',
85
        'TAGS',
86
        'XML_ID',
87
        'EXTERNAL_ID',
88
        'TMP_ID',
89
        'CREATED_USER_NAME',
90
        'DETAIL_PAGE_URL',
91
        'LIST_PAGE_URL',
92
        'CREATED_DATE',
93
    ];
94
95
    /**
96
     * Constructor.
97
     *
98
     * @param object $bxObject
99
     * @param string $modelName
100
     */
101
    public function __construct($bxObject, $modelName)
102
    {
103
        static::instantiateCIblockObject();
104
        parent::__construct($bxObject, $modelName);
105
106
        $this->iblockId = $modelName::iblockId();
107
        $this->iblockVersion = $modelName::IBLOCK_VERSION ?: 2;
108
    }
109
110
    /**
111
     * Instantiate bitrix entity object.
112
     *
113
     * @throws Exception
114
     *
115
     * @return object
116
     */
117
    public static function instantiateCIblockObject()
118
    {
119
        if (static::$cIblockObject) {
120
            return static::$cIblockObject;
121
        }
122
123
        if (class_exists('CIBlock')) {
124
            return static::$cIblockObject = new CIBlock();
125
        }
126
127
        throw new Exception('CIblock object initialization failed');
128
    }
129
130
    /**
131
     * Setter for groupBy.
132
     *
133
     * @param $value
134
     *
135
     * @return $this
136
     */
137
    public function groupBy($value)
138
    {
139
        $this->groupBy = $value;
140
141
        return $this;
142
    }
143
144
    /**
145
     * Get list of items.
146
     *
147
     * @return Collection
148
     */
149
    public function getList()
150
    {
151
        if ($this->queryShouldBeStopped) {
152
            return new Collection();
153
        }
154
155
        $sort = $this->sort;
156
        $filter = $this->normalizeFilter();
157
        $groupBy = $this->groupBy;
158
        $navigation = $this->navigation;
159
        $select = $this->normalizeSelect();
160
        $queryType = 'ElementQuery::getList';
161
        $keyBy = $this->keyBy;
162
        list($select, $chunkQuery) = $this->multiplySelectForMaxJoinsRestrictionIfNeeded($select);
163
164
        $callback = function() use ($sort, $filter, $groupBy, $navigation, $select, $chunkQuery) {
165
            if ($chunkQuery) {
166
                $itemsChunks = [];
167
                foreach ($select as $chunkIndex => $selectForChunk) {
168
                    $rsItems = $this->bxObject->GetList($sort, $filter, $groupBy, $navigation, $selectForChunk);
169
                    while ($arItem = $this->performFetchUsingSelectedMethod($rsItems)) {
170
                        $this->addItemToResultsUsingKeyBy($itemsChunks[$chunkIndex], new $this->modelName($arItem['ID'], $arItem));
171
                    }
172
                }
173
174
                $items = $this->mergeChunks($itemsChunks);
175
            } else {
176
                $items = [];
177
                $rsItems = $this->bxObject->GetList($sort, $filter, $groupBy, $navigation, $select);
178
                while ($arItem = $this->performFetchUsingSelectedMethod($rsItems)) {
179
                    $this->addItemToResultsUsingKeyBy($items, new $this->modelName($arItem['ID'], $arItem));
180
                }
181
            }
182
            return new Collection($items);
183
        };
184
185
        return $this->handleCacheIfNeeded(compact('sort', 'filter', 'group', 'navigation', 'select', 'queryType', 'keyBy'), $callback);
186
    }
187
188
    /**
189
     * Get the first element with a given code.
190
     *
191
     * @param string $code
192
     *
193
     * @return ElementModel
194
     */
195
    public function getByCode($code)
196
    {
197
        $this->filter['CODE'] = $code;
198
199
        return $this->first();
200
    }
201
202
    /**
203
     * Get the first element with a given external id.
204
     *
205
     * @param string $id
206
     *
207
     * @return ElementModel
208
     */
209
    public function getByExternalId($id)
210
    {
211
        $this->filter['EXTERNAL_ID'] = $id;
212
213
        return $this->first();
214
    }
215
216
    /**
217
     * Get count of elements that match $filter.
218
     *
219
     * @return int
220
     */
221 View Code Duplication
    public function count()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
222
    {
223
        if ($this->queryShouldBeStopped) {
224
            return 0;
225
        }
226
227
        $filter = $this->normalizeFilter();
228
        $queryType = "ElementQuery::count";
229
230
        $callback = function () use ($filter) {
231
            return (int) $this->bxObject->GetList(false, $filter, []);
232
        };
233
234
        return $this->handleCacheIfNeeded(compact('filter', 'queryType'), $callback);
235
    }
236
237
//    /**
238
//     * Normalize properties's format converting it to 'PROPERTY_"CODE"_VALUE'.
239
//     *
240
//     * @param array $fields
241
//     *
242
//     * @return null
243
//     */
244
//    protected function normalizePropertyResultFormat(&$fields)
245
//    {
246
//        if (empty($fields['PROPERTIES'])) {
247
//            return;
248
//        }
249
//
250
//        foreach ($fields['PROPERTIES'] as $code => $prop) {
251
//            $fields['PROPERTY_'.$code.'_VALUE'] = $prop['VALUE'];
252
//            $fields['~PROPERTY_'.$code.'_VALUE'] = $prop['~VALUE'];
253
//            $fields['PROPERTY_'.$code.'_DESCRIPTION'] = $prop['DESCRIPTION'];
254
//            $fields['~PROPERTY_'.$code.'_DESCRIPTION'] = $prop['~DESCRIPTION'];
255
//            $fields['PROPERTY_'.$code.'_VALUE_ID'] = $prop['PROPERTY_VALUE_ID'];
256
//            if (isset($prop['VALUE_ENUM_ID'])) {
257
//                $fields['PROPERTY_'.$code.'_ENUM_ID'] = $prop['VALUE_ENUM_ID'];
258
//            }
259
//        }
260
//    }
261
262
    /**
263
     * Normalize filter before sending it to getList.
264
     * This prevents some inconsistency.
265
     *
266
     * @return array
267
     */
268
    protected function normalizeFilter()
269
    {
270
        $this->filter['IBLOCK_ID'] = $this->iblockId;
271
272
        return $this->filter;
273
    }
274
275
    /**
276
     * Normalize select before sending it to getList.
277
     * This prevents some inconsistency.
278
     *
279
     * @return array
280
     */
281 View Code Duplication
    protected function normalizeSelect()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
282
    {
283
        if ($this->fieldsMustBeSelected()) {
284
            $this->select = array_merge($this->standardFields, $this->select);
285
        }
286
287
        $this->select[] = 'ID';
288
        $this->select[] = 'IBLOCK_ID';
289
290
        return $this->clearSelectArray();
291
    }
292
293
    /**
294
     * Fetch all iblock property codes from database
295
     *
296
     * return array
297
     */
298
    protected function fetchAllPropsForSelect()
299
    {
300
        $props = [];
301
        $rsProps = static::$cIblockObject->GetProperties($this->iblockId);
302
        while ($prop = $rsProps->Fetch()) {
303
            $props[] = 'PROPERTY_'.$prop['CODE'];
304
        }
305
306
        return $props;
307
    }
308
    
309
    protected function multiplySelectForMaxJoinsRestrictionIfNeeded($select)
310
    {
311
        if (!$this->propsMustBeSelected()) {
312
            return [$select, false];
313
        }
314
315
        $chunkSize = 20;
316
        $props = $this->fetchAllPropsForSelect();
317
        if ($this->iblockVersion !== 1 || (count($props) <= $chunkSize)) {
318
            return [array_merge($select, $props), false];
319
        }
320
321
        // начинаем формировать селекты из свойств
322
        $multipleSelect = array_chunk($props, $chunkSize);
323
324
        // добавляем в каждый селект поля "несвойства"
325
        foreach ($multipleSelect as $i => $partOfProps) {
326
            $multipleSelect[$i] = array_merge($select, $partOfProps);
327
        }
328
329
        return [$multipleSelect, true];
330
    }
331
    
332
    protected function mergeChunks($chunks)
333
    {
334
        $items = [];
335
        foreach ($chunks as $chunk) {
336
            foreach ($chunk as $k => $item) {
337
                if (isset($items[$k])) {
338
                    $item->fields['_were_multiplied'] = array_merge((array) $items[$k]->fields['_were_multiplied'], (array) $item->fields['_were_multiplied']);
339
                    $items[$k]->fields = (array) $item->fields + (array) $items[$k]->fields;
340
                } else {
341
                    $items[$k] = $item;
342
                }
343
            }
344
        }
345
346
        return $items;
347
    }
348
}
349