GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#223)
by
unknown
20:28 queued 13:51
created

BContactController   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 441
Duplicated Lines 4.08 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
dl 18
loc 441
rs 8.6
c 0
b 0
f 0
wmc 37
lcom 1
cbo 7

10 Methods

Rating   Name   Duplication   Size   Complexity  
B actionUpdate() 0 204 1
A actionSort() 0 12 3
B actionDelete() 0 31 5
A sortFields() 9 9 2
A sortTextBlocks() 9 9 2
B saveModels() 0 32 6
B saveTextblock() 0 29 6
A createTextBlock() 0 10 2
A saveGroup() 0 16 3
C saveField() 0 33 7

How to fix   Duplicated Code   

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:

1
<?php
2
/**
3
 * @author Nikita Melnikov <[email protected]>
4
 * @link https://github.com/shogodev/argilla/
5
 * @copyright Copyright &copy; 2003-2014 Shogo
6
 * @license http://argilla.ru/LICENSE
7
 * @package backend.modules.contact.controllers
8
 */
9
class BContactController extends BController
10
{
11
  public $name = 'Контакты';
12
13
  public $modelClass = 'BContact';
14
15
  public $position = 1;
16
17
  /**
18
   * @param $id
19
   */
20
  public function actionUpdate($id)
21
  {
22
    Yii::app()->clientScript->registerScript(
23
      'BContactFormScripts', "
24
      $(function(){
25
        //-----------------------------------------------------------------------------
26
        // Добавить тестовое поле
27
        var textblockCounter = 0;
28
        $('.action.btn[data-action=\"add-textblock\"]').on('click', function(){
29
          var name    = $('<input type=\"text\" style=\"width:250px\" name=\"BContactTextBlock[new][' + textblockCounter + '][name]\"    placeholder=\"Заголовок\" />');
30
          var sysname = $('<input type=\"text\" style=\"width:250px\" name=\"BContactTextBlock[new][' + textblockCounter + '][sysname]\" placeholder=\"Системное имя\" />');
31
      
32
          // создание кнопки \"Удалить\"
33
          var button_delete = $('<a href=\"#\" rel=\"tooltip\" title=\"Удалить текстовый блок\" class=\"btn btn-alone delete\" />');
34
          button_delete.on('click', function(e) {
35
            e.preventDefault();
36
            $(this).parent('div').remove();
37
          });
38
      
39
          var content = $('<div style=\"margin-bottom:5px\" />');
40
          content.append(name);
41
          $(content).append(' ');
42
          content.append(sysname);
43
          $(content).append(' ');
44
          $(content).append(button_delete);
45
          $('#textblock-add-cell').append(content);
46
      
47
          textblockCounter++;
48
        });
49
      
50
        //-----------------------------------------------------------------------------
51
        // Добавление группы полей
52
        var group_counter = 1;
53
        $('.action.btn[data-action=\"group\"]').on('click', function(){
54
          // создание поля с названием поля
55
          var name    = $('<input type=\"text\" style=\"width:250px\" name=\"BContactGroup[' + group_counter + '][name]\" placeholder=\"Название\" />');
56
      
57
          // создание поля с системным именем поля
58
          var sysname = $('<input type=\"text\" style=\"width:250px\" name=\"BContactGroup[' + group_counter + '][sysname]\" placeholder=\"Системное имя\" />');
59
      
60
          // создание кнопки \"Удалить\"
61
          var button_delete = $('<a href=\"#\" rel=\"tooltip\" title=\"Удалить поле\" class=\"btn btn-alone delete\" />');
62
          button_delete.on('click', function(e) {
63
            e.preventDefault();
64
            $(this).parent('div').remove();
65
          });
66
      
67
          var content = $('<div style=\"margin-bottom:5px\" />');
68
          content.append(name);
69
          $(content).append(' ');
70
          content.append(sysname);
71
          $(content).append(' ');
72
          $(content).append(button_delete);
73
      
74
          $('#group-add-cell').append(content);
75
          group_counter++;
76
        });
77
      
78
        //-----------------------------------------------------------------------------
79
        // Добавление поля к группе
80
        $('.action.btn[data-action=\"field\"]').on('click', function(){
81
          var group = $(this).attr('data-group'),
82
              list = $('.field-add-cell[data-group=' + group + '] ul');
83
          var last_id = list.find('li').size();
84
      
85
          // создание иконки
86
          var icon = $('<i class=\"icon-move\" style=\"background:none;\"/>');
87
      
88
          // создание поля со значением поля
89
          var name = $('<input type=\"text\" style=\"width:250px\" name=\"BContactField[new][' + last_id + '][' + group + '][value]\" />');
90
      
91
          // создание поля с описанием поля
92
          var description = $('<input type=\"text\" style=\"width:500px\" name=\"BContactField[new][' + last_id + '][' + group + '][description]\" />');
93
      
94
          // создание кнопки \"Удалить\"
95
          var button_delete = $('<a href=\"#\" rel=\"tooltip\" title=\"Удалить поле\" style=\"background:none;content:none;\" class=\"btn btn-alone delete\" />');
96
          button_delete.on('click', function(e) {
97
            e.preventDefault();
98
            $(this).parent('li').remove();
99
          });
100
      
101
          // добавляем все созданные элементы в список
102
          var content = $('<li class=\"not-sortable\" style=\"margin-bottom:5px;cursor:default;\" />');
103
      
104
          $(content).append(icon);
105
          $(content).append(' ');
106
          $(content).append(name);
107
          $(content).append(' ');
108
          $(content).append(description);
109
          $(content).append(' ');
110
          $(content).append(button_delete);
111
      
112
          list.append(content);
113
        });
114
      
115
        // -----------------------------------------------------------------------------------------
116
        // Сортировка полей в группе
117
        $('.sortable').sortable({
118
          items: 'li:not(.not-sortable)',
119
          update: function(event, ui) {
120
            sortFields(ui.item);
121
          }
122
        });
123
      
124
        function sortFields(item) {
125
          var url      = '" . $this->createUrl('sort') . "';
126
          var list     = [];
127
          var position = 1;
128
          var hasError = false;
129
      
130
          // создание массива полей
131
          $(item).parents('ul').children('li:not(.not-sortable)').each(function(){
132
            var listItem         = {};
133
            listItem['id']       = $(this).attr('data-fid');
134
            listItem['position'] = position;
135
      
136
            list.push(listItem);
137
            position++;
138
          });
139
      
140
          if( !hasError )
141
            $.post(url, {'sort' : list, 'type' : 'field'});
142
        }
143
      
144
        // -----------------------------------------------------------------------------------------
145
        // Сортировка текстовых блоков
146
        $('.textblock-container').sortable({
147
          update: function(event, ui) {
148
            sortTextBlocks(ui.item);
149
          }
150
        });
151
      
152
        function sortTextBlocks(item)
153
        {
154
          var url      = '" . $this->createUrl('sort') . "';
155
          var list     = [];
156
          var position = 1;
157
          var hasError = false;
158
      
159
          console.log(item);
160
      
161
          // создание массива полей
162
          $(item).parents('ul').children('li').each(function(){
163
            var listItem         = {};
164
            listItem['id']       = $(this).attr('data-textblock-id');
165
            listItem['position'] = position;
166
      
167
            list.push(listItem);
168
            position++;
169
          });
170
      
171
          if( !hasError )
172
            $.post(url, {'sort' : list, 'type' : 'textblock'});
173
        }
174
      
175
        // -------------------------------------------------------------------------------------------
176
        // Удаление полей
177
        $('.btn.delete').on('click', function(e){
178
          e.preventDefault();
179
      
180
          var id = $(this).attr('data-fid');
181
          var type = 'field';
182
      
183
          if( id === undefined )
184
          {
185
            id = $(this).attr('data-textblock-id');
186
            type = 'textblock';
187
          }
188
      
189
          if( id === undefined )
190
            return false;
191
      
192
          var url  = '" . $this->createUrl('delete') . "';
193
          var self = $(this);
194
      
195
          var callback = function(resp){
196
            $(self).parents('li').fadeOut();
197
          };
198
      
199
          $.post(url, {'delete' : {'id' : id, 'type' : type}}, callback);
200
        });
201
      
202
        // -------------------------------------------------------------------------------------------
203
        // Удаление группы полей
204
        $('span.delete-group').on('click', function(){
205
          if( !confirm('Вы уверены, что хотите удалить группу полей?') )
206
            return false;
207
      
208
          var url = '" . $this->createUrl('delete') . "';
209
          var id  = $(this).attr('data-group');
210
      
211
          var callback = function(resp){
212
            $('td.field-add-cell[data-group=' + id + ']').parents('tr').fadeOut();
213
          };
214
      
215
          $.post(url, {'delete' : {'id' : id, 'type' : 'group'}}, callback);
216
        });
217
      
218
      });",
219
      CClientScript::POS_END
220
    );
221
222
    parent::actionUpdate($id);
223
  }
224
225
  /**
226
   * Сохранение сортировки
227
   */
228
  public function actionSort()
229
  {
230
    switch( Yii::app()->request->getPost('type') )
231
    {
232
      case 'field':
233
        $this->sortFields();
234
        break;
235
      case 'textblock':
236
        $this->sortTextBlocks();
237
        break;
238
    }
239
  }
240
241
  /**
242
   * Удаление поля из группы полей
243
   */
244
  public function actionDelete()
245
  {
246
    $data = Yii::app()->request->getPost('delete');
247
248
    if( !empty($data['id']) )
249
    {
250
      /**
251
       * Может приходить всего 3 типа данных на удаление
252
       * field - поле в группе
253
       * group - группа полей
254
       * textbloc - текстовой блок
255
       */
256
      switch( $data['type'] )
257
      {
258
        case 'field':
259
          $field = BContactField::model()->findByPk($data['id']);
260
          $field->delete();
261
          break;
262
263
        // Для группы полей так же удаляем все дочерние элементы
264
        case 'group':
265
          $group = BContactGroup::model()->findByPk($data['id']);
266
          $group->delete();
267
          break;
268
269
        case 'textblock':
270
          $textblock = BContactTextBlock::model()->findByPk($data['id'])->delete();
0 ignored issues
show
Unused Code introduced by
$textblock is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
271
          break;
272
      }
273
    }
274
  }
275
276
  /**
277
   * Сортировка полей группы
278
   */
279 View Code Duplication
  protected function sortFields()
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...
280
  {
281
    foreach( Yii::app()->request->getPost('sort') as $sortItem )
282
    {
283
      $field           = BContactField::model()->findByPk($sortItem['id']);
284
      $field->position = $sortItem['position'];
285
      $field->save();
286
    }
287
  }
288
289
  /**
290
   * Сортировка текстовых блоков
291
   */
292 View Code Duplication
  protected function sortTextBlocks()
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...
293
  {
294
    foreach( Yii::app()->request->getPost('sort') as $sortItem )
295
    {
296
      $textblock = BContactTextBlock::model()->findByPk($sortItem['id']);
297
      $textblock->position = $sortItem['position'];
298
      $textblock->save();
299
    }
300
  }
301
302
  /**
303
   * @inheritdoc
304
   */
305
  protected function saveModels($models, $extendedSave = true, $redirectToUpdate = true)
306
  {
307
    $model = Arr::reset($models);
308
309
    Yii::app()->getClientScript()->registerCoreScript( 'jquery.ui' );
310
311
    $this->performAjaxValidation($model);
312
    $attributes = Yii::app()->request->getPost(get_class($model));
313
314
    if( isset($attributes) )
315
    {
316
      $model->setAttributes($attributes);
317
318
      if( $model->save() )
319
      {
320
        $this->saveGroup($model);
321
        $this->saveField();
322
323
        $this->saveTextblock($model);
324
325
        if( $redirectToUpdate )
326
        {
327
          Yii::app()->user->setFlash('success', 'Запись успешно '.($model->isNewRecord ? 'создана' : 'сохранена').'.');
328
329
          if( Yii::app()->request->getParam('action') )
330
            $this->redirect($this->getBackUrl());
331
          else
332
            $this->redirect(array('update', 'id' => $model->id));
333
        }
334
      }
335
    }
336
  }
337
338
  /**
339
   * Сохранение текстовых блоков для записи контактов
340
   *
341
   * @param BContact $model
342
   */
343
  protected function saveTextblock(BContact $model)
344
  {
345
    $textblocks = Yii::app()->request->getPost('BContactTextBlock');
346
347
    if( !empty($textblocks['new']) )
348
    {
349
      $this->createTextBlock($model, $textblocks['new']);
350
      unset($textblocks['new']);
351
    }
352
353
    if( !empty($textblocks) )
354
    {
355
      foreach( $textblocks as $id => $values )
356
      {
357
        $textblock = BContactTextBlock::model()->findByPk($id);
358
359
        if( !empty($values['delete']) )
360
          $textblock->delete();
361
        else
362
        {
363
          if( empty($values['visible']) )
364
          $values['visible'] = 0;
365
366
          $textblock->setAttributes($values);
367
          $textblock->save();
368
        }
369
      }
370
    }
371
  }
372
373
  /**
374
   * Создание новых текстовых блоков
375
   *
376
   * @param BContact $model
377
   * @param array $data
378
   */
379
  public function createTextBlock(BContact $model, array $data)
380
  {
381
    foreach( $data as $item )
382
    {
383
      $textblock = new BContactTextBlock();
384
      $textblock->setAttributes($item);
385
      $textblock->contact_id = $model->id;
386
      $textblock->save();
387
    }
388
  }
389
390
  /**
391
   * Сохранение групп для текущей записи контактов
392
   *
393
   * @param array $model
394
   */
395
  protected function saveGroup($model)
396
  {
397
    $groups = Yii::app()->request->getPost('BContactGroup');
398
399
    if( empty($groups) ) return;
400
401
    foreach( $groups as $group )
402
    {
403
      $contactGroup             = new BContactGroup();
404
      $contactGroup->name       = $group['name'];
405
      $contactGroup->sysname    = $group['sysname'];
406
      $contactGroup->contact_id = $model->id;
407
408
      $contactGroup->save();
409
    }
410
  }
411
412
  /**
413
   * Сохранение полей для групп полей
414
   * Так же осуществляется создание новых полей по ключу 'new'
415
   */
416
  protected function saveField()
417
  {
418
    $fields = Yii::app()->request->getPost('BContactField');
419
420
    if( empty($fields) ) return;
421
422
    foreach( $fields as $id => $field )
423
    {
424
      // Если в качестве ключа используется PK, то обновляем запись
425
      if( is_numeric($id) )
426
      {
427
        $contactField              = BContactField::model()->findByPk($id);
428
        $contactField->value       = $field['value'];
429
        $contactField->description = $field['description'];
430
        $contactField->save();
431
      }
432
      // Если используется ключ new, создаем навые записи
433
      elseif( $id == 'new' )
434
      {
435
        foreach( $field as $newFields )
436
        {
437
          foreach( $newFields as $groupId => $params )
438
          {
439
            $contactField              = new BContactField();
440
            $contactField->value       = $params['value'];
441
            $contactField->description = $params['description'];
442
            $contactField->group_id    = $groupId;
443
            $contactField->save();
444
          }
445
        }
446
      }
447
    }
448
  }
449
}