Completed
Push — master ( e0aff5...5f2e51 )
by Jean-Christophe
09:49
created

DataTable::_getFieldIdentifier()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Ajax\semantic\widgets\datatable;
4
5
use Ajax\common\Widget;
6
use Ajax\JsUtils;
7
use Ajax\semantic\html\collections\HtmlTable;
8
use Ajax\semantic\html\elements\HtmlInput;
9
use Ajax\semantic\html\collections\menus\HtmlPaginationMenu;
10
use Ajax\semantic\html\modules\checkbox\HtmlCheckbox;
11
use Ajax\semantic\html\elements\HtmlButton;
12
use Ajax\semantic\html\collections\menus\HtmlMenu;
13
use Ajax\semantic\html\base\constants\Direction;
14
use Ajax\service\JArray;
15
use Ajax\semantic\widgets\base\FieldAsTrait;
16
use Ajax\semantic\html\base\HtmlSemDoubleElement;
17
18
/**
19
 * DataTable widget for displaying list of objects
20
 * @author jc
21
 *
22
 */
23
class DataTable extends Widget {
24
	use FieldAsTrait;
25
26
	protected $_searchField;
27
	protected $_urls;
28
	protected $_pagination;
29
	protected $_hasCheckboxes;
30
	protected $_toolbar;
31
	protected $_compileParts;
32
	protected $_toolbarPosition;
33
34
	public function run(JsUtils $js){
35
		if($this->_hasCheckboxes && isset($js)){
36
			$js->execOn("change", "#".$this->identifier." [name='selection[]']", "
37
		var \$parentCheckbox=\$('#ck-main-ck-{$this->identifier}'),\$checkbox=\$('#{$this->identifier} [name=\"selection[]\"]'),allChecked=true,allUnchecked=true;
38
		\$checkbox.each(function() {if($(this).prop('checked')){allUnchecked = false;}else{allChecked = false;}});
39
		if(allChecked) {\$parentCheckbox.checkbox('set checked');}else if(allUnchecked){\$parentCheckbox.checkbox('set unchecked');}else{\$parentCheckbox.checkbox('set indeterminate');}");
40
		}
41
		parent::run($js);
42
	}
43
44
	public function __construct($identifier,$model,$modelInstance=NULL) {
45
		parent::__construct($identifier, $model,$modelInstance);
46
		$this->_instanceViewer=new InstanceViewer();
47
		$this->content=["table"=>new HtmlTable($identifier, 0,0)];
48
		$this->_toolbarPosition=PositionInTable::BEFORETABLE;
49
	}
50
51
	public function compile(JsUtils $js=NULL,&$view=NULL){
52
		$this->_instanceViewer->setInstance($this->_model);
53
		$captions=$this->_instanceViewer->getCaptions();
54
55
		$table=$this->content["table"];
56
57
		if($this->_hasCheckboxes){
58
			$ck=new HtmlCheckbox("main-ck-".$this->identifier,"");
59
			$ck->setOnChecked("$('#".$this->identifier." [name=%quote%selection[]%quote%]').prop('checked',true);");
60
			$ck->setOnUnchecked("$('#".$this->identifier." [name=%quote%selection[]%quote%]').prop('checked',false);");
61
			\array_unshift($captions, $ck);
62
		}
63
64
		$table->setRowCount(0, \sizeof($captions));
65
		$table->setHeaderValues($captions);
66
		if(isset($this->_compileParts))
67
			$table->setCompileParts($this->_compileParts);
68
		if(isset($this->_searchField)){
69
			if(isset($js))
70
				$this->_searchField->postOn("change", $this->_urls,"{'s':$(this).val()}","-#".$this->identifier." tbody",["preventDefault"=>false]);
71
		}
72
73
		$this->_generateContent($table);
74
75
		if($this->_hasCheckboxes){
76
			if($table->hasPart("thead"))
77
				$table->getHeader()->getCell(0, 0)->addToProperty("class","no-sort");
78
		}
79
80
		if(isset($this->_pagination) && $this->_pagination->getVisible()){
81
			$this->_generatePagination($table);
82
		}
83
		if(isset($this->_toolbar)){
84
			$this->_setToolbarPosition($table, $captions);
85
		}
86
		$this->content=JArray::sortAssociative($this->content, [PositionInTable::BEFORETABLE,"table",PositionInTable::AFTERTABLE]);
87
		return parent::compile($js,$view);
88
	}
89
90
	private function _generateContent($table){
91
		$objects=$this->_modelInstance;
92
		if(isset($this->_pagination)){
93
			$objects=$this->_pagination->getObjects($this->_modelInstance);
94
		}
95
		InstanceViewer::setIndex(0);
96
		$table->fromDatabaseObjects($objects, function($instance){
97
			$this->_instanceViewer->setInstance($instance);
98
			InstanceViewer::$index++;
99
			$result= $this->_instanceViewer->getValues();
100
			if($this->_hasCheckboxes){
101
				$ck=new HtmlCheckbox("ck-".$this->identifier,"");
102
				$field=$ck->getField();
103
				$field->setProperty("value",$this->_instanceViewer->getIdentifier());
104
				$field->setProperty("name", "selection[]");
105
				\array_unshift($result, $ck);
106
			}
107
			return $result;
108
		});
109
	}
110
111
	private function _generatePagination($table){
112
		$footer=$table->getFooter();
113
		$footer->mergeCol();
114
		$menu=new HtmlPaginationMenu("pagination-".$this->identifier,$this->_pagination->getPagesNumbers());
115
		$menu->floatRight();
116
		$menu->setActiveItem($this->_pagination->getPage()-1);
117
		$footer->setValues($menu);
118
		$menu->postOnClick($this->_urls,"{'p':$(this).attr('data-page')}","-#".$this->identifier." tbody",["preventDefault"=>false]);
119
	}
120
121
	private function _setToolbarPosition($table,$captions){
122
		switch ($this->_toolbarPosition){
123
			case PositionInTable::BEFORETABLE:case PositionInTable::AFTERTABLE:
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
124
				if(isset($this->_compileParts)===false){
125
					$this->content[$this->_toolbarPosition]=$this->_toolbar;
126
				}
127
				break;
128
			case PositionInTable::HEADER:case PositionInTable::FOOTER: case PositionInTable::BODY:
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
129
				$this->addToolbarRow($this->_toolbarPosition,$table, $captions);
130
				break;
131
		}
132
	}
133
134
	/**
135
	 * Associates a $callback function after the compilation of the field at $index position
136
	 * The $callback function can take the following arguments : $field=>the compiled field, $instance : the active instance of the object, $index: the field position
137
	 * @param int $index postion of the compiled field
138
	 * @param callable $callback function called after the field compilation
139
	 * @return \Ajax\semantic\widgets\datatable\DataTable
140
	 */
141
	public function afterCompile($index,$callback){
142
		$this->_instanceViewer->afterCompile($index,$callback);
143
		return $this;
144
	}
145
146
	private function addToolbarRow($part,$table,$captions){
147
		$row=$table->getPart($part)->addRow(\sizeof($captions));
148
		$row->mergeCol();
149
		$row->setValues([$this->_toolbar]);
150
	}
151
152
	public function getInstanceViewer() {
153
		return $this->_instanceViewer;
154
	}
155
156
	public function setInstanceViewer($_instanceViewer) {
157
		$this->_instanceViewer=$_instanceViewer;
158
		return $this;
159
	}
160
161
	public function setCaptions($captions){
162
		$this->_instanceViewer->setCaptions($captions);
163
		return $this;
164
	}
165
166
	public function setFields($fields){
167
		$this->_instanceViewer->setVisibleProperties($fields);
168
		return $this;
169
	}
170
171
	public function addField($field){
172
		$this->_instanceViewer->addField($field);
173
		return $this;
174
	}
175
176
	public function insertField($index,$field){
177
		$this->_instanceViewer->insertField($index, $field);
178
		return $this;
179
	}
180
181
	public function insertInField($index,$field){
182
		$this->_instanceViewer->insertInField($index, $field);
183
		return $this;
184
	}
185
186
	public function setValueFunction($index,$callback){
187
		$this->_instanceViewer->setValueFunction($index, $callback);
188
		return $this;
189
	}
190
191
	public function setIdentifierFunction($callback){
192
		$this->_instanceViewer->setIdentifierFunction($callback);
193
		return $this;
194
	}
195
196
	public function getHtmlComponent(){
197
		return $this->content["table"];
198
	}
199
200
	public function getUrls() {
201
		return $this->_urls;
202
	}
203
204
	public function setUrls($urls) {
205
		$this->_urls=$urls;
206
		return $this;
207
	}
208
209
	public function paginate($items_per_page=10,$page=1){
210
		$this->_pagination=new Pagination($items_per_page,4,$page);
211
	}
212
213
	public function getHasCheckboxes() {
214
		return $this->_hasCheckboxes;
215
	}
216
217
	public function setHasCheckboxes($_hasCheckboxes) {
218
		$this->_hasCheckboxes=$_hasCheckboxes;
219
		return $this;
220
	}
221
222
	public function refresh($compileParts=["tbody"]){
223
		$this->_compileParts=$compileParts;
224
		return $this;
225
	}
226
	/**
227
	 * @param string $caption
228
	 * @param callable $callback
229
	 * @return callable
230
	 */
231
	private function getFieldButtonCallable($caption,$callback=null){
232
		return $this->getCallable("getFieldButton",[$caption],$callback);
233
	}
234
235
	/**
236
	 * @param mixed $object
0 ignored issues
show
Bug introduced by
There is no parameter named $object. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
237
	 * @param callable $callback
238
	 * @return callable
239
	 */
240
	private function getCallable($thisCallback,$parameters,$callback=null){
241
		$result=function($instance) use($thisCallback,$parameters,$callback){
242
			$object=call_user_func_array(array($this,$thisCallback), $parameters);
243
			if(isset($callback)){
244
				if(\is_callable($callback)){
245
					$callback($object,$instance);
246
				}
247
			}
248
			if($object instanceof HtmlSemDoubleElement){
249
				$object->setProperty("data-ajax",$this->_instanceViewer->getIdentifier());
250
			}
251
			return $object;
252
		};
253
		return $result;
254
	}
255
256
	/**
257
	 * @param string $caption
258
	 * @return HtmlButton
259
	 */
260
	private function getFieldButton($caption){
261
		return new HtmlButton("",$caption);
262
	}
263
264
	/**
265
	 * Inserts a new Button for each row
266
	 * @param string $caption
267
	 * @param callable $callback
268
	 * @return \Ajax\semantic\widgets\datatable\DataTable
269
	 */
270
	public function addFieldButton($caption,$callback=null){
271
		$this->addField($this->getCallable("getFieldButton",[$caption],$callback));
272
		return $this;
273
	}
274
275
	/**
276
	 * Inserts a new Button for each row at col $index
277
	 * @param int $index
278
	 * @param string $caption
279
	 * @param callable $callback
280
	 * @return \Ajax\semantic\widgets\datatable\DataTable
281
	 */
282
	public function insertFieldButton($index,$caption,$callback=null){
283
		$this->insertField($index, $this->getFieldButtonCallable($caption,$callback));
284
		return $this;
285
	}
286
287
	/**
288
	 * Inserts a new Button for each row in col at $index
289
	 * @param int $index
290
	 * @param string $caption
291
	 * @param callable $callback
292
	 * @return \Ajax\semantic\widgets\datatable\DataTable
293
	 */
294
	public function insertInFieldButton($index,$caption,$callback=null){
295
		$this->insertInField($index, $this->getFieldButtonCallable($caption,$callback));
296
		return $this;
297
	}
298
299
	private function addDefaultButton($icon,$class=null,$callback=null){
300
		$this->addField($this->getCallable("getDefaultButton",[$icon,$class],$callback));
301
		return $this;
302
	}
303
304
	private function insertDefaultButtonIn($index,$icon,$class=null,$callback=null){
305
		$this->insertInField($index,$this->getCallable("getDefaultButton",[$icon,$class],$callback));
306
		return $this;
307
	}
308
309
	private function getDefaultButton($icon,$class=null){
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
310
		$bt=$this->getFieldButton("");
311
		$bt->asIcon($icon);
312
		if(isset($class))
313
			$bt->addToProperty("class", $class);
314
		return $bt;
315
	}
316
317
	public function addDeleteButton($callback=null){
318
		return $this->addDefaultButton("remove","delete red basic",$callback);
319
	}
320
321
	public function addEditButton($callback=null){
322
		return $this->addDefaultButton("edit","edit basic",$callback);
323
	}
324
325
	public function addEditDeleteButtons($callbackEdit=null,$callbackDelete=null){
326
		$this->addEditButton($callbackEdit);
327
		$index=$this->_instanceViewer->visiblePropertiesCount()-1;
328
		$this->insertDeleteButtonIn($index,$callbackDelete);
329
		return $this;
330
	}
331
332
	public function insertDeleteButtonIn($index,$callback=null){
333
		return $this->insertDefaultButtonIn($index,"remove","delete red basic",$callback);
334
	}
335
336
	public function insertEditButtonIn($index,$callback=null){
337
		return $this->insertDefaultButtonIn($index,"edit","edit basic",$callback);
338
	}
339
340
	public function setSelectable(){
341
		$this->content["table"]->setSelectable();
342
		return $this;
343
	}
344
345
	/**
346
	 * @return \Ajax\semantic\html\collections\menus\HtmlMenu
347
	 */
348
	public function getToolbar(){
349
		if(isset($this->_toolbar)===false){
350
			$this->_toolbar=new HtmlMenu("toolbar-".$this->identifier);
351
			$this->_toolbar->setSecondary();
352
		}
353
		return $this->_toolbar;
354
	}
355
356
	/**
357
	 * Adds a new element in toolbar
358
	 * @param mixed $element
359
	 * @return \Ajax\common\html\HtmlDoubleElement
360
	 */
361
	public function addInToolbar($element){
362
		$tb=$this->getToolbar();
363
		return $tb->addItem($element);
364
	}
365
366
	public function addItemInToolbar($caption,$icon=NULL){
367
		$result=$this->addInToolbar($caption);
368
		$result->addIcon($icon);
369
		return $result;
370
	}
371
372
	public function addButtonInToolbar($caption){
373
		$bt=new HtmlButton("",$caption);
374
		return $this->addInToolbar($bt);
375
	}
376
377
	public function addLabelledIconButtonInToolbar($caption,$icon,$before=true,$labeled=false){
378
		$bt=new HtmlButton("",$caption);
379
		$bt->addIcon($icon,$before,$labeled);
380
		return $this->addInToolbar($bt);
381
	}
382
383
384
	public function addSearchInToolbar(){
385
		return $this->addInToolbar($this->getSearchField())->setPosition("right");
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Ajax\common\html\HtmlDoubleElement as the method setPosition() does only exist in the following sub-classes of Ajax\common\html\HtmlDoubleElement: Ajax\bootstrap\html\content\HtmlGridCol, Ajax\semantic\html\colle...menus\HtmlAccordionMenu, Ajax\semantic\html\collections\menus\HtmlIconMenu, Ajax\semantic\html\colle...nus\HtmlLabeledIconMenu, Ajax\semantic\html\collections\menus\HtmlMenu, Ajax\semantic\html\colle...enus\HtmlPaginationMenu, Ajax\semantic\html\content\HtmlAccordionMenuItem, Ajax\semantic\html\content\HtmlDropdownItem, Ajax\semantic\html\content\HtmlMenuItem, Ajax\semantic\html\modules\HtmlPopup. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
386
	}
387
388
	public function getSearchField(){
389
		if(isset($this->_searchField)===false){
390
			$this->_searchField=new HtmlInput("search-".$this->identifier,"search","","Search...");
391
			$this->_searchField->addIcon("search",Direction::RIGHT);
392
		}
393
		return $this->_searchField;
394
	}
395
396
	public function setSortable($colIndex=NULL) {
397
		$this->content["table"]->setSortable($colIndex);
398
		return $this;
399
	}
400
401
	protected function _getFieldIdentifier($prefix){
402
		return $this->identifier."-{$prefix}-".$this->_instanceViewer->getIdentifier();
403
	}
404
405
	/**
406
	 * The callback function called after the insertion of each row when fromDatabaseObjects is called
407
	 * callback function takes the parameters $row : the row inserted and $object: the instance of model used
408
	 * @param callable $callback
409
	 * @return DataTable
410
	 */
411
	public function onNewRow($callback) {
412
		$this->content["table"]->onNewRow($callback);
413
		return $this;
414
	}
415
}