Completed
Push — master ( acbd35...e1ce60 )
by Jean-Christophe
03:14
created

DataTable   D

Complexity

Total Complexity 74

Size/Duplication

Total Lines 390
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 4
Bugs 2 Features 0
Metric Value
wmc 74
c 4
b 2
f 0
lcom 1
cbo 13
dl 0
loc 390
rs 4.5631

36 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B run() 0 14 6
A _generateBehavior() 0 6 2
A getTable() 0 3 1
C compile() 0 42 12
A _generateHeader() 0 6 2
A _generateContent() 0 15 3
A _generateRow() 0 22 3
A _generatePagination() 0 13 3
A _associatePaginationBehavior() 0 5 2
A _getFieldName() 0 3 1
A _getFieldCaption() 0 3 1
B _setToolbarPosition() 0 15 7
A afterCompile() 0 4 1
A addToolbarRow() 0 10 2
A getHtmlComponent() 0 3 1
A getUrls() 0 3 1
A setUrls() 0 10 2
A paginate() 0 4 1
A autoPaginate() 0 4 1
A refresh() 0 4 1
A addSearchInToolbar() 0 3 1
A getSearchField() 0 7 2
A onNewRow() 0 4 1
A asForm() 0 3 1
A getTargetSelector() 0 6 2
A setTargetSelector() 0 4 1
A getRefreshSelector() 0 5 2
A setRefreshSelector() 0 4 1
A show() 0 7 3
A getRowClass() 0 3 1
A setRowClass() 0 4 1
A setEmptyMessage() 0 4 1
A setSortable() 0 4 1
A setActiveRowSelector() 0 4 1
A hideColumn() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like DataTable often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DataTable, and based on these observations, apply Extract Interface, too.

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
		$id=$this->_instanceViewer->getIdentifier();
156
		if($this->_hasCheckboxes){
157
			$ck=new HtmlCheckbox("ck-".$this->identifier."-".$id,"");
158
			$ck->setOnChange("event.stopPropagation();");
159
			$field=$ck->getField();
160
			$field->setProperty("value",$id);
161
			$field->setProperty("name", "selection[]");
162
			if(isset($checkedClass))
163
				$field->setClass($checkedClass);
164
			\array_unshift($values, $ck);
165
		}
166
		$result=$table->newRow();
167
		$result->setIdentifier($this->identifier."-tr-".$id);
168
		$result->setProperty("data-ajax",$id);
169
		$result->setValues($values);
170
		$result->addToProperty("class",$this->_rowClass);
171
		return $result;
172
	}
173
174
	protected function _generatePagination($table,$js=NULL){
175
		if(isset($this->_toolbar)){
176
			if($this->_toolbarPosition==PositionInTable::FOOTER)
177
				$this->_toolbar->setFloated("left");
178
		}
179
		$footer=$table->getFooter();
180
		$footer->mergeCol();
181
		$menu=new HtmlPaginationMenu("pagination-".$this->identifier,$this->_pagination->getPagesNumbers());
182
		$menu->floatRight();
183
		$menu->setActiveItem($this->_pagination->getPage()-1);
184
		$footer->addValues($menu);
185
		$this->_associatePaginationBehavior($menu,$js);
186
	}
187
188
	protected function _associatePaginationBehavior(HtmlMenu $menu,JsUtils $js=NULL){
189
		if(isset($this->_urls["refresh"])){
190
			$menu->postOnClick($this->_urls["refresh"],"{'p':$(this).attr('data-page')}",$this->getRefreshSelector(),["preventDefault"=>false,"jqueryDone"=>"replaceWith"]);
191
		}
192
	}
193
194
	protected function _getFieldName($index){
195
		return parent::_getFieldName($index)."[]";
196
	}
197
198
	protected function _getFieldCaption($index){
199
		return null;
200
	}
201
202
	protected function _setToolbarPosition($table,$captions=NULL){
203
		switch ($this->_toolbarPosition){
204
			case PositionInTable::BEFORETABLE:
205
			case PositionInTable::AFTERTABLE:
206
				if(isset($this->_compileParts)===false){
207
					$this->content[$this->_toolbarPosition]=$this->_toolbar;
208
				}
209
				break;
210
			case PositionInTable::HEADER:
211
			case PositionInTable::FOOTER:
212
			case PositionInTable::BODY:
213
				$this->addToolbarRow($this->_toolbarPosition,$table, $captions);
214
				break;
215
		}
216
	}
217
218
	/**
219
	 * Associates a $callback function after the compilation of the field at $index position
220
	 * The $callback function can take the following arguments : $field=>the compiled field, $instance : the active instance of the object, $index: the field position
221
	 * @param int $index postion of the compiled field
222
	 * @param callable $callback function called after the field compilation
223
	 * @return DataTable
224
	 */
225
	public function afterCompile($index,$callback){
226
		$this->_instanceViewer->afterCompile($index,$callback);
227
		return $this;
228
	}
229
230
	private function addToolbarRow($part,$table,$captions){
231
		$hasPart=$table->hasPart($part);
232
		if($hasPart){
233
			$row=$table->getPart($part)->addRow(\sizeof($captions));
234
		}else{
235
			$row=$table->getPart($part)->getRow(0);
236
		}
237
		$row->mergeCol();
238
		$row->setValues([$this->_toolbar]);
239
	}
240
241
	public function getHtmlComponent(){
242
		return $this->content["table"];
243
	}
244
245
	public function getUrls() {
246
		return $this->_urls;
247
	}
