/
Sets.php
105 lines (89 loc) · 3.28 KB
/
Sets.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
<?php
namespace Statamic\Fieldtypes;
use Statamic\CP\FieldtypeFactory;
use Statamic\Fields\Fieldset;
use Statamic\Fields\FieldTransformer;
use Statamic\Fields\Fieldtype;
use Statamic\Support\Arr;
class Sets extends Fieldtype
{
protected $selectable = false;
/**
* Converts the "sets" array of a Replicator (or Bard) field into what the
* <sets-fieldtype> Vue component is expecting, within either the Blueprint
* or Fieldset builders in the AJAX request performed when opening the field.
*/
public function preProcess($data)
{
return collect($data)->map(function ($set, $handle) {
$set['_id'] = $handle;
$set['handle'] = $handle;
$set['fields'] = collect($set['fields'])->map(function ($field, $i) {
return array_merge(FieldTransformer::toVue($field), ['_id' => $i]);
})->all();
return $set;
})->values()->all();
}
/**
* Converts the "sets" array of a Replicator (or Bard) field into what
* the <replicator-fieldtype> is expecting in its config.sets array.
*/
public function preProcessConfig($data)
{
return collect($data)
->map(function ($config, $name) {
return array_merge($config, [
'handle' => $name,
'id' => $name,
'fields' => (new NestedFields)->preProcessConfig(array_get($config, 'fields', [])),
]);
})
->values()
->all();
}
/**
* Converts the Blueprint/Fieldset builder Settings Vue component's representation of the
* Replicator's "sets" array into what should be saved to the Blueprint/Fieldset's YAML.
* Triggered in the AJAX request when you click "finish" when editing a Replicator field.
*/
public function process($sets)
{
return collect($sets)
->mapWithKeys(function ($set) {
$handle = Arr::pull($set, 'handle');
$set = Arr::except($set, '_id');
$set['fields'] = collect($set['fields'])->map(function ($field) {
return FieldTransformer::fromVue($field);
})->all();
return [$handle => $set];
})
->all();
}
private function moveOutNameKey($fields)
{
$processed = [];
foreach ($fields as $field) {
$handle = $field['handle'];
unset($field['handle']);
$processed[$handle] = $this->recursivelyProcess($field);
}
return $processed;
}
private function recursivelyProcess($config)
{
// Get the fieldtype for this field
$type = $config['type'];
$config_fieldtype = FieldtypeFactory::create($type);
// Get the fieldtype's config fieldset
$fieldset = $config_fieldtype->getConfigFieldset();
// Process all the fields in the fieldset
foreach ($fieldset->fieldtypes() as $field) {
// Ignore if the field isn't in the config
if (! in_array($field->getName(), array_keys($config))) {
continue;
}
$config[$field->getName()] = $field->process($config[$field->getName()]);
}
return Fieldset::cleanFieldForSaving($config);
}
}