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.

TbBulkActions::renderButtons()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 0
cts 14
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 0
crap 12
1
<?php
2
/**
3
 *## TbBulkActions class file
4
 *
5
 * @author Antonio Ramirez <[email protected]>
6
 * @copyright Copyright &copy; Clevertech 2012-
7
 * @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
8
 */
9
10
Yii::import('zii.widgets.grid.CCheckBoxColumn');
11
Yii::import('booster.widgets.TbButton');
12
13
/**
14
 * Bulk actions widget.
15
 *
16
 * @package booster.widgets.grids.columns
17
 */
18
class TbBulkActions extends CComponent {
19
	
20
    /**
21
     * @var TbGridView The grid view object that owns this column.
22
     */
23
    public $grid;
24
25
    /**
26
     * @var array the configuration for action displays.
27
     * Each array element specifies a single button
28
     * which has the following format:
29
     * <pre>
30
     * 'actions' => array(
31
     *      array(
32
     *          'context'=> 'primary', // '', 'primary', 'info', 'success', 'warning', 'danger' or 'inverse'
33
     *          'size'=> 'large', // '', 'large', 'small', 'mini'
34
     *          'label'=>'...',     // text label of the button or dropdown label
35
     *          'click'=> // the js function that will be called
36
     *      )
37
     * ),
38
     * </pre>
39
     * For more configuration options please @see TbButton
40
     *
41
     * Note that in order to display these additional buttons, the {@link template} property needs to
42
     * be configured so that the corresponding button IDs appear as tokens in the template.
43
     */
44
    public $actionButtons = array();
45
46
    /**
47
     * @var array the checkbox column configuration
48
     */
49
    public $checkBoxColumnConfig = array();
50
    
51
	/**
52
	 * @var string
53
	 */
54
    public $noCheckedMessage = 'No items are checked';
55
56
    /**
57
     * @var string
58
     */
59
    public $align = 'right';
60
61
    /**
62
     * @var integer the counter for generating implicit IDs.
63
     */
64
    private static $_counter = 0;
65
66
    /**
67
     * @var string id of the widget.
68
     */
69
    private $_id;
70
71
    /**
72
     *### .getId()
73
     *
74
     * Returns the ID of the widget or generates a new one if requested.
75
     *
76
     * @param boolean $autoGenerate whether to generate an ID if it is not set previously
77
     *
78
     * @return string id of the widget.
79
     */
80
    public function getId($autoGenerate = true) {
81
    	
82
        if ($this->_id !== null) {
83
            return $this->_id;
84
        } else if ($autoGenerate) {
85
            return $this->_id = 'egw' . self::$_counter++;
86
        } else {
87
	        return ''; // why getId can sometimes return nothing ? because it is used in the jquery selector, so null is not an acceptable value 
88
        }
89
    }
90
91
    /**
92
     * @var string the column name of the checkbox column
93
     */
94
    protected $columnName;
95
96
    /**
97
     * @var array the bulk action buttons
98
     */
99
    protected $buttons = array();
100
101
    /**
102
     * @var array the life events to attach the buttons to
103
     */
104
    protected $events = array();
105
106
    /**
107
     *### .__construct()
108
     *
109
     * Constructor.
110
     *
111
     * @param CGridView $grid the grid view that owns this column.
112
     */
113
    public function __construct($grid) {
114
    	
115
        $this->grid = $grid;
0 ignored issues
show
Documentation Bug introduced by
$grid is of type object<CGridView>, but the property $grid was declared to be of type object<TbGridView>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
116
    }
117
118
    /**
119
     *### .init()
120
     *
121
     * Component's initialization method
122
     */
123
    public function init() {
124
    	
125
        $this->align = $this->align == 'left' ? 'pull-left' : 'pull-right';
126
        $this->initColumn();
127
        $this->initButtons();
128
    }
129
130
    /**
131
     *### .initColumn()
132
     *
133
     * @return bool checks whether they are
134
     */
135
    public function initColumn() {
136
    	
137
        if (!is_array($this->checkBoxColumnConfig)) {
138
            $this->checkBoxColumnConfig = array();
139
        }
140
141
        if (empty($this->grid->columns)) {
142
            return false;
143
        }
144
145
        $columns = $this->grid->columns;
146
147
        foreach ($columns as $idx => $column) {
148
            if (!is_array($column) || !isset($column['class'])) {
149
                continue;
150
            }
151
            if (preg_match('/ccheckboxcolumn/i', $column['class'])) {
152
                if (isset($column['checkBoxHtmlOptions']) && isset($column['checkBoxHtmlOptions']['name'])) {
153
                    $this->columnName = strtr(
154
                        $column['checkBoxHtmlOptions']['name'],
155
                        array('[' => "\\[", ']' => "\\]")
156
                    );
157
                } else {
158
                    $this->columnName = $this->grid->id . '_c' . $idx . '\[\]';
159
                }
160
                return true; // it has already a CCheckBoxColumn
161
            }
162
        }
163
        // not CCheckBoxColumn, attach one
164
        $this->attachCheckBoxColumn();
165
        return true;
166
    }
167
168
    /**
169
     *### .initButtons()
170
     *
171
     * initializes the buttons to be render
172
     */
173
    public function initButtons() {
174
    	
175
        if (empty($this->columnName) || empty($this->actionButtons))
176
            return;
177
178
	    $this->buttons = array();
179
        foreach ($this->actionButtons as $action)
180
	        $this->buttons[] = $this->convertToTbButtonConfig($action);
181
    }
182
183
    /**
184
     *### .renderButtons()
185
     *
186
     * @return bool renders all initialized buttons
187
     */
188
    public function renderButtons() {
189
    	
190
        if ($this->buttons === array())
191
            return false;
192
193
        echo CHtml::openTag(
194
            'div',
195
            array('id' => $this->getId(), 'style' => 'position:relative', 'class' => $this->align)
196
        );
197
198
        foreach ($this->buttons as $actionButton)
199
            $this->renderButton($actionButton);
200
201
        echo '<div style="position:absolute;top:0;left:0;height:100%;width:100%;display:block;" class="bulk-actions-blocker"></div>';
202
203
        echo CHtml::closeTag('div');
204
205
        $this->registerClientScript();
206
	    return true;
207
    }
208
209
    /**
210
     *### .registerClientScript()
211
     *
212
     * Registers client script
213
     */
214
    public function registerClientScript() {
215
		$id = $this->grid->id;
216
        $js = '';
217
        $js .= "$.fn.yiiGridView.initBulkActions('{$id}');";
218
219
        foreach ($this->events as $buttonId => $handler) {
220
            $js .= "\n
221
            $(document).on('click','#{$buttonId}', function() {
222
	            var checked = $.fn.yiiGridView.getCheckedRowsIds('$id');
223
	            if (!checked.length) {
224
	                alert('".$this->noCheckedMessage."');
225
	                return false;
226
	            }
227
				var fn = $handler;
228
	            if ($.isFunction(fn)){ fn(checked); } \n
229
	            return false;
230
        	}); \n
231
            ";
232
        }
233
        Yii::app()->getClientScript()->registerScript(__CLASS__ . '#' . $this->getId(), $js);
234
    }
235
236
    /**
237
     *### .renderButton()
238
     *
239
     * Creates a TbButton and renders it
240
     *
241
     * @param array $actionButton the configuration to create the TbButton
242
     */
243
    protected function renderButton($actionButton) {
244
    	
245
    	if (isset($actionButton['htmlOptions']['class']))
246
            $actionButton['htmlOptions']['class'] .= ' disabled bulk-actions-btn';
247
        else
248
            $actionButton['htmlOptions']['class'] = 'disabled bulk-actions-btn';
249
        
250
        $action = null;
251
        if (isset($actionButton['click'])) {
252
            $action = CJavaScript::encode($actionButton['click']);
253
            unset($actionButton['click']);
254
        }
255
256
        $button = Yii::createComponent($actionButton);
257
        $button->init();
258
        echo '&nbsp;';
259
        $button->run();
260
        echo '&nbsp;';
261
        if ($action !== null) {
262
            $this->events[$button->id] = $action;
263
        }
264
    }
265
266
    /**
267
     *### .attachCheckBoxColumn()
268
     *
269
     * Adds a checkbox column to the grid. It is called when
270
     */
271
    protected function attachCheckBoxColumn() {
272
    	
273
        $dataProvider = $this->grid->dataProvider;
274
        $columnName = null;
275
276
        if (!isset($this->checkBoxColumnConfig['name'])) {
277
            // supports two types of DataProviders
278
            if ($dataProvider instanceof CActiveDataProvider) {
0 ignored issues
show
Bug introduced by
The class CActiveDataProvider does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
279
                // we need to get the name of the key field 'by default'
280
                if (is_string($dataProvider->modelClass)) {
281
                    $modelClass = $dataProvider->modelClass;
282
                    $model = CActiveRecord::model($modelClass);
283
                } else {
284
                    $model = $dataProvider->modelClass;
285
                }
286
287
                $table = $model->tableSchema;
288
                if (is_string($table->primaryKey)) {
289
                    $columnName = $this->{$table->primaryKey};
290
                } else if (is_array($table->primaryKey)) {
291
                    $columnName = $table->primaryKey[0];
292
                } // just get the first one
293
            }
294
            if ($dataProvider instanceof CArrayDataProvider || $dataProvider instanceof CSqlDataProvider) {
0 ignored issues
show
Bug introduced by
The class CArrayDataProvider does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Bug introduced by
The class CSqlDataProvider does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
295
                $columnName = $dataProvider->keyField;
296
            } // key Field
297
        }
298
        // create CCheckBoxColumn and attach to columns at its beginning
299
        $column = CMap::mergeArray(
300
            array(
301
                'class' => 'CCheckBoxColumn',
302
                'name' => $columnName,
303
            ),
304
            $this->checkBoxColumnConfig
305
        );
306
307
308
        array_unshift($this->grid->columns, $column);
309
        $this->columnName = $this->grid->id . '_c0\[\]'; //
310
    }
311
312
	/**
313
	 * @param $action
314
	 *
315
	 * @return array
316
	 * @throws CException
317
	 */
318
	private function convertToTbButtonConfig($action) {
319
		
320
		if (!isset($action['id'])) {
321
			throw new CException(Yii::t(
322
				'zii',
323
				'Each bulk action button should have its "id" attribute set to ensure its functionality among ajax updates'
324
			));
325
		}
326
		// button configuration is a regular TbButton
327
		$buttonConfig = array(
328
			'class' => 'booster.widgets.TbButton',
329
			'id' => $action['id'], // we must ensure this
330
			'buttonType' => isset($action['buttonType']) ? $action['buttonType'] : TbButton::BUTTON_LINK,
331
			'context' => isset($action['context']) ? $action['context'] : '',
332
			'size' => isset($action['size']) ? $action['size'] : TbButton::SIZE_SMALL,
333
			'icon' => isset($action['icon']) ? $action['icon'] : null,
334
			'label' => isset($action['label']) ? $action['label'] : null,
335
			'url' => isset($action['url']) ? $action['url'] : null,
336
			'active' => isset($action['active']) ? $action['active'] : false,
337
			'items' => isset($action['items']) ? $action['items'] : array(),
338
			'ajaxOptions' => isset($action['ajaxOptions']) ? $action['ajaxOptions'] : array(),
339
			'htmlOptions' => isset($action['htmlOptions']) ? $action['htmlOptions'] : array(),
340
			'encodeLabel' => isset($action['encodeLabel']) ? $action['encodeLabel'] : true,
341
			'click' => isset($action['click']) ? $action['click'] : false
342
		);
343
		return $buttonConfig;
344
	}
345
}
346