Completed
Push — master ( f15fe2...9a8393 )
by Pavel
07:23 queued 11s
created

EntityGridItem::getPropertyAccessVariations()   A

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
36
    private function getPropertyAccessVariations(string $attribute): array
37
    {
38
        $camelAttribute = preg_replace_callback('/_([a-z]?)/', function ($matches) {
39
            return isset($matches[1]) ? strtoupper($matches[1]) : '';
40
        }, $attribute);
41
        $getter = 'get' . $camelAttribute;
42
        return [$camelAttribute, $getter];
43
    }
44
}