Completed
Push — master ( 50defc...ab536e )
by Pavel
02:43
created

Column::addAttributes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
/**
4
 * @copyright   Copyright (c) 2015 ublaboo <[email protected]>
5
 * @author      Pavel Janda <[email protected]>
6
 * @package     Ublaboo
7
 */
8
9
namespace Ublaboo\DataGrid\Column;
10
11
use Nette\InvalidArgumentException;
12
use Ublaboo;
13
use Ublaboo\DataGrid\DataGrid;
14
use Ublaboo\DataGrid\Row;
15
use Ublaboo\DataGrid\Exception\DataGridException;
16
use Ublaboo\DataGrid\Exception\DataGridColumnRendererException;
17
use Ublaboo\DataGrid\Exception\DataGridHasToBeAttachedToPresenterComponentException;
18
use Nette\Utils\Html;
19
20
abstract class Column extends Ublaboo\DataGrid\Object
21
{
22
23
	/**
24
	 * @var string
25
	 */
26
	protected $column;
27
28
	/**
29
	 * @var string
30
	 */
31
	protected $name;
32
33
	/**
34
	 * @var array
35
	 */
36
	protected $replacements = [];
37
38
	/**
39
	 * @var Renderer|NULL
40
	 */
41
	protected $renderer;
42
43
	/**
44
	 * @var string
45
	 */
46
	protected $template;
47
48
	/**
49
	 * @var boolean
50
	 */
51
	protected $is_sortable = FALSE;
52
53
	/**
54
	 * @var array
55
	 */
56
	protected $sort;
57
58
	/**
59
	 * @var bool
60
	 */
61
	protected $template_escaping = TRUE;
62
63
	/**
64
	 * @var string
65
	 */
66
	protected $align;
67
68
	/**
69
	 * @var array
70
	 */
71
	protected $template_variables;
72
73
	/**
74
	 * @var callable
75
	 */
76
	protected $editable_callback;
77
78
	/**
79
	 * @var DataGrid
80
	 */
81
	protected $grid;
82
83
	/**
84
	 * Cached html elements
85
	 * @var array
86
	 */
87
	protected $el_cache = [];
88
89
90
	/**
91
	 * @param DataGrid $grid
92
	 * @param string   $column
93
	 * @param string   $name
94
	 */
95
	public function __construct(DataGrid $grid, $column, $name)
96
	{
97
		$this->grid = $grid;
98
		$this->column = $column;
99
		$this->name = $name;
100
	}
101
102
103
	/**
104
	 * Render row item into template
105
	 * @param  Row   $row
106
	 * @return mixed
107
	 */
108
	public function render(Row $row)
109
	{
110
		/**
111
		 * Renderer function may be used
112
		 */
113
		try {
114
			return $this->useRenderer($row);
115
		} catch (DataGridColumnRendererException $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
116
117
		/**
118
		 * Or replacements may be applied
119
		 */
120
		list($do_replace, $replaced) = $this->applyReplacements($row);
121
		if ($do_replace) {
122
			return $replaced;
123
		}
124
125
		return $this->getColumnValue($row);
126
	}
127
128
129
	/**
130
	 * Try to render item with custom renderer
131
	 * @param  Row   $row
132
	 * @return mixed
133
	 */
134
	public function useRenderer(Row $row)
135
	{
136
		$renderer = $this->getRenderer();
137
138
		if (!$renderer) {
139
			throw new DataGridColumnRendererException;
140
		}
141
142
		if ($renderer->getConditionCallback()) {
143
			if (!call_user_func_array($renderer->getConditionCallback(), [$row->getItem()])) {
144
				throw new DataGridColumnRendererException;
145
			}
146
147
			return call_user_func_array($renderer->getCallback(), [$row->getItem()]);
148
		}
149
150
		return call_user_func_array($renderer->getCallback(), [$row->getItem()]);
151
	}
152
153
154
	/**
155
	 * Should be column values escaped in latte?
156
	 * @param boolean $template_escaping
157
	 */
158
	public function setTemplateEscaping($template_escaping = TRUE)
159
	{
160
		$this->template_escaping = (bool) $template_escaping;
161
162
		return $this;
163
	}
164
165
166
	public function isTemplateEscaped()
167
	{
168
		return $this->template_escaping;
169
	}
170
171
172
	/**
173
	 * Set column sortable or not
174
	 * @param bool $sortable
175
	 */
176
	public function setSortable($sortable = TRUE)
177
	{
178
		$this->is_sortable = (bool) $sortable;
179
180
		return $this;
181
	}
182
183
184
	/**
185
	 * Tell whether column is sortable
186
	 * @return boolean
187
	 */
188
	public function isSortable()
189
	{
190
		return $this->is_sortable;
191
	}
192
193
194
	/**
195
	 * Get column name
196
	 * @return string
197
	 */
198
	public function getColumnName()
199
	{
200
		return $this->column;
201
	}
202
203
204
	/**
205
	 * Get column value of row item
206
	 * @param  Row   $row
207
	 * @return mixed
208
	 */
209
	public function getColumnValue(Row $row)
210
	{
211
		return $row->getValue($this->column);
212
	}
213
214
215
	public function getName()
216
	{
217
		return $this->name;
218
	}
219
220
221
	/**
222
	 * Set column replacements
223
	 * @param  array $replacements
224
	 * @return Column
225
	 */
226
	public function setReplacement(array $replacements)
227
	{
228
		$this->replacements = $replacements;
229
230
		return $this;
231
	}
232
233
234
	/**
235
	 * Tell whether columns has replacements
236
	 * @return boolean
237
	 */
238
	public function hasReplacements()
239
	{
240
		return (bool) $this->replacements;
241
	}
242
243
244
	/**
245
	 * Apply replacements
246
	 * @param  Row   $row
247
	 * @return array
248
	 */
249
	public function applyReplacements(Row $row)
250
	{
251
		$value = $row->getValue($this->column);
252
253
		if ((is_scalar($value) || is_null($value)) && isset($this->replacements[$value])) {
254
			return [TRUE, $this->replacements[$value]];
255
		}
256
257
		return [FALSE, NULL];
258
	}
259
260
261
	/**
262
	 * Set renderer callback and (it may be optional - the condition callback will decide)
263
	 * @param callable $renderer
264
	 */
265
	public function setRenderer($renderer, $condition_callback = NULL)
266
	{
267
		if ($this->hasReplacements()) {
268
			throw new DataGridException(
269
				"Use either Column::setReplacement() or Column::setRenderer, not both."
270
			);
271
		}
272
273
		if (!is_callable($renderer)) {
274
			throw new DataGridException(
275
				"Renderer (method Column::setRenderer()) must be callable."
276
			);
277
		}
278
279
		if (NULL != $condition_callback && !is_callable($condition_callback)) {
280
			throw new DataGridException(
281
				"Renderer (method Column::setRenderer()) must be callable."
282
			);
283
		}
284
285
		$this->renderer = new Renderer($renderer, $condition_callback);
286
287
		return $this;
288
	}
289
290
291
	/**
292
	 * Set renderer callback just if condition is truthy
293
	 * @param callable $renderer
294
	 */
295
	public function setRendererOnCondition($renderer, $condition_callback)
296
	{
297
		return $this->setRenderer($renderer, $condition_callback);
298
	}
299
300
301
	/**
302
	 * Return custom renderer callback
303
	 * @return Renderer|null
304
	 */
305
	public function getRenderer()
306
	{
307
		return $this->renderer;
308
	}
309
310
311
	/**
312
	 * Column may have its own template
313
	 * @param string $template
314
	 */
315
	public function setTemplate($template, array $template_variables = [])
316
	{
317
		$this->template = $template;
318
		$this->template_variables = $template_variables;
319
320
		return $this;
321
	}
322
323
324
	/**
325
	 * Column can have variables that will be passed to custom template scope
326
	 * @return array
327
	 */
328
	public function getTemplateVariables()
329
	{
330
		return $this->template_variables;
331
	}
332
333
334
	/**
335
	 * Tell whether column has its owntemplate
336
	 * @return bool
337
	 */
338
	public function hasTemplate()
339
	{
340
		return (bool) $this->template;
341
	}
342
343
344
	/**
345
	 * Get column template path
346
	 * @return string
347
	 */
348
	public function getTemplate()
349
	{
350
		return $this->template;
351
	}
352
353
354
	/**
355
	 * Tell whether data source is sorted by this collumn
356
	 * @return boolean
357
	 */
358
	public function isSortedBy()
359
	{
360
		return (bool) $this->sort;
361
	}
362
363
364
	/**
365
	 * Tell column his sorting options
366
	 * @param array $sort
367
	 */
368
	public function setSort(array $sort)
369
	{
370
		$this->sort = $sort[$this->column];
371
372
		return $this;
373
	}
374
375
376
	/**
377
	 * What sorting will be applied after next click?
378
	 * @return array
379
	 */
380
	public function getSortNext()
381
	{
382
		if ($this->sort == 'ASC') {
383
			return [$this->column => 'DESC'];
384
		} else if ($this->sort == 'DESC') {
385
			return [$this->column => NULL];
386
		}
387
388
		return [$this->column => 'ASC'];
389
	}
390
391
392
	/**
393
	 * Is sorting ascending?
394
	 * @return boolean
395
	 */
396
	public function isSortAsc()
397
	{
398
		return $this->sort == 'ASC';
399
	}
400
401
402
	/**
403
	 * Set column alignment
404
	 * @param string $align
405
	 */
406
	public function setAlign($align)
407
	{
408
		$this->align = (string) $align;
409
410
		return $this;
411
	}
412
413
414
	/**
415
	 * Has column some alignment?
416
	 * @return boolean [description]
417
	 */
418
	public function hasAlign()
419
	{
420
		return (bool) $this->align;
421
	}
422
423
424
	/**
425
	 * Get column alignment
426
	 * @return string
427
	 */
428
	public function getAlign()
429
	{
430
		return $this->align ?: 'left';
431
	}
432
433
434
	/**
435
	 * Set callback that will be called after inline editing
436
	 * @param callable $editable_callback
437
	 */
438
	public function setEditableCallback(callable $editable_callback)
439
	{
440
		$this->editable_callback = $editable_callback;
441
442
		return $this;
443
	}
444
445
446
	/**
447
	 * Return callback that is used after inline editing
448
	 * @return callable
449
	 */
450
	public function getEditableCallback()
451
	{
452
		return $this->editable_callback;
453
	}
454
455
456
	/**
457
	 * Is column editable?
458
	 * @return boolean
459
	 */
460
	public function isEditable()
461
	{
462
		return (bool) $this->getEditableCallback();
463
	}
464
465
466
	/**
467
	 * Set attributes for both th and td element
468
	 * @param array $attrs
469
	 * @return static
470
	 */
471
	public function addAttributes(array $attrs)
472
	{
473
		$this->getElementPrototype('td')->addAttributes($attrs);
474
		$this->getElementPrototype('th')->addAttributes($attrs);
475
476
		return $this;
477
	}
478
479
480
	/**
481
	 * Get th/td column element
482
	 * @param  string   $tag th|td
483
	 * @param  string   $key
484
	 * @param  Row|NULL $row
485
	 * @return Html
486
	 */
487
	public function getElementPrototype($tag, $key = NULL, Row $row = NULL)
488
	{
489
		/**
490
		 * Get cached element
491
		 */
492
		if (empty($this->el_cache[$tag])) {
493
			$this->el_cache[$tag] = $el = $el = Html::el($tag);
494
		} else {
495
			$el = $this->el_cache[$tag];
496
		}
497
498
		/**
499
		 * Method called from datagrid template, set appropriate classes and another attributes
500
		 */
501
		if ($key) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $key of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
502
			/**
503
			 * If class was set by user via $el->class = '', fix it
504
			 */
505
			if (!empty($el->class) && is_string($el->class)) {
506
				$class = $el->class;
507
				unset($el->class);
508
509
				$el->class[] = $class;
510
			}
511
512
			$el->class[] = "col-{$key} text-{$this->getAlign()}";
513
514
			if ($tag == 'td') {
515
				if ($this->isEditable()) {
516
					$link = $this->grid->link('edit!', ['key' => $key, 'id' => $row->getId()]);
0 ignored issues
show
Bug introduced by
It seems like $row is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
517
518
					$el->data('datagrid-editable-url', $link);
519
				}
520
			}
521
		}
522
523
		return $el;
524
	}
525
526
527
	/**
528
	 * Create link to custom destination
529
	 * @param  string $href
530
	 * @param  array  $params
531
	 * @return string
532
	 * @throws DataGridHasToBeAttachedToPresenterComponentException
533
	 * @throws InvalidArgumentException
534
	 */
535
	protected function createLink($href, $params)
536
	{
537
		try {
538
			$parent = $this->grid->getParent();
539
540
			return $parent->link($href, $params);
541
		} catch (DataGridHasToBeAttachedToPresenterComponentException $e) {
542
			$parent = $this->grid->getPresenter();
543
544
		} catch (InvalidArgumentException $e) {
545
			$parent = $this->grid->getPresenter();
546
547
		}
548
549
		return $parent->link($href, $params);
550
	}
551
552
553
	/**
554
	 * Get row item params (E.g. action may be called id => $item->id, name => $item->name, ...)
555
	 * @param  Row   $row
556
	 * @param  array $params_list
557
	 * @return array
558
	 */
559
	protected function getItemParams(Row $row, array $params_list)
560
	{
561
		$return = [];
562
563
		foreach ($params_list as $param_name => $param) {
564
			$return[is_string($param_name) ? $param_name : $param] = $row->getValue($param);
565
		}
566
567
		return $return;
568
	}
569
570
}
571