|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* Copyright Humbly Arrogant Ltd 2020-2022. |
|
7
|
|
|
* |
|
8
|
|
|
* Use of this software is governed by the Business Source License included in the LICENSE file and at https://getparthenon.com/docs/next/license. |
|
9
|
|
|
* |
|
10
|
|
|
* Change Date: TBD ( 3 years after 2.0.0 release ) |
|
11
|
|
|
* |
|
12
|
|
|
* On the date above, in accordance with the Business Source License, use of this software will be governed by the open source license specified in the LICENSE file. |
|
13
|
|
|
*/ |
|
14
|
|
|
|
|
15
|
|
|
namespace Parthenon\Common; |
|
16
|
|
|
|
|
17
|
|
|
use Parthenon\Common\Exception\InvalidFieldException; |
|
18
|
|
|
|
|
19
|
|
|
trait FieldAccesorTrait |
|
20
|
|
|
{ |
|
21
|
|
|
protected function getFieldData($data, $fieldName) |
|
22
|
|
|
{ |
|
23
|
|
|
if (false !== strpos($fieldName, '.')) { |
|
24
|
|
|
[$field, $subfield] = explode('.', $fieldName, 2); |
|
25
|
|
|
|
|
26
|
|
|
return $this->getFieldData($this->getFieldData($data, $field), $subfield); |
|
27
|
|
|
} |
|
28
|
|
|
$camelCase = str_replace('_', '', ucwords($fieldName, '_')); |
|
29
|
|
|
$getter = 'get'.$camelCase; |
|
30
|
|
|
$isser = 'is'.$camelCase; |
|
31
|
|
|
$hasser = 'has'.$camelCase; |
|
32
|
|
|
$camelCaseAccessor = lcfirst($camelCase); |
|
33
|
|
|
if (is_array($data) && array_key_exists($fieldName, $data)) { |
|
34
|
|
|
return $data[$fieldName]; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
if (is_object($data) && method_exists($data, $fieldName)) { |
|
38
|
|
|
return $data->$fieldName(); |
|
39
|
|
|
} |
|
40
|
|
|
if (is_object($data) && method_exists($data, $camelCaseAccessor)) { |
|
41
|
|
|
return $data->$camelCaseAccessor(); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if (is_object($data) && method_exists($data, $getter)) { |
|
45
|
|
|
return $data->$getter(); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
if (is_object($data) && method_exists($data, $isser)) { |
|
49
|
|
|
return $data->$isser(); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
if (is_object($data) && method_exists($data, $hasser)) { |
|
53
|
|
|
return $data->$hasser(); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
if (is_object($data) && property_exists($data, $camelCaseAccessor)) { |
|
57
|
|
|
return $data->$camelCaseAccessor; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
if (is_object($data) && property_exists($data, $fieldName)) { |
|
61
|
|
|
return $data->$fieldName; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
throw new InvalidFieldException('The field '.$fieldName.' is invalid'); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|