Completed
Push — master ( 80e027...da7bd7 )
by Jean-Christophe
04:34
created

DataTable::_getFieldName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
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\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\base\constants\Direction;
12
use Ajax\service\JArray;
13
use Ajax\semantic\widgets\base\InstanceViewer;
14
use Ajax\semantic\html\collections\table\traits\TableTrait;
15
use Ajax\semantic\html\collections\HtmlMessage;
16
use Ajax\semantic\html\collections\menus\HtmlMenu;
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,DataTableFieldAsTrait,HasCheckboxesTrait;
27
	protected $_searchField;
28
	protected $_urls;
29
	protected $_pagination;
30
	protected $_compileParts;
31
	protected $_deleteBehavior;
32
	protected $_editBehavior;
33
	protected $_visibleHover=false;
34
	protected $_targetSelector;
35
	protected $_refreshSelector;
36
	protected $_emptyMessage;
37
	protected $_json;
38
	protected $_rowClass="";
39
	protected $_sortable;
40
41
42
	public function __construct($identifier,$model,$modelInstance=NULL) {
43
		parent::__construct($identifier, $model,$modelInstance);
44
		$this->_init(new InstanceViewer($identifier), "table", new HtmlTable($identifier, 0,0), false);
45
		$this->_urls=[];
46
		$this->_emptyMessage=new HtmlMessage("","nothing to display");
47
		$this->_emptyMessage->setIcon("info circle");
48
	}
49
50
	public function run(JsUtils $js){
51
		if($this->_hasCheckboxes && isset($js)){
52
			$this->_runCheckboxes($js);
53
		}
54
		if($this->_visibleHover){
55
			$js->execOn("mouseover", "#".$this->identifier." tr", "$(event.target).closest('tr').find('.visibleover').css('visibility', 'visible');",["preventDefault"=>false,"stopPropagation"=>true]);
56
			$js->execOn("mouseout", "#".$this->identifier." tr", "$(event.target).closest('tr').find('.visibleover').css('visibility', 'hidden');",["preventDefault"=>false,"stopPropagation"=>true]);
57
		}
58
		if(\is_array($this->_deleteBehavior))
59
			$this->_generateBehavior("delete",$this->_deleteBehavior, $js);
60
		if(\is_array($this->_editBehavior))
61
			$this->_generateBehavior("edit",$this->_editBehavior,$js);
62
		return parent::run($js);
63
	}
64
65
66
67
	protected function _generateBehavior($op,$params,JsUtils $js){
68
		if(isset($this->_urls[$op])){
69
			$params=\array_merge($params,["attr"=>"data-ajax"]);
70
			$js->getOnClick("#".$this->identifier." ._".$op, $this->_urls[$op],$this->getTargetSelector(),$params);
71
		}
72
	}
73
74
	/**
75
	 * {@inheritDoc}
76
	 * @see \Ajax\semantic\html\collections\table\TableTrait::getTable()
77
	 */
78
	protected function getTable() {
79
		return $this->content["table"];
80
	}
81
82
83
	public function compile(JsUtils $js=NULL,&$view=NULL){
84
		if(!$this->_generated){
85
			$this->_instanceViewer->setInstance($this->_model);
86
			$captions=$this->_instanceViewer->getCaptions();
87
88
			$table=$this->content["table"];
89
90
			if($this->_hasCheckboxes){
91
				$this->_generateMainCheckbox($captions);
92
			}
93
94
			$table->setRowCount(0, \sizeof($captions));
95
			$this->_generateHeader($table,$captions);
96
97
			if(isset($this->_compileParts))
98
				$table->setCompileParts($this->_compileParts);
99
100
			if(isset($this->_searchField) && isset($js)){
101
				if(isset($this->_urls["refresh"]))
102
					$this->_searchField->postOn("change", $this->_urls["refresh"],"{'s':$(this).val()}","#".$this->identifier." tbody",["preventDefault"=>false,"jqueryDone"=>"replaceWith"]);
103
			}
104
105
			$this->_generateContent($table);
106
107
			if($this->_hasCheckboxes && $table->hasPart("thead")){
108
					$table->getHeader()->getCell(0, 0)->addClass("no-sort");
109
			}
110
111
			if(isset($this->_toolbar)){
112
				$this->_setToolbarPosition($table, $captions);
113
			}
114
			if(isset($this->_pagination) && $this->_pagination->getVisible()){
115
				$this->_generatePagination($table,$js);
116
			}
117
118
			$this->content=JArray::sortAssociative($this->content, [PositionInTable::BEFORETABLE,"table",PositionInTable::AFTERTABLE]);
119
			$this->_compileForm();
120
121
			$this->_generated=true;
122
		}
123
		return parent::compile($js,$view);
124
	}
125
126
	protected function _generateHeader(HtmlTable $table,$captions){
127
		$table->setHeaderValues($captions);
128
		if(isset($this->_sortable)){
129
			$table->setSortable($this->_sortable);
130
		}
131
	}
