|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace NovaFlexibleContent\Value; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
|
6
|
|
|
use NovaFlexibleContent\Layouts\Collections\GroupsCollection; |
|
7
|
|
|
use NovaFlexibleContent\Layouts\Collections\LayoutsCollection; |
|
8
|
|
|
use NovaFlexibleContent\Layouts\Layout; |
|
9
|
|
|
|
|
10
|
|
|
class DefaultResolver implements Resolver |
|
11
|
|
|
{ |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* @inerhitDoc |
|
15
|
|
|
*/ |
|
16
|
|
|
public function set(mixed $resource, string $attribute, GroupsCollection $groups): string |
|
17
|
|
|
{ |
|
18
|
|
|
return $resource->$attribute = $groups->map(function (Layout $group) { |
|
19
|
|
|
return [ |
|
20
|
|
|
'layout' => $group->name(), |
|
21
|
|
|
'key' => $group->key(), |
|
22
|
|
|
'collapsed' => $group->isCollapsed(), |
|
23
|
|
|
'attributes' => $group->getAttributes(), |
|
24
|
|
|
]; |
|
25
|
|
|
}); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @inerhitDoc |
|
30
|
|
|
*/ |
|
31
|
4 |
|
public function get(mixed $resource, string $attribute, LayoutsCollection $groups): GroupsCollection |
|
32
|
|
|
{ |
|
33
|
4 |
|
return GroupsCollection::make( |
|
34
|
4 |
|
$this->extractValueFromResource($resource, $attribute) |
|
|
|
|
|
|
35
|
4 |
|
)->map(function ($item) use ($groups, $attribute) { |
|
|
|
|
|
|
36
|
4 |
|
if($item instanceof Layout) { |
|
37
|
|
|
return $item; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
4 |
|
if ($layout = $groups->find($item->layout)) { |
|
41
|
4 |
|
return $layout->duplicate($item->key, (array)$item->attributes) |
|
42
|
4 |
|
->setCollapsed((bool)($item->collapsed ?? false)); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
return null; |
|
46
|
4 |
|
})->filter()->values(); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Find the attribute's value in the given resource |
|
51
|
|
|
* |
|
52
|
|
|
* @param mixed $resource |
|
53
|
|
|
* @param string $attribute |
|
54
|
|
|
* @return array |
|
55
|
|
|
*/ |
|
56
|
4 |
|
protected function extractValueFromResource($resource, $attribute) |
|
57
|
|
|
{ |
|
58
|
4 |
|
$value = data_get($resource, str_replace('->', '.', $attribute)) ?? []; |
|
59
|
|
|
|
|
60
|
4 |
|
if ($value instanceof Collection) { |
|
61
|
|
|
$value = $value->all(); |
|
62
|
4 |
|
} elseif (is_string($value)) { |
|
63
|
4 |
|
$value = json_decode($value) ?? []; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
// Fail silently in case data is invalid |
|
67
|
4 |
|
if (!is_array($value)) { |
|
68
|
|
|
return []; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
4 |
|
return array_map(function ($item) { |
|
72
|
4 |
|
return is_array($item) ? (object)$item : $item; |
|
73
|
4 |
|
}, $value); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|