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.

TreeviewActionsWidget::run()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 0
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Sergey Glagolev <[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.widgets
8
 */
9
class TreeviewActionsWidget extends CWidget
10
{
11
  /**
12
   * @var CActiveRecord
13
   */
14
  public $model;
15
16
  public function run()
17
  {
18
    if( !isset($this->model) )
19
    {
20
      throw new CHttpException(500, '"model" have to be set!');
21
    }
22
23
    $actions = array();
24
    $items = $this->model->findAll();
25
26
    if( method_exists($this->model, 'getTreeActions') )
27
      $actions = $this->model->getTreeActions();
28
29
    if( !empty($actions) )
30
    {
31
      $this->renderActions($actions, $items);
32
    }
33
  }
34
35
  private function renderActions(array $actions, array $items)
36
  {
37
    $jdata = array();
38
39
    echo CHtml::openTag('div', array('id' => 'treeview-actions'));
40
41
    foreach($actions as $id => $action)
42
    {
43
      $class = $id;
44
      $title = $action;
45
      $url = '#';
46
47
      if( is_array($action) )
48
      {
49
        $title = Arr::get($action, 'title', '');
50
        $class = Arr::get($action, 'class', $id);
51
        $url = Arr::get($action, 'url', '#');
52
        $submit = Arr::get($action, 'submit', false);
0 ignored issues
show
Unused Code introduced by
$submit 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...
53
        $onClick = Arr::get($action, 'onClick');
54
      }
55
56
      foreach($items as $item)
57
      {
58
        $jdata[$item->id][$id] = array('disabled' => isset($item->$id) && !$item->$id ? true : false,
59
          'toggle' => $url === '#' ? true : false,
60
          'url' => $url === '#' ? '#' : $this->buildUrl($url, $item),
61
        );
62
      }
63
64
      echo CHtml::link('', $url, array('rel' => 'tooltip',
65
          'title' => $title,
66
          'data-action' => $id,
67
          'onClick' => $onClick,
0 ignored issues
show
Bug introduced by
The variable $onClick does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
68
          'class' => 'btn btn-small '.$class)).PHP_EOL;
69
    }
70
71
    echo CHtml::closeTag('div');
72
73
    $jdata = CJavaScript::encode($jdata);
74
75
    $this->registerScriptTreeViewActions($jdata);
76
    $this->registerScriptTreeViewActionsDragAndDrop();
77
  }
78
79
  private function buildUrl($url, $item)
80
  {
81
    $urlParams = Arr::reset($url);
82
    $urlAction = key($url);
83
84
    foreach($urlParams as $key => $param)
85
      $urlParams[$key] = Yii::app()->evaluateExpression($param, array('data' => $item));
86
87
    return Yii::app()->controller->createUrl($urlAction, $urlParams);
88
  }
89
90
  private function registerScriptTreeViewActions($jdata)
91
  {
92
    $modelId = $this->model->id;
93
    $modelClass = get_class($this->model);
94
    $indexUrl = Yii::app()->controller->createUrl('index');
95
    $ajaxUrl = Yii::app()->controller->createUrl('toggle', array('attribute' => '_attr_', 'id' => '_id_'));
96
    $deleteUrl = Yii::app()->controller->createUrl('delete', array('id' => '_id_'));
97
98
    Yii::app()->clientScript->registerScript(__CLASS__.'_InitPlugin', "
99
      var treeActions = {$jdata};
100
      var modelClass  = '{$modelClass}';
101
      var modelId     = '{$modelId}';
102
      var indexUrl    = '{$indexUrl}';
103
      var ajaxUrl     = '{$ajaxUrl}';
104
      var deleteUrl   = '{$deleteUrl}';
105
106
      function initTreeActions()
107
      {
108
109
        $('.filetree li:not(#node_1) a').unifloat({
110
          rel: '#treeview-actions',
111
          posTop: { value: 'top - 2', auto: false },
112
          posLeft: { value: 'after', auto: false },
113
114
          onShow: function(source, target)
115
          {
116
            if( $(source).parent().attr('id') === undefined )
117
              return false;
118
            var id = $(source).parent().attr('id').match(/node_(\d+)/)[1];
119
120
            for(var i in treeActions[id])
121
            {
122
              var button = $(target).find('[data-action='+i+']');
123
              button.toggleClass('disabled', treeActions[id][i].disabled);
124
              button.attr('href', treeActions[id][i].url);
125
              button.data('toggle', treeActions[id][i].toggle);
126
              button.data('id', id);
127
            }
128
          }
129
        });
130
      }
131
    ", CClientScript::POS_READY);
132
133
    Yii::app()->clientScript->registerScript(__CLASS__, "
134
      initTreeActions();
135
136
      $('#treeview-actions a').on('click', function(e)
137
      {
138
        var self   = this;
139
        var action = $(this).data('action');
140
        var id     = $(this).data('id');
141
142
        if( action === 'delete' )
143
        {
144
          e.preventDefault();
145
146
          if( !confirm('Вы действительно хотите удалить данный элемент?') )
147
            return;
148
149
          return function(id)
150
          {
151
            var callback = function(resp)
152
            {
153
              document.location.href = indexUrl;
154
            };
155
156
            $.post(deleteUrl.replace('_id_', id), {}, callback);
157
          }(id);
158
        }
159
160
        if( !$(this).data('toggle') )
161
          return;
162
        else
163
          e.preventDefault();
164
165
        var callback = function(resp)
166
        {
167
          $(self).toggleClass('disabled');
168
          treeActions[id][action].disabled = !treeActions[id][action].disabled;
169
170
          if( treeActions[id].visible )
171
            $('#tree_'+modelClass+' li#node_'+id).toggleClass('disabled', treeActions[id].visible.disabled);
172
173
          if( $('#'+modelClass+'_'+action).length && modelId == id  )
174
            $('#'+modelClass+'_'+action).attr('checked', treeActions[id][action].disabled ? false : true);
175
        };
176
177
        $.post(ajaxUrl.replace('_attr_', action).replace('_id_', id), {}, callback);
178
      });
179
180
      $('#tree_'+modelClass+' a').each(function()
181
      {
182
        var id = $(this).parent().attr('id').match(/node_(\d+)/)[1];
183
        if( treeActions[id].visible && treeActions[id].visible.disabled === true )
184
          $(this).parent().addClass('disabled');
185
      });
186
    ", CClientScript::POS_READY);
187
  }
188
189
  private function registerScriptTreeViewActionsDragAndDrop()
190
  {
191
    $treeId = 'tree_'.get_class($this->model);
192
    $dragAndDropUrl = Yii::app()->controller->createUrl('info/dragAndDrop');
193
194
    Yii::app()->clientScript->registerScript(__CLASS__.'_dragAndDrop', "
195
      var treeId = '{$treeId}';
196
197
      var dragAndDropUrl = '{$dragAndDropUrl}';
198
      var parentSelector;
199
      var targetSelector;
200
201
      $('ul.filetree').on('click', 'li#node_1>a', function(e){
202
        e.preventDefault();
203
      });
204
205
      var dropCallback = function(target, draggableItem)
206
      {
207
        var callback = function callback(resp)
208
        {
209
          if( $(resp).attr('id') == treeId )
210
          {
211
            $('#sidebar').find('#'+treeId).html($(resp).html());
212
            $('#' + treeId).treeview({'persist':'cookie', 'collapsed':true, 'animated':'fast'});
213
            initTreeDragAndDrop($('#' + treeId));
214
            initTreeActions();
215
          }
216
        }
217
218
        var draggableText = draggableItem.children('a').text()
219
        var targetText = target.children('a').text()
220
        var current = $('#' + treeId + ' li.current').length > 0 ? $('#' + treeId + ' li.current').attr('id').match(/node_(\d+)/)[1] : 0
221
222
        var dragId = draggableItem.attr('id').match(/node_(\d+)/)[1];
223
        var dropId = target.attr('id').match(/node_(\d+)/)[1];
224
        var parentDragId = parentSelector.attr('id').match(/node_(\d+)/)[1];
225
226
        draggableItem.height('auto');
227
228
        if( parentDragId == dropId )
229
          return false;
230
231
        if( confirm('Вы действительно хотите перенести раздел \"' + draggableText + '\" в \"' + targetText + '\"' ) )
232
        {
233
          $.post(dragAndDropUrl, {
234
              'action' : 'move',
235
              'drag' : dragId,
236
              'drop' : dropId,
237
              'current' : current
238
            }
239
            , callback);
240
241
          return true;
242
        }
243
        else
244
         return false;
245
      };
246
247
      var initTreeDragAndDrop = function(tree)
248
      {
249
        var treeItems = tree.find('li');
250
251
        $(treeItems).droppable({
252
          tolerance : 'pointer',
253
          hoverClass: 'drop-hover',
254
          greedy: true,
255
          drop: function() {
256
            targetSelector = $(this);
257
          }
258
        });
259
260
        $(treeItems).draggable({
261
          connectToSortable: '#' + tree.attr('id'),
262
          revert: true,
263
          revertDuration: 0,
264
          draggableItem: null,
265
          start: function() {
266
            this.draggableItem = $(this);
267
            parentSelector = $(this).parent().parent();
268
            targetSelector = null;
269
          },
270
          stop: function()
271
          {
272
            if( targetSelector && !dropCallback(targetSelector, this.draggableItem) )
273
              return;
274
275
            if ( targetSelector !== null )
276
            {
277
              if ( targetSelector.hasClass('folder') )
278
              {
279
                $(this).appendTo(targetSelector.children('ul'));
280
              }
281
              else
282
              {
283
                var htmlContent = '<div class=\"hitarea folder-hitarea collapsable-hitarea\"></div>'+ targetSelector.html() +'<ul style=\"display: block;\"></ul>';
284
                targetSelector.removeClass('file').addClass('folder collapsable').html(htmlContent);
285
                $(this).appendTo(targetSelector.children('ul'));
286
              }
287
            }
288
            else
289
              $(this).appendTo(tree);
290
291
            if( !parentSelector.children('ul').has('li').length )
292
            {
293
              parentSelector.removeClass('folder')
294
                .addClass('file')
295
                .html('<a href=\"'+ parentSelector.children('a').attr('href') +'\">' + parentSelector.children('a').html() + '</a>');
296
            }
297
          }
298
        });
299
      };
300
301
      initTreeDragAndDrop($('#' + treeId));
302
    ", CClientScript::POS_READY);
303
  }
304
}