132
133
134
135
	protected function _generateContent($table){
136
		$objects=$this->_modelInstance;
137
		if(isset($this->_pagination)){
138
			$objects=$this->_pagination->getObjects($this->_modelInstance);
139
		}
140
			InstanceViewer::setIndex(0);
141
			$table->fromDatabaseObjects($objects, function($instance) use($table){
142
				return $this->_generateRow($instance, $table);
143
			});
144
		if($table->getRowCount()==0){
145
			$result=$table->addRow();
146
			$result->mergeRow();
147
			$result->setValues([$this->_emptyMessage]);
148
		}
149
	}
150
151
	protected function _generateRow($instance,&$table,$checkedClass=null){
152
		$this->_instanceViewer->setInstance($instance);
153
		InstanceViewer::$index++;
154
		$values= $this->_instanceViewer->getValues();
155
		if($this->_hasCheckboxes){
156
			$ck=new HtmlCheckbox("ck-".$this->identifier,"");
157
			$field=$ck->getField();
158
			$field->setProperty("value",$this->_instanceViewer->getIdentifier());
159
			$field->setProperty("name", "selection[]");
160
			if(isset($checkedClass))
161
				$field->setClass($checkedClass);
162
			\array_unshift($values, $ck);
163
		}
164
		$result=$table->newRow();
165
		$result->setIdentifier($this->identifier."-tr-".$this->_instanceViewer->getIdentifier());
166
		$result->setValues($values);
167
		$result->addToProperty("class",$this->_rowClass);
168
		return $result;
169
	}
170
171
	protected function _generatePagination($table,$js=NULL){
172
		if(isset($this->_toolbar)){
173
			if($this->_toolbarPosition==PositionInTable::FOOTER)
174
				$this->_toolbar->setFloated("left");
175
		}
176
		$footer=$table->getFooter();
177
		$footer->mergeCol();
178
		$menu=new HtmlPaginationMenu("pagination-".$this->identifier,$this->_pagination->getPagesNumbers());
179
		$menu->floatRight();
180
		$menu->setActiveItem($this->_pagination->getPage()-1);
181
		$footer->addValues($menu);
182
		$this->_associatePaginationBehavior($menu,$js);
183
	}
184
185
	protected function _associatePaginationBehavior(HtmlMenu $menu,JsUtils $js=NULL){
186
		if(isset($this->_urls["refresh"])){
187
			$menu->postOnClick($this->_urls["refresh"],"{'p':$(this).attr('data-page')}",$this->getRefreshSelector(),["preventDefault"=>false,"jqueryDone"=>"replaceWith"]);
188
		}
189
	}
190
191
	protected function _getFieldName($index){
192
		return parent::_getFieldName($index)."[]";
193
	}
194
195
	protected function _getFieldCaption($index){
196
		return null;
197
	}
198
199
	protected function _setToolbarPosition($table,$captions=NULL){
200
		switch ($this->_toolbarPosition){
201
			case PositionInTable::BEFORETABLE:
202
			case PositionInTable::AFTERTABLE:
203
				if(isset($this->_compileParts)===false){
204
					$this->content[$this->_toolbarPosition]=$this->_toolbar;
205
				}
206
				break;
207
			case PositionInTable::HEADER:
208
			case PositionInTable::FOOTER:
209
			case PositionInTable::BODY:
210
				$this->addToolbarRow($this->_toolbarPosition,$table, $captions);
211
				break;
212
		}
213
	}
214
215
	/**
216
	 * Associates a $callback function after the compilation of the field at $index position
217
	 * The $callback function can take the following arguments : $field=>the compiled field, $instance : the active instance of the object, $index: the field position
218
	 * @param int $index postion of the compiled field
219
	 * @param callable $callback function called after the field compilation
220
	 * @return DataTable
221
	 */
222
	public function afterCompile($index,$callback){
223
		$this->_instanceViewer->afterCompile($index,$callback);
224
		return $this;
225
	}
226
227
	private function addToolbarRow($part,$table,$captions){
228
		$hasPart=$table->hasPart($part);
229
		if($hasPart){
230
			$row=$table->getPart($part)->addRow(\sizeof($captions));
231
		}else{
232
			$row=$table->getPart($part)->getRow(0);
233
		}
234
		$row->mergeCol();
235
		$row->setValues([$this->_toolbar]);
236
	}
237
238
	public function getHtmlComponent(){
239
		return $this->content["table"];
240
	}
241
242
	public function getUrls() {
243
		return $this->_urls;
244
	}
245
246
	/**
247
	 * Sets the associative array of urls for refreshing, updating or deleting
248
	 * @param string|array $urls associative array with keys refresh: for refreshing with search field or pagination, edit : for updating a row, delete: for deleting a row
249
	 * @return DataTable
250
	 */
