EntityGridItem::getPropertyAccessVariations()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
nc 1
nop 1
dl 0
loc 7
rs 10
c 1
b 0
f 0
1
<?php
2
3
4
namespace Pfilsx\DataGrid\Grid\Items;
5
6
7
use Pfilsx\DataGrid\DataGridException;
8
9
class EntityGridItem extends DataGridItem
10
{
11
12
    public function has(string $attribute): bool
13
    {
14
        list($camelAttribute, $getter) = $this->getPropertyAccessVariations($attribute);
15
        return method_exists($this->data, $getter)
16
            || property_exists($this->data, $attribute)
17
            || property_exists($this->data, $camelAttribute);
18
    }
19
20
    public function get(string $attribute)
21
    {
22
        list($camelAttribute, $getter) = $this->getPropertyAccessVariations($attribute);
23
        if (method_exists($this->data, $getter)) {
24
            return $this->data->$getter();
25
        }
26
        if (property_exists($this->data, $attribute)) {
27
            return $this->data->$attribute;
28
        }
29
        if (property_exists($this->data, $camelAttribute)) {
30
            return $this->data->$camelAttribute;
31
        }
32
        throw new DataGridException('Unknown property ' . $attribute . ' in ' . get_class($this->data));
33
    }
34
35
    public function __call(string $name, array $arguments)
36
    {
37
        if (method_exists($this->data, $name)){
38
            return call_user_func_array([$this->data, $name], $arguments);
39
        }
40
        throw new DataGridException('Unknown method ' . $name . ' in ' . get_class($this->data));
41
    }
42
43
44
    private function getPropertyAccessVariations(string $attribute): array
45
    {
46
        $camelAttribute = preg_replace_callback('/_([a-z]?)/', function ($matches) {
47
            return isset($matches[1]) ? strtoupper($matches[1]) : '';
48
        }, $attribute);
49
        $getter = 'get' . $camelAttribute;
50
        return [$camelAttribute, $getter];
51
    }
52
}