IBlock   F
last analyzed

Complexity

Total Complexity 62

Size/Duplication

Total Lines 637
Duplicated Lines 1.41 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 62
lcom 1
cbo 2
dl 9
loc 637
rs 3.403
c 0
b 0
f 0

50 Methods

Rating   Name   Duplication   Size   Complexity  
A add() 0 13 2
A update() 9 9 2
A delete() 0 8 2
A constructDefault() 0 4 1
A setSiteId() 0 6 1
A setCode() 0 6 1
A setXmlId() 0 6 1
A setIblockTypeId() 0 6 1
A setName() 0 6 1
A setActive() 0 6 2
A setSort() 0 6 1
A setListPageUrl() 0 6 1
A setSectionPageUrl() 0 6 1
A setCanonicalPageUrl() 0 6 1
A setDetailPageUrl() 0 6 1
A setDefaultUrls() 0 18 2
A setPicture() 0 6 1
A setDescription() 0 6 1
A setDescriptionType() 0 6 1
A setRssActive() 0 6 2
A setRssTtl() 0 6 1
A setRssFileActive() 0 6 2
A setRssFileLimit() 0 6 1
A setRssFileDays() 0 6 1
A setRssYandexActive() 0 6 2
A setIndexElement() 0 6 2
A setIndexSection() 0 6 2
A setListMode() 0 6 1
A setRightsMode() 0 6 1
A setSectionProperty() 0 6 1
A setPropertyIndex() 0 6 1
A setLastConvElement() 0 6 1
A setGroupId() 0 6 1
A setSocnetGroupId() 0 6 1
A setWorkflow() 0 6 2
A setBizProc() 0 6 2
A setSectionChooser() 0 6 1
A setVersion() 0 6 1
A setEditFileBefore() 0 6 1
A setEditFileAfter() 0 6 1
A setMessElementName() 0 6 1
A setMessElementsName() 0 6 1
A setMessElementAdd() 0 6 1
A setMessElementEdit() 0 6 1
A setMessElementDelete() 0 6 1
A setMessSectionName() 0 6 1
A setMessSectionsName() 0 6 1
A setMessSectionAdd() 0 6 1
A setMessSectionEdit() 0 6 1
A setMessSectionDelete() 0 6 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like IBlock often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use IBlock, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
4
namespace Arrilot\BitrixMigrations\Constructors;
5
6
7
use Arrilot\BitrixMigrations\Logger;
8
use Bitrix\Main\Application;
9
10
class IBlock
11
{
12
    use FieldConstructor;
13
14
    /**
15
     * Добавить инфоблок
16
     * @throws \Exception
17
     */
18
    public function add()
19
    {
20
        $obj = new \CIBlock();
21
22
        $iblockId = $obj->Add($this->getFieldsWithDefault());
23
        if (!$iblockId) {
24
            throw new \Exception($obj->LAST_ERROR);
25
        }
26
27
        Logger::log("Добавлен инфоблок {$this->fields['CODE']}", Logger::COLOR_GREEN);
28
29
        return $iblockId;
30
    }
31
32
    /**
33
     * Обновить инфоблок
34
     * @param $id
35
     * @throws \Exception
36
     */
37 View Code Duplication
    public function update($id)
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...
38
    {
39
        $obj = new \CIBlock();
40
        if (!$obj->Update($id, $this->fields)) {
41
            throw new \Exception($obj->LAST_ERROR);
42
        }
43
44
        Logger::log("Обновлен инфоблок {$id}", Logger::COLOR_GREEN);
45
    }
46
47
    /**
48
     * Удалить инфоблок
49
     * @param $id
50
     * @throws \Exception
51
     */
52
    public static function delete($id)
53
    {
54
        if (!\CIBlock::Delete($id)) {
55
            throw new \Exception('Ошибка при удалении инфоблока');
56
        }
57
58
        Logger::log("Удален инфоблок {$id}", Logger::COLOR_GREEN);
59
    }
60
61
    /**
62
     * Установить настройки для добавления инфоблока по умолчанию
63
     * @param $name
64
     * @param $code
65
     * @param $iblock_type_id
66
     * @return $this
67
     */
68
    public function constructDefault($name, $code, $iblock_type_id)
69
    {
70
        return $this->setName($name)->setCode($code)->setIblockTypeId($iblock_type_id);
71
    }
72
73
    /**
74
     * ID сайта.
75
     * @param string $siteId
76
     * @return $this
77
     */
78
    public function setSiteId($siteId)
79
    {
80
        $this->fields['SITE_ID'] = $siteId;
81
82
        return $this;
83
    }
84
85
    /**
86
     * Символьный идентификатор.
87
     * @param string $code
88
     * @return $this
89
     */
90
    public function setCode($code)
91
    {
92
        $this->fields['CODE'] = $code;
93
94
        return $this;
95
    }
96
97
    /**
98
     * Внешний код.
99
     * @param string $xml_id
100
     * @return $this
101
     */
102
    public function setXmlId($xml_id)
103
    {
104
        $this->fields['XML_ID'] = $xml_id;
105
106
        return $this;
107
    }
108
109
    /**
110
     * Код типа инфоблока
111
     * @param string $iblockTypeId
112
     * @return $this
113
     */
114
    public function setIblockTypeId($iblockTypeId)
115
    {
116
        $this->fields['IBLOCK_TYPE_ID'] = $iblockTypeId;
117
118
        return $this;
119
    }
120
121
    /**
122
     * Название.
123
     * @param string $name
124
     * @return $this
125
     */
126
    public function setName($name)
127
    {
128
        $this->fields['NAME'] = $name;
129
130
        return $this;
131
    }
132
133
    /**
134
     * Флаг активности
135
     * @param bool $active
136
     * @return $this
137
     */
138
    public function setActive($active = true)
139
    {
140
        $this->fields['ACTIVE'] = $active ? 'Y' : 'N';
141
142
        return $this;
143
    }
144
145
    /**
146
     * Индекс сортировки.
147
     * @param int $sort
148
     * @return $this
149
     */
150
    public function setSort($sort = 500)
151
    {
152
        $this->fields['SORT'] = $sort;
153
154
        return $this;
155
    }
156
157
    /**
158
     * Шаблон URL-а к странице для публичного просмотра списка элементов информационного блока.
159
     * @param string $listPageUrl
160
     * @return $this
161
     */
162
    public function setListPageUrl($listPageUrl)
163
    {
164
        $this->fields['LIST_PAGE_URL'] = $listPageUrl;
165
166
        return $this;
167
    }
168
169
    /**
170
     * Шаблон URL-а к странице для просмотра раздела.
171
     * @param string $sectionPageUrl
172
     * @return $this
173
     */
174
    public function setSectionPageUrl($sectionPageUrl)
175
    {
176
        $this->fields['SECTION_PAGE_URL'] = $sectionPageUrl;
177
178
        return $this;
179
    }
180
181
    /**
182
     * Канонический URL элемента.
183
     * @param string $canonicalPageUrl
184
     * @return $this
185
     */
186
    public function setCanonicalPageUrl($canonicalPageUrl)
187
    {
188
        $this->fields['CANONICAL_PAGE_URL'] = $canonicalPageUrl;
189
190
        return $this;
191
    }
192
193
    /**
194
     * URL детальной страницы элемента.
195
     *
196
     * @param string $detailPageUrl
197
     *
198
     * @return $this
199
     */
200
    public function setDetailPageUrl($detailPageUrl)
201
    {
202
        $this->fields['DETAIL_PAGE_URL'] = $detailPageUrl;
203
204
        return $this;
205
    }
206
207
    /**
208
     * Устанавливает значения по умолчанию для страниц инфоблока, раздела и деталей элемента
209
     * (как при создании через административный интерфейс или с ЧПУ).
210
     *
211
     * Для использовании ЧПУ рекомендуется сделать обязательными для заполнения символьный код
212
     * элементов и разделов инфоблока.
213
     *
214
     * @param bool sef Использовать ли ЧПУ (понадобится добавить правило в urlrewrite)
215
     *
216
     * @return IBlock
217
     */
218
    public function setDefaultUrls($sef = false)
219
    {
220
        if ($sef === true) {
221
            $prefix = "#SITE_DIR#/#IBLOCK_TYPE_ID#/#IBLOCK_CODE#/";
222
            $this
223
                ->setListPageUrl($prefix)
224
                ->setSectionPageUrl("$prefix#SECTION_CODE_PATH#/")
225
                ->setDetailPageUrl("$prefix#SECTION_CODE_PATH#/#ELEMENT_CODE#/");
226
        } else {
227
            $prefix = "#SITE_DIR#/#IBLOCK_TYPE_ID#";
228
            $this
229
                ->setListPageUrl("$prefix/index.php?ID=#IBLOCK_ID#")
230
                ->setSectionPageUrl("$prefix/list.php?SECTION_ID=#SECTION_ID#")
231
                ->setDetailPageUrl("$prefix/detail.php?ID=#ELEMENT_ID#");
232
        }
233
234
        return $this;
235
    }
236
237
    /**
238
     * Код картинки в таблице файлов.
239
     * @param array $picture
240
     * @return $this
241
     */
242
    public function setPicture($picture)
243
    {
244
        $this->fields['PICTURE'] = $picture;
245
246
        return $this;
247
    }
248
249
    /**
250
     * Описание.
251
     * @param string $description
252
     * @return $this
253
     */
254
    public function setDescription($description)
255
    {
256
        $this->fields['DESCRIPTION'] = $description;
257
258
        return $this;
259
    }
260
261
    /**
262
     * Тип описания (text/html)
263
     * @param string $descriptionType
264
     * @return $this
265
     */
266
    public function setDescriptionType($descriptionType = 'text')
267
    {
268
        $this->fields['DESCRIPTION_TYPE'] = $descriptionType;
269
270
        return $this;
271
    }
272
273
    /**
274
     * Разрешен экспорт в RSS динамически
275
     * @param bool $rssActive
276
     * @return $this
277
     */
278
    public function setRssActive($rssActive = true)
279
    {
280
        $this->fields['RSS_ACTIVE'] = $rssActive ? 'Y' : 'N';
281
282
        return $this;
283
    }
284
285
    /**
286
     * Время жизни RSS и интервал между генерациями файлов RSS (при включенном RSS_FILE_ACTIVE или RSS_YANDEX_ACTIVE) (часов).
287
     * @param int $rssTtl
288
     * @return $this
289
     */
290
    public function setRssTtl($rssTtl = 24)
291
    {
292
        $this->fields['RSS_TTL'] = $rssTtl;
293
294
        return $this;
295
    }
296
297
    /**
298
     * Прегенерировать выгрузку в файл.
299
     * @param bool $rssFileActive
300
     * @return $this
301
     */
302
    public function setRssFileActive($rssFileActive = false)
303
    {
304
        $this->fields['RSS_FILE_ACTIVE'] = $rssFileActive ? 'Y' : 'N';
305
306
        return $this;
307
    }
308
309
    /**
310
     * Количество экспортируемых в RSS файл элементов (при включенном RSS_FILE_ACTIVE)
311
     * @param int $rssFileLimit
312
     * @return $this
313
     */
314
    public function setRssFileLimit($rssFileLimit)
315
    {
316
        $this->fields['RSS_FILE_LIMIT'] = $rssFileLimit;
317
318
        return $this;
319
    }
320
321
    /**
322
     * За сколько последних дней экспортировать в RSS файл. (при включенном RSS_FILE_ACTIVE). -1 без ограничения по дням.
323
     * @param int $rssFileDays
324
     * @return $this
325
     */
326
    public function setRssFileDays($rssFileDays)
327
    {
328
        $this->fields['RSS_FILE_DAYS'] = $rssFileDays;
329
330
        return $this;
331
    }
332
333
    /**
334
     * Экспортировать в RSS файл в формате для yandex
335
     * @param bool $rssYandexActive
336
     * @return $this
337
     */
338
    public function setRssYandexActive($rssYandexActive = false)
339
    {
340
        $this->fields['RSS_YANDEX_ACTIVE'] = $rssYandexActive ? 'Y' : 'N';
341
342
        return $this;
343
    }
344
345
    /**
346
     * Индексировать для поиска элементы информационного блока.
347
     * @param bool $indexElement
348
     * @return $this
349
     */
350
    public function setIndexElement($indexElement = true)
351
    {
352
        $this->fields['INDEX_ELEMENT'] = $indexElement ? 'Y' : 'N';
353
354
        return $this;
355
    }
356
357
    /**
358
     * Индексировать для поиска разделы информационного блока.
359
     * @param bool $indexSection
360
     * @return $this
361
     */
362
    public function setIndexSection($indexSection = false)
363
    {
364
        $this->fields['INDEX_SECTION'] = $indexSection ? 'Y' : 'N';
365
366
        return $this;
367
    }
368
369
    /**
370
     * Режим отображения списка элементов в административном разделе (S|C).
371
     * @param string $listMode
372
     * @return $this
373
     */
374
    public function setListMode($listMode)
375
    {
376
        $this->fields['LIST_MODE'] = $listMode;
377
378
        return $this;
379
    }
380
381
    /**
382
     * Режим проверки прав доступа (S|E).
383
     * @param string $rightsMode
384
     * @return $this
385
     */
386
    public function setRightsMode($rightsMode = 'S')
387
    {
388
        $this->fields['RIGHTS_MODE'] = $rightsMode;
389
390
        return $this;
391
    }
392
393
    /**
394
     * Признак наличия привязки свойств к разделам (Y|N).
395
     * @param string $sectionProperty
396
     * @return $this
397
     */
398
    public function setSectionProperty($sectionProperty)
399
    {
400
        $this->fields['SECTION_PROPERTY'] = $sectionProperty;
401
402
        return $this;
403
    }
404
405
    /**
406
     * Признак наличия фасетного индекса (N|Y|I).
407
     * @param string $propertyIndex
408
     * @return $this
409
     */
410
    public function setPropertyIndex($propertyIndex)
411
    {
412
        $this->fields['PROPERTY_INDEX'] = $propertyIndex;
413
414
        return $this;
415
    }
416
417
    /**
418
     * Служебное поле для процедуры конвертации места хранения значений свойств инфоблока.
419
     * @param int $lastConvElement
420
     * @return $this
421
     */
422
    public function setLastConvElement($lastConvElement)
423
    {
424
        $this->fields['LAST_CONV_ELEMENT'] = $lastConvElement;
425
426
        return $this;
427
    }
428
429
    /**
430
     * Служебное поле для установки прав для разных групп на доступ к информационному блоку.
431
     * @param array $groupId Массив соответствий кодов групп правам доступа
432
     * @return $this
433
     */
434
    public function setGroupId($groupId)
435
    {
436
        $this->fields['GROUP_ID'] = $groupId;
437
438
        return $this;
439
    }
440
441
    /**
442
     * Служебное поле для привязки к группе социальной сети.
443
     * @param int $socnetGroupId
444
     * @return $this
445
     */
446
    public function setSocnetGroupId($socnetGroupId)
447
    {
448
        $this->fields['SOCNET_GROUP_ID'] = $socnetGroupId;
449
450
        return $this;
451
    }
452
453
    /**
454
     * Инфоблок участвует в документообороте (Y|N).
455
     * @param bool $workflow
456
     * @return $this
457
     */
458
    public function setWorkflow($workflow = true)
459
    {
460
        $this->fields['WORKFLOW'] = $workflow ? 'Y' : 'N';
461
462
        return $this;
463
    }
464
465
    /**
466
     * Инфоблок участвует в бизнес-процессах (Y|N).
467
     * @param bool $bizproc
468
     * @return $this
469
     */
470
    public function setBizProc($bizproc = false)
471
    {
472
        $this->fields['BIZPROC'] = $bizproc ? 'Y' : 'N';
473
474
        return $this;
475
    }
476
477
    /**
478
     * Флаг выбора интерфейса отображения привязки элемента к разделам (D|L|P).
479
     * @param string $sectionChooser
480
     * @return $this
481
     */
482
    public function setSectionChooser($sectionChooser)
483
    {
484
        $this->fields['SECTION_CHOOSER'] = $sectionChooser;
485
486
        return $this;
487
    }
488
489
    /**
490
     * Флаг хранения значений свойств элементов инфоблока (1 - в общей таблице | 2 - в отдельной).
491
     * @param int $version
492
     * @return $this
493
     */
494
    public function setVersion($version = 1)
495
    {
496
        $this->fields['VERSION'] = $version;
497
498
        return $this;
499
    }
500
501
    /**
502
     * Полный путь к файлу-обработчику массива полей элемента перед сохранением на странице редактирования элемента.
503
     * @param string $editFileBefore
504
     * @return $this
505
     */
506
    public function setEditFileBefore($editFileBefore)
507
    {
508
        $this->fields['EDIT_FILE_BEFORE'] = $editFileBefore;
509
510
        return $this;
511
    }
512
513
    /**
514
     * Полный путь к файлу-обработчику вывода интерфейса редактирования элемента.
515
     * @param string $editFileAfter
516
     * @return $this
517
     */
518
    public function setEditFileAfter($editFileAfter)
519
    {
520
        $this->fields['EDIT_FILE_AFTER'] = $editFileAfter;
521
522
        return $this;
523
    }
524
525
    /**
526
     * Название элемента в единственном числе
527
     * @param string $message
528
     * @return $this
529
     */
530
    public function setMessElementName($message = 'Элемент')
531
    {
532
        $this->fields['ELEMENT_NAME'] = $message;
533
534
        return $this;
535
    }
536
537
    /**
538
     * Название элемента во множнственном числе
539
     * @param string $message
540
     * @return $this
541
     */
542
    public function setMessElementsName($message = 'Элементы')
543
    {
544
        $this->fields['ELEMENTS_NAME'] = $message;
545
546
        return $this;
547
    }
548
549
    /**
550
     * Действие по добавлению элемента
551
     * @param string $message
552
     * @return $this
553
     */
554
    public function setMessElementAdd($message = 'Добавить элемент')
555
    {
556
        $this->fields['ELEMENT_ADD'] = $message;
557
558
        return $this;
559
    }
560
561
    /**
562
     * Действие по редактированию/изменению элемента
563
     * @param string $message
564
     * @return $this
565
     */
566
    public function setMessElementEdit($message = 'Изменить элемент')
567
    {
568
        $this->fields['ELEMENT_EDIT'] = $message;
569
570
        return $this;
571
    }
572
573
    /**
574
     * Действие по удалению элемента
575
     * @param string $message
576
     * @return $this
577
     */
578
    public function setMessElementDelete($message = 'Удалить элемент')
579
    {
580
        $this->fields['ELEMENT_DELETE'] = $message;
581
582
        return $this;
583
    }
584
585
    /**
586
     * Название раздела в единственном числе
587
     * @param string $message
588
     * @return $this
589
     */
590
    public function setMessSectionName($message = 'Раздел')
591
    {
592
        $this->fields['SECTION_NAME'] = $message;
593
594
        return $this;
595
    }
596
597
    /**
598
     * Название раздела во множнственном числе
599
     * @param string $message
600
     * @return $this
601
     */
602
    public function setMessSectionsName($message = 'Разделы')
603
    {
604
        $this->fields['SECTIONS_NAME'] = $message;
605
606
        return $this;
607
    }
608
609
    /**
610
     * Действие по добавлению раздела
611
     * @param string $message
612
     * @return $this
613
     */
614
    public function setMessSectionAdd($message = 'Добавить раздел')
615
    {
616
        $this->fields['SECTION_ADD'] = $message;
617
618
        return $this;
619
    }
620
621
    /**
622
     * Действие по редактированию/изменению раздела
623
     * @param string $message
624
     * @return $this
625
     */
626
    public function setMessSectionEdit($message = 'Изменить раздел')
627
    {
628
        $this->fields['SECTION_EDIT'] = $message;
629
630
        return $this;
631
    }
632
633
    /**
634
     * Действие по удалению раздела
635
     * @param string $message
636
     * @return $this
637
     */
638
    public function setMessSectionDelete($message = 'Удалить раздел')
639
    {
640
        $this->fields['SECTION_DELETE'] = $message;
641
642
        return $this;
643
    }
644
645
646
}
647