251
	public function setUrls($urls) {
252
		if(\is_array($urls)){
253
			$this->_urls["refresh"]=JArray::getValue($urls, "refresh",0);
254
			$this->_urls["edit"]=JArray::getValue($urls, "edit",1);
255
			$this->_urls["delete"]=JArray::getValue($urls, "delete",2);
256
		}else{
257
			$this->_urls=["refresh"=>$urls,"edit"=>$urls,"delete"=>$urls];
258
		}
259
		return $this;
260
	}
261
262
	/**
263
	 * Paginates the DataTable element with a Semantic HtmlPaginationMenu component
264
	 * @param number $page the active page number
265
	 * @param number $total_rowcount the total number of items
266
	 * @param number $items_per_page The number of items per page
267
	 * @param number $pages_visibles The number of visible pages in the Pagination component
268
	 * @return DataTable
269
	 */
270
	public function paginate($page,$total_rowcount,$items_per_page=10,$pages_visibles=null){
271
		$this->_pagination=new Pagination($items_per_page,$pages_visibles,$page,$total_rowcount);
272
		return $this;
273
	}
274
275
	/**
276
	 * Auto Paginates the DataTable element with a Semantic HtmlPaginationMenu component
277
	 * @param number $page the active page number
278
	 * @param number $items_per_page The number of items per page
279
	 * @param number $pages_visibles The number of visible pages in the Pagination component
280
	 * @return DataTable
281
	 */
282
	public function autoPaginate($page=1,$items_per_page=10,$pages_visibles=4){
283
		$this->_pagination=new Pagination($items_per_page,$pages_visibles,$page);
284
		return $this;
285
	}
286
287
288
289
	/**
290
	 * @param array $compileParts
291
	 * @return DataTable
292
	 */
293
	public function refresh($compileParts=["tbody"]){
294
		$this->_compileParts=$compileParts;
295
		return $this;
296
	}
297
298
299
	public function addSearchInToolbar($position=Direction::RIGHT){
300
		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...
301
	}
302
303
	public function getSearchField(){
304
		if(isset($this->_searchField)===false){
305
			$this->_searchField=new HtmlInput("search-".$this->identifier,"search","","Search...");
306
			$this->_searchField->addIcon("search",Direction::RIGHT);
307
		}
308
		return $this->_searchField;
309
	}
310
311
	/**
312
	 * The callback function called after the insertion of each row when fromDatabaseObjects is called
313
	 * callback function takes the parameters $row : the row inserted and $object: the instance of model used
314
	 * @param callable $callback
315
	 * @return DataTable
316
	 */
317
	public function onNewRow($callback) {
318
		$this->content["table"]->onNewRow($callback);
319
		return $this;
320
	}
321
322
	public function asForm(){
323
		return $this->getForm();
324
	}
325
326
327
328
	protected function getTargetSelector() {
329
		$result=$this->_targetSelector;
330
		if(!isset($result))
331
			$result="#".$this->identifier;
332
		return $result;
333
	}
334
335
	/**
336
	 * Sets the response element selector for Edit and Delete request with ajax
337
	 * @param string $_targetSelector
338
	 * @return \Ajax\semantic\widgets\datatable\DataTable
339
	 */
340
	public function setTargetSelector($_targetSelector) {
341
		$this->_targetSelector=$_targetSelector;
342
		return $this;
343
	}
344
345
	public function getRefreshSelector() {
346
		if(isset($this->_refreshSelector))
347
			return $this->_refreshSelector;
348
		return "#".$this->identifier." tbody";
349
	}
350
351
	public function setRefreshSelector($_refreshSelector) {
352
		$this->_refreshSelector=$_refreshSelector;
353
		return $this;
354
	}
355
356
	/**
357
	 * {@inheritDoc}
358
	 * @see \Ajax\common\Widget::show()
359
	 */
360
	public function show($modelInstance){
361
		if(\is_array($modelInstance)){
362
			if(\is_array(array_values($modelInstance)[0]))
363
				$modelInstance=\json_decode(\json_encode($modelInstance), FALSE);
364
		}
365
		$this->_modelInstance=$modelInstance;
366
	}
367
368
	public function getRowClass() {
369
		return $this->_rowClass;
370
	}
371
372
	/**
373
	 * Sets the default row class (tr class)
374
	 * @param string $_rowClass
375
	 * @return DataTable
376
	 */
377
	public function setRowClass($_rowClass) {
378
		$this->_rowClass=$_rowClass;
379
		return $this;
380
	}
381
382
	/**
383
	 * Sets the message displayed when there is no record
384
	 * @param mixed $_emptyMessage
385
	 * @return DataTable
386
	 */
387
	public function setEmptyMessage($_emptyMessage) {
388
		$this->_emptyMessage=$_emptyMessage;
389
		return $this;
390
	}
391
392
	public function setSortable($colIndex=NULL) {
393
		$this->_sortable=$colIndex;
394
		return $this;
395
	}
396
397
}