/
AbstractAugmented.php
115 lines (89 loc) · 2.7 KB
/
AbstractAugmented.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
namespace Statamic\Data;
use Statamic\Contracts\Data\Augmented;
use Statamic\Fields\Value;
use Statamic\Statamic;
use Statamic\Support\Arr;
use Statamic\Support\Str;
abstract class AbstractAugmented implements Augmented
{
protected $data;
protected $blueprintFields;
public function __construct($data)
{
$this->data = $data;
}
public function all()
{
return $this->select();
}
public function except($keys)
{
return $this->select(array_diff($this->keys(), Arr::wrap($keys)));
}
public function select($keys = null)
{
$arr = [];
$keys = $this->filterKeys(Arr::wrap($keys ?: $this->keys()));
foreach ($keys as $key) {
$arr[$key] = $this->get($key);
}
return new AugmentedCollection($arr);
}
abstract public function keys();
public function get($handle)
{
$method = Str::camel($handle);
if ($this->methodExistsOnThisClass($method)) {
return $this->$method();
}
if (method_exists($this->data, $method) && collect($this->keys())->contains(Str::snake($handle))) {
return $this->wrapValue($this->data->$method(), $handle);
}
return $this->wrapValue($this->getFromData($handle), $handle);
}
protected function filterKeys($keys)
{
return array_diff($keys, $this->excludedKeys());
}
protected function excludedKeys()
{
return Statamic::isApiRoute()
? config('statamic.api.excluded_keys', [])
: [];
}
private function methodExistsOnThisClass($method)
{
return method_exists($this, $method) && ! in_array($method, ['select', 'except']);
}
protected function getFromData($handle)
{
$value = method_exists($this->data, 'value') ? $this->data->value($handle) : $this->data->get($handle);
if (method_exists($this->data, 'getSupplement')) {
$value = $this->data->getSupplement($handle) ?? $value;
}
return $value;
}
protected function wrapValue($value, $handle)
{
$fields = $this->blueprintFields();
if (! $fields->has($handle)) {
return $value;
}
return new Value(
$value,
$handle,
$fields->get($handle)->fieldtype(),
$this->data
);
}
protected function blueprintFields()
{
if (! isset($this->blueprintFields)) {
$this->blueprintFields = (method_exists($this->data, 'blueprint') && $blueprint = $this->data->blueprint())
? $blueprint->fields()->all()
: collect();
}
return $this->blueprintFields;
}
}