FieldAccesorTrait   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 26
c 1
b 0
f 0
dl 0
loc 46
rs 10
wmc 18

1 Method

Rating   Name   Duplication   Size   Complexity  
D getFieldData() 0 44 18
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * Copyright (C) 2020-2025 Iain Cambridge
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by
10
 * the Free Software Foundation, either version 2.1 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
20
 */
21
22
namespace Parthenon\Common;
23
24
use Parthenon\Common\Exception\InvalidFieldException;
25
26
trait FieldAccesorTrait
27
{
28
    protected function getFieldData($data, $fieldName)
29
    {
30
        if (false !== strpos($fieldName, '.')) {
31
            [$field, $subfield] = explode('.', $fieldName, 2);
32
33
            return $this->getFieldData($this->getFieldData($data, $field), $subfield);
34
        }
35
        $camelCase = str_replace('_', '', ucwords($fieldName, '_'));
36
        $getter = 'get'.$camelCase;
37
        $isser = 'is'.$camelCase;
38
        $hasser = 'has'.$camelCase;
39
        $camelCaseAccessor = lcfirst($camelCase);
40
        if (is_array($data) && array_key_exists($fieldName, $data)) {
41
            return $data[$fieldName];
42
        }
43
44
        if (is_object($data) && method_exists($data, $fieldName)) {
45
            return $data->$fieldName();
46
        }
47
        if (is_object($data) && method_exists($data, $camelCaseAccessor)) {
48
            return $data->$camelCaseAccessor();
49
        }
50
51
        if (is_object($data) && method_exists($data, $getter)) {
52
            return $data->$getter();
53
        }
54
55
        if (is_object($data) && method_exists($data, $isser)) {
56
            return $data->$isser();
57
        }
58
59
        if (is_object($data) && method_exists($data, $hasser)) {
60
            return $data->$hasser();
61
        }
62
63
        if (is_object($data) && property_exists($data, $camelCaseAccessor)) {
64
            return $data->$camelCaseAccessor;
65
        }
66
67
        if (is_object($data) && property_exists($data, $fieldName)) {
68
            return $data->$fieldName;
69
        }
70
71
        throw new InvalidFieldException('The field '.$fieldName.' is invalid');
72
    }
73
}
74