Completed
Push — master ( aa1d0c...064b6c )
by Jean-Christophe
04:19
created

DataTable::getFieldButtonCallable()   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 2
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\table\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\base\constants\Direction;
13
use Ajax\service\JArray;
14
use Ajax\semantic\html\base\HtmlSemDoubleElement;
15
use Ajax\semantic\widgets\base\InstanceViewer;
16
use Ajax\semantic\html\collections\table\traits\TableTrait;
17
18
/**
19
 * DataTable widget for displaying list of objects
20
 * @version 1.0
21
 * @author jc
22
 * @since 2.2
23
 *
24
 */
25
class DataTable extends Widget {
26
	use TableTrait;
27
	protected $_searchField;
28
	protected $_urls;
29
	protected $_pagination;
30
	protected $_hasCheckboxes;
31
	protected $_compileParts;
32
33
	public function run(JsUtils $js){
34
		if($this->_hasCheckboxes && isset($js)){
35
			$js->execOn("change", "#".$this->identifier." [name='selection[]']", "
36
		var \$parentCheckbox=\$('#ck-main-ck-{$this->identifier}'),\$checkbox=\$('#{$this->identifier} [name=\"selection[]\"]'),allChecked=true,allUnchecked=true;
37
		\$checkbox.each(function() {if($(this).prop('checked')){allUnchecked = false;}else{allChecked = false;}});
38
		if(allChecked) {\$parentCheckbox.checkbox('set checked');}else if(allUnchecked){\$parentCheckbox.checkbox('set unchecked');}else{\$parentCheckbox.checkbox('set indeterminate');}");
39
		}
40
		parent::run($js);
41
	}
42
43 View Code Duplication
	public function __construct($identifier,$model,$modelInstance=NULL) {
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...
44
		parent::__construct($identifier, $model,$modelInstance);
45
		$this->_instanceViewer=new InstanceViewer($identifier);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Ajax\semantic\widge...anceViewer($identifier) of type object<Ajax\semantic\widgets\base\InstanceViewer> is incompatible with the declared type object<Ajax\common\InstanceViewer> of property $_instanceViewer.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
46
		$this->content=["table"=>new HtmlTable($identifier, 0,0)];
47
		$this->_toolbarPosition=PositionInTable::BEFORETABLE;
48
	}
49
50
	/**
51
	 * {@inheritDoc}
52
	 * @see \Ajax\semantic\html\collections\table\TableTrait::getTable()
53
	 */
54
	protected function getTable() {
55
		return $this->content["table"];
56
	}
57
58
59
	public function compile(JsUtils $js=NULL,&$view=NULL){
60
		$this->_instanceViewer->setInstance($this->_model);
61
		$captions=$this->_instanceViewer->getCaptions();
62
63
		$table=$this->content["table"];
64
65
		if($this->_hasCheckboxes){
66
			$ck=new HtmlCheckbox("main-ck-".$this->identifier,"");
67
			$ck->setOnChecked("$('#".$this->identifier." [name=%quote%selection[]%quote%]').prop('checked',true);");
68
			$ck->setOnUnchecked("$('#".$this->identifier." [name=%quote%selection[]%quote%]').prop('checked',false);");
69
			\array_unshift($captions, $ck);
70
		}
71
72
		$table->setRowCount(0, \sizeof($captions));
73
		$table->setHeaderValues($captions);
74
		if(isset($this->_compileParts))
75
			$table->setCompileParts($this->_compileParts);
76
		if(isset($this->_searchField)){
77
			if(isset($js))
78
				$this->_searchField->postOn("change", $this->_urls,"{'s':$(this).val()}","-#".$this->identifier." tbody",["preventDefault"=>false]);
79
		}
80
81
		$this->_generateContent($table);
82
83
		if($this->_hasCheckboxes){
84
			if($table->hasPart("thead"))
85
				$table->getHeader()->getCell(0, 0)->addToProperty("class","no-sort");
86
		}
87
88
		if(isset($this->_pagination) && $this->_pagination->getVisible()){
89
			$this->_generatePagination($table);
90
		}
91
		if(isset($this->_toolbar)){
92
			$this->_setToolbarPosition($table, $captions);
93
		}
94
		$this->content=JArray::sortAssociative($this->content, [PositionInTable::BEFORETABLE,"table",PositionInTable::AFTERTABLE]);
95
		return parent::compile($js,$view);
96
	}
97
98
	protected function _generateContent($table){
99
		$objects=$this->_modelInstance;
100
		if(isset($this->_pagination)){
101
			$objects=$this->_pagination->getObjects($this->_modelInstance);
102
		}
103
		InstanceViewer::setIndex(0);
104
		$table->fromDatabaseObjects($objects, function($instance){
105
			$this->_instanceViewer->setInstance($instance);
106
			InstanceViewer::$index++;
107
			$result= $this->_instanceViewer->getValues();
108
			if($this->_hasCheckboxes){
109
				$ck=new HtmlCheckbox("ck-".$this->identifier,"");
110
				$field=$ck->getField();
111
				$field->setProperty("value",$this->_instanceViewer->getIdentifier());
112
				$field->setProperty("name", "selection[]");
113
				\array_unshift($result, $ck);
114
			}
115
			return $result;
116
		});
117
	}
118
119
	private function _generatePagination($table){
120
		$footer=$table->getFooter();
121
		$footer->mergeCol();
122
		$menu=new HtmlPaginationMenu("pagination-".$this->identifier,$this->_pagination->getPagesNumbers());
123
		$menu->floatRight();
124
		$menu->setActiveItem($this->_pagination->getPage()-1);
125
		$footer->setValues($menu);
126
		$menu->postOnClick($this->_urls,"{'p':$(this).attr('data-page')}","-#".$this->identifier." tbody",["preventDefault"=>false]);
127
	}
128
129
	protected function _setToolbarPosition($table,$captions=NULL){
130
		switch ($this->_toolbarPosition){
131
			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...
132
				if(isset($this->_compileParts)===false){
133
					$this->content[$this->_toolbarPosition]=$this->_toolbar;
134
				}
135
				break;
136
			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...
137
				$this->addToolbarRow($this->_toolbarPosition,$table, $captions);
138
				break;
139
		}
140
	}
141
142
	/**
143
	 * Associates a $callback function after the compilation of the field at $index position
144
	 * The $callback function can take the following arguments : $field=>the compiled field, $instance : the active instance of the object, $index: the field position
145
	 * @param int $index postion of the compiled field
146
	 * @param callable $callback function called after the field compilation
147
	 * @return \Ajax\semantic\widgets\datatable\DataTable
148
	 */
149
	public function afterCompile($index,$callback){
150
		$this->_instanceViewer->afterCompile($index,$callback);
151
		return $this;
152
	}
153
154
	private function addToolbarRow($part,$table,$captions){
155
		$row=$table->getPart($part)->addRow(\sizeof($captions));
156
		$row->mergeCol();
157
		$row->setValues([$this->_toolbar]);
158
	}
159
160
	public function getHtmlComponent(){
161
		return $this->content["table"];
162
	}
163
164
	public function getUrls() {
165
		return $this->_urls;
166
	}
167
168
	public function setUrls($urls) {
169
		$this->_urls=$urls;
170
		return $this;
171
	}
172
173
	public function paginate($items_per_page=10,$page=1){
174
		$this->_pagination=new Pagination($items_per_page,4,$page);
175
	}
176
177
	public function getHasCheckboxes() {
178
		return $this->_hasCheckboxes;
179
	}
180
181
	public function setHasCheckboxes($_hasCheckboxes) {
182
		$this->_hasCheckboxes=$_hasCheckboxes;
183
		return $this;
184
	}
185
186
	public function refresh($compileParts=["tbody"]){
187
		$this->_compileParts=$compileParts;
188
		return $this;
189
	}
190
	/**
191
	 * @param string $caption
192
	 * @param callable $callback
193
	 * @return callable
194
	 */
195
	private function getFieldButtonCallable($caption,$callback=null){
196
		return $this->getCallable("getFieldButton",[$caption],$callback);
197
	}
198
199
	/**
200
	 * @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...
201
	 * @param callable $callback
202
	 * @return callable
203
	 */
204
	private function getCallable($thisCallback,$parameters,$callback=null){
205
		$result=function($instance) use($thisCallback,$parameters,$callback){
206
			$object=call_user_func_array(array($this,$thisCallback), $parameters);
207
			if(isset($callback)){
208
				if(\is_callable($callback)){
209
					$callback($object,$instance);
210
				}
211
			}
212
			if($object instanceof HtmlSemDoubleElement){
213
				$object->setProperty("data-ajax",$this->_instanceViewer->getIdentifier());
214
			}
215
			return $object;
216
		};
217
		return $result;
218
	}
219
220
	/**
221
	 * @param string $caption
222
	 * @return HtmlButton
223
	 */
224
	private function getFieldButton($caption){
225
		return new HtmlButton("",$caption);
226
	}
227
228
	/**
229
	 * Inserts a new Button for each row
230
	 * @param string $caption
231
	 * @param callable $callback
232
	 * @return \Ajax\semantic\widgets\datatable\DataTable
233
	 */
234
	public function addFieldButton($caption,$callback=null){
235
		$this->addField($this->getCallable("getFieldButton",[$caption],$callback));
236
		return $this;
237
	}
238
239
	/**
240
	 * Inserts a new Button for each row at col $index
241
	 * @param int $index
242
	 * @param string $caption
243
	 * @param callable $callback
244
	 * @return \Ajax\semantic\widgets\datatable\DataTable
245
	 */
246
	public function insertFieldButton($index,$caption,$callback=null){
247
		$this->insertField($index, $this->getFieldButtonCallable($caption,$callback));
248
		return $this;
249
	}
250
251
	/**
252
	 * Inserts a new Button for each row in col at $index
253
	 * @param int $index
254
	 * @param string $caption
255
	 * @param callable $callback
256
	 * @return \Ajax\semantic\widgets\datatable\DataTable
257
	 */
258
	public function insertInFieldButton($index,$caption,$callback=null){
259
		$this->insertInField($index, $this->getFieldButtonCallable($caption,$callback));
260
		return $this;
261
	}
262
263
	private function addDefaultButton($icon,$class=null,$callback=null){
264
		$this->addField($this->getCallable("getDefaultButton",[$icon,$class],$callback));
265
		return $this;
266
	}
267
268
	private function insertDefaultButtonIn($index,$icon,$class=null,$callback=null){
269
		$this->insertInField($index,$this->getCallable("getDefaultButton",[$icon,$class],$callback));
270
		return $this;
271
	}
272
273
	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...
274
		$bt=$this->getFieldButton("");
275
		$bt->asIcon($icon);
276
		if(isset($class))
277
			$bt->addToProperty("class", $class);
278
		return $bt;
279
	}
280
281
	public function addDeleteButton($callback=null){
282
		return $this->addDefaultButton("remove","delete red basic",$callback);
283
	}
284
285
	public function addEditButton($callback=null){
286
		return $this->addDefaultButton("edit","edit basic",$callback);
287
	}
288
289
	public function addEditDeleteButtons($callbackEdit=null,$callbackDelete=null){
290
		$this->addEditButton($callbackEdit);
291
		$index=$this->_instanceViewer->visiblePropertiesCount()-1;
292
		$this->insertDeleteButtonIn($index,$callbackDelete);
293
		return $this;
294
	}
295
296
	public function insertDeleteButtonIn($index,$callback=null){
297
		return $this->insertDefaultButtonIn($index,"remove","delete red basic",$callback);
298
	}
299
300
	public function insertEditButtonIn($index,$callback=null){
301
		return $this->insertDefaultButtonIn($index,"edit","edit basic",$callback);
302
	}
303
304
	public function addSearchInToolbar($position=Direction::RIGHT){
305
		return $this->addInToolbar($this->getSearchField())->setPosition($position);
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...
306
	}
307
308
	public function getSearchField(){
309
		if(isset($this->_searchField)===false){
310
			$this->_searchField=new HtmlInput("search-".$this->identifier,"search","","Search...");
311
			$this->_searchField->addIcon("search",Direction::RIGHT);
312
		}
313
		return $this->_searchField;
314
	}
315
316
	/**
317
	 * The callback function called after the insertion of each row when fromDatabaseObjects is called
318
	 * callback function takes the parameters $row : the row inserted and $object: the instance of model used
319
	 * @param callable $callback
320
	 * @return DataTable
321
	 */
322
	public function onNewRow($callback) {
323
		$this->content["table"]->onNewRow($callback);
324
		return $this;
325
	}
326
}