248
249
	/**
250
	 * Sets the associative array of urls for refreshing, updating or deleting
251
	 * @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
252
	 * @return DataTable
253
	 */
254
	public function setUrls($urls) {
255
		if(\is_array($urls)){
256
			$this->_urls["refresh"]=JArray::getValue($urls, "refresh",0);
257
			$this->_urls["edit"]=JArray::getValue($urls, "edit",1);
258
			$this->_urls["delete"]=JArray::getValue($urls, "delete",2);
259
		}else{
260
			$this->_urls=["refresh"=>$urls,"edit"=>$urls,"delete"=>$urls];
261
		}
262
		return $this;
263
	}
264
265
	/**
266
	 * Paginates the DataTable element with a Semantic HtmlPaginationMenu component
267
	 * @param number $page the active page number
268
	 * @param number $total_rowcount the total number of items
269
	 * @param number $items_per_page The number of items per page
270
	 * @param number $pages_visibles The number of visible pages in the Pagination component
271
	 * @return DataTable
272
	 */
273
	public function paginate($page,$total_rowcount,$items_per_page=10,$pages_visibles=null){
274
		$this->_pagination=new Pagination($items_per_page,$pages_visibles,$page,$total_rowcount);
275
		return $this;
276
	}
277
278
	/**
279
	 * Auto Paginates the DataTable element with a Semantic HtmlPaginationMenu component
280
	 * @param number $page the active page number
281
	 * @param number $items_per_page The number of items per page
282
	 * @param number $pages_visibles The number of visible pages in the Pagination component
283
	 * @return DataTable
284
	 */
285
	public function autoPaginate($page=1,$items_per_page=10,$pages_visibles=4){
286
		$this->_pagination=new Pagination($items_per_page,$pages_visibles,$page);
287
		return $this;
288
	}
289
290
291
292
	/**
293
	 * @param array $compileParts
294
	 * @return DataTable
295
	 */
296
	public function refresh($compileParts=["tbody"]){
297
		$this->_compileParts=$compileParts;
298
		return $this;
299
	}
300
301
302
	public function addSearchInToolbar($position=Direction::RIGHT){
303
		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...
304
	}
305
306
	public function getSearchField(){
307
		if(isset($this->_searchField)===false){
308
			$this->_searchField=new HtmlInput("search-".$this->identifier,"search","","Search...");
309
			$this->_searchField->addIcon("search",Direction::RIGHT);
310
		}
311
		return $this->_searchField;
312
	}
313
314
	/**
315
	 * The callback function called after the insertion of each row when fromDatabaseObjects is called
316
	 * callback function takes the parameters $row : the row inserted and $object: the instance of model used
317
	 * @param callable $callback
318
	 * @return DataTable
319
	 */
320
	public function onNewRow($callback) {
321
		$this->content["table"]->onNewRow($callback);
322
		return $this;
323
	}
324
325
	public function asForm(){
326
		return $this->getForm();
327
	}
328
329
330
331
	protected function getTargetSelector() {
332
		$result=$this->_targetSelector;
333
		if(!isset($result))
334
			$result="#".$this->identifier;
335
		return $result;
336
	}
337
338
	/**
339
	 * Sets the response element selector for Edit and Delete request with ajax
340
	 * @param string $_targetSelector
341
	 * @return \Ajax\semantic\widgets\datatable\DataTable
342
	 */
343
	public function setTargetSelector($_targetSelector) {
344
		$this->_targetSelector=$_targetSelector;
345
		return $this;
346
	}
347
348
	public function getRefreshSelector() {
349
		if(isset($this->_refreshSelector))
350
			return $this->_refreshSelector;
351
		return "#".$this->identifier." tbody";
352
	}
353
354
	/**
355
	 * @param string $_refreshSelector
356
	 * @return DataTable
357
	 */
358
	public function setRefreshSelector($_refreshSelector) {
359
		$this->_refreshSelector=$_refreshSelector;
360
		return $this;
361
	}
362
363
	/**
364
	 * {@inheritDoc}
365
	 * @see \Ajax\common\Widget::show()
366
	 */
367
	public function show($modelInstance){
368
		if(\is_array($modelInstance)){
369
			if(\is_array(array_values($modelInstance)[0]))
370
				$modelInstance=\json_decode(\json_encode($modelInstance), FALSE);
371
		}
372
		$this->_modelInstance=$modelInstance;
373
	}
374
375
	public function getRowClass() {
376
		return $this->_rowClass;
377
	}
378
379
	/**
380
	 * Sets the default row class (tr class)
381
	 * @param string $_rowClass
382
	 * @return DataTable
383
	 */
384
	public function setRowClass($_rowClass) {
385
		$this->_rowClass=$_rowClass;
386
		return $this;
387
	}
388
389
	/**
390
	 * Sets the message displayed when there is no record
391
	 * @param mixed $_emptyMessage
392
	 * @return DataTable
393
	 */
394
	public function setEmptyMessage($_emptyMessage) {
395
		$this->_emptyMessage=$_emptyMessage;
396
		return $this;
397
	}
398
399
	public function setSortable($colIndex=NULL) {
400
		$this->_sortable=$colIndex;
401
		return $this;
402
	}
403
404
	public function setActiveRowSelector($class="active",$event="click",$multiple=false){
405
		$this->getTable()->setActiveRowSelector($class,$event,$multiple);
406
		return $this;
407
	}
408
409
	public function hideColumn($colIndex){
410
		$this->getTable()->hideColumn($colIndex);
411
		return $this;
412
	}
413
414
}