Completed
Branch feature/rework (8c4d59)
by Pavel
07:53
created

DataColumn::getEntityAttribute()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 2
nop 2
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace Pfilsx\DataGrid\Grid\Columns;
5
6
7
use Pfilsx\DataGrid\DataGridException;
8
9
class DataColumn extends AbstractColumn
10
{
11
    protected $attribute;
12
    protected $format = 'raw';
13
    protected $sort = true;
14
15
    /**
16
     * @param mixed $attribute
17
     */
18
    protected function setAttribute($attribute): void
19
    {
20
        $this->attribute = $attribute;
21
    }
22
23
    /**
24
     * @return null|string
25
     */
26
    public function getAttribute()
27
    {
28
        return $this->attribute;
29
    }
30
31
    /**
32
     * @return string
33
     */
34
    public function getFormat(): string
35
    {
36
        return $this->format;
37
    }
38
39
    /**
40
     * @param string $format
41
     */
42
    protected function setFormat(string $format): void
43
    {
44
        $this->format = strtolower($format);
45
    }
46
47
    protected function checkConfiguration()
48
    {
49
        if ((!is_string($this->attribute) || empty($this->attribute)) && $this->value === null) {
50
            throw new DataGridException('attribute or value property must be set for ' . static::class);
51
        }
52
    }
53
54
    public function hasFilter()
55
    {
56
        return parent::hasFilter() && !empty($this->attribute);
57
    }
58
59
    public function getHeadContent()
60
    {
61
        return !empty($this->label) ? ucfirst($this->label) : (!empty($this->attribute) ? ucfirst($this->attribute) : '');
62
    }
63
64
    public function getFilterContent()
65
    {
66
        if ($this->hasFilter()) {
67
            return $this->filter->render($this->attribute, $this->filterValue);
68
        }
69
        return '';
70
    }
71
72
    public function getCellContent($entity)
73
    {
74
        $result = (string)$this->getCellValue($entity);
75
        return $this->format === 'html'
76
            ? $result
77
            : htmlspecialchars($result);
78
    }
79
80
    protected function getCellValue($entity)
81
    {
82
        if (is_callable($this->value)) {
83
            return call_user_func_array($this->value, [$entity]);
84
        } elseif ($this->value !== null) {
85
            return $this->value;
86
        } else {
87
            return $entity->{$this->attribute};
88
        }
89
    }
90
}
91