-
Notifications
You must be signed in to change notification settings - Fork 924
Expand file tree
/
Copy pathFieldsProtectedMethods.php
More file actions
398 lines (334 loc) · 14 KB
/
FieldsProtectedMethods.php
File metadata and controls
398 lines (334 loc) · 14 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
<?php
namespace Backpack\CRUD\app\Library\CrudPanel\Traits;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
trait FieldsProtectedMethods
{
/**
* If field has entity we want to get the relation type from it.
*
* @param array $field
* @return array
*/
public function makeSureFieldHasRelationType($field)
{
$field['relation_type'] = $field['relation_type'] ?? $this->inferRelationTypeFromRelationship($field);
return $field;
}
/**
* If field has entity we want to make sure it also has a model for that relation.
*
* @param array $field
* @return array
*/
public function makeSureFieldHasModel($field)
{
$field['model'] = $field['model'] ?? $this->inferFieldModelFromRelationship($field);
return $field;
}
/**
* Based on relation type we can guess if pivot is set.
*
* @param array $field
* @return array
*/
public function makeSureFieldHasPivot($field)
{
$field['pivot'] = $field['pivot'] ?? $this->guessIfFieldHasPivotFromRelationType($field['relation_type']);
return $field;
}
/**
* Based on relation type we can try to guess if it is a multiple field.
*
* @param array $field
* @return array
*/
public function makeSureFieldHasMultiple($field)
{
if (isset($field['relation_type'])) {
$field['multiple'] = $field['multiple'] ?? $this->guessIfFieldHasMultipleFromRelationType($field['relation_type']);
}
return $field;
}
/**
* In case field name is dot notation we want to convert it to a valid HTML array field name for validation purposes.
*
* @param array $field
* @return array
*/
public function overwriteFieldNameFromDotNotationToArray($field)
{
if (strpos($field['name'], '.') !== false) {
$entity_array = explode('.', $field['name']);
$name_string = '';
foreach ($entity_array as $key => $array_entity) {
$name_string .= ($key == 0) ? $array_entity : '['.$array_entity.']';
}
$field['name'] = $name_string;
}
return $field;
}
/**
* Run the field name overwrite in multiple fields.
*
* @param array $fields
* @return array
*/
public function overwriteFieldNamesFromDotNotationToArray($fields)
{
foreach ($fields as $key => $field) {
$fields[$key] = $this->overwriteFieldNameFromDotNotationToArray($field);
}
return $fields;
}
/**
* If the field_definition_array array is a string, it means the programmer was lazy
* and has only passed the name of the field. Turn that into a proper array.
*
* @param string|array $field The field definition array (or string).
* @return array
*/
protected function makeSureFieldHasName($field)
{
if (empty($field)) {
abort(500, 'Field name can\'t be empty', ['developer-error-exception']);
}
if (is_string($field)) {
return ['name' => Str::replace(' ', '', $field)];
}
if (is_array($field) && ! isset($field['name'])) {
abort(500, 'All fields must have their name defined', ['developer-error-exception']);
}
if (is_array($field['name'])) {
abort(500, 'Field name can\'t be an array. It should be a string. Error in field: '.json_encode($field['name']), ['developer-error-exception']);
}
$field['name'] = Str::replace(' ', '', $field['name']);
return $field;
}
/**
* If entity is not present, but it looks like the field SHOULD be a relationship field,
* try to determine the method on the model that defines the relationship, and pass it to
* the field as 'entity'.
*
* @param array $field
* @return array
*/
protected function makeSureFieldHasEntity($field)
{
$model = isset($field['baseModel']) ? (new $field['baseModel']) : $this->model;
if (isset($field['entity'])) {
return $field;
}
// by default, entity is false if we cannot link it with guessing functions to a relation
$field['entity'] = false;
//if the name is dot notation we are sure it's a relationship
if (strpos($field['name'], '.') !== false) {
$possibleMethodName = Str::of($field['name'])->before('.')->value();
// check model method for possibility of being a relationship
$field['entity'] = $this->modelMethodIsRelationship($model, $possibleMethodName) ? $field['name'] : false;
return $field;
}
// if there's a method on the model with this name
if (method_exists($model, $field['name']) || $model->isRelation($field['name'])) {
// check model method for possibility of being a relationship
$field['entity'] = $this->modelMethodIsRelationship($model, $field['name']);
return $field;
}
// if the name ends with _id and that method exists,
// we can probably use it as an entity
if (Str::endsWith($field['name'], '_id')) {
$possibleMethodName = Str::replaceLast('_id', '', $field['name']);
if (method_exists($model, $possibleMethodName)) {
// check model method for possibility of being a relationship
$field['entity'] = $this->modelMethodIsRelationship($model, $possibleMethodName);
return $field;
}
}
return $field;
}
protected function makeSureFieldHasAttribute($field)
{
if (isset($field['entity']) && $field['entity']) {
// if the user setup the attribute in relation string, we are not going to infer that attribute from model
// instead we get the defined attribute by the user.
if ($this->isAttributeInRelationString($field)) {
$field['attribute'] = $field['attribute'] ?? Str::afterLast($field['entity'], '.');
return $field;
}
}
// if there's a model defined, but no attribute
// guess an attribute using the identifiableAttribute functionality in CrudTrait
if (isset($field['model']) && ! isset($field['attribute']) && method_exists($field['model'], 'identifiableAttribute')) {
$field['attribute'] = (new $field['model']())->identifiableAttribute();
}
return $field;
}
/**
* Set the label of a field, if it's missing, by capitalizing the name and replacing
* underscores with spaces.
*
* @param array $field Field definition array.
* @return array Field definition array that contains label too.
*/
protected function makeSureFieldHasLabel($field)
{
if (! isset($field['label'])) {
$name = str_replace(',', ' ', $field['name']);
$name = str_replace('_id', '', $name);
$field['label'] = mb_ucfirst(str_replace('_', ' ', $name));
}
return $field;
}
/**
* Set the type of a field, if it's missing, by inferring it from the
* db column type.
*
* @param array $field Field definition array.
* @return array Field definition array that contains type too.
*/
protected function makeSureFieldHasType($field)
{
if (! isset($field['type'])) {
$field['type'] = isset($field['relation_type']) ? $this->inferFieldTypeFromRelationType($field['relation_type']) : $this->inferFieldTypeFromDbColumnType($field['name']);
}
return $field;
}
protected function inferFieldTypeFromRelationType($relationType)
{
if (backpack_pro()) {
return 'relationship';
}
switch ($relationType) {
case 'BelongsTo':
return 'select';
case 'BelongsToMany':
case 'MorphToMany':
return 'select_multiple';
default:
return 'text';
}
}
/**
* If a field has subfields, go through each subfield and guess
* its attribute, filling in whatever is missing.
*
* @param array $field Field definition array.
* @return array The improved definition of that field (a better 'subfields' array)
*/
protected function makeSureSubfieldsHaveNecessaryAttributes($field)
{
if (! isset($field['subfields']) || ! is_array($field['subfields'])) {
return $field;
}
if (! is_multidimensional_array($field['subfields'], true)) {
abort(500, 'Subfields of «'.$field['name'].'» are malformed. Make sure you provide an array of subfields.', ['developer-error-exception']);
}
foreach ($field['subfields'] as $key => $subfield) {
if (empty($subfield) || ! isset($subfield['name'])) {
abort(500, 'A subfield of «'.$field['name'].'» is malformed. Subfield attribute name can\'t be empty.', ['developer-error-exception']);
}
// make sure the field definition is an array
if (is_string($subfield)) {
$subfield = ['name' => $subfield];
}
$subfield['name'] = Str::replace(' ', '', $subfield['name']);
$subfield['parentFieldName'] = $field['name'];
$subfield['baseFieldName'] = is_array($subfield['name']) ? implode(',', $subfield['name']) : $subfield['name'];
$subfield['baseFieldName'] = Str::afterLast($subfield['baseFieldName'], '.');
if (! isset($field['model'])) {
// we're inside a simple 'repeatable' with no model/relationship, so
// we assume all subfields are supposed to be text fields
$subfield['type'] = $subfield['type'] ?? 'text';
$subfield['entity'] = $subfield['entity'] ?? false;
} else {
// we should use 'model' as the `baseModel` for all subfields, so that when
// we look if `category()` relationship exists on the model, we look on
// the model this repeatable represents, not the main CRUD model
$currentEntity = $subfield['baseEntity'] ?? $field['entity'];
$subfield['baseModel'] = $subfield['baseModel'] ?? $field['model'];
$subfield['baseEntity'] = isset($field['baseEntity']) ? $field['baseEntity'].'.'.$currentEntity : $currentEntity;
}
$field['subfields'][$key] = $this->makeSureFieldHasNecessaryAttributes($subfield);
}
// when field has any of `many` relations we need to append either the pivot selector for the `ToMany` or the
// local key for the `many` relations. Other relations don't need any special treatment when used as subfields.
if (isset($field['relation_type'])) {
switch ($field['relation_type']) {
case 'MorphToMany':
case 'BelongsToMany':
$pivotSelectorField = static::getPivotFieldStructure($field);
$pivot = Arr::where($field['subfields'], function ($item) use ($pivotSelectorField) {
return $item['name'] === $pivotSelectorField['name'];
});
if (! empty($pivot)) {
break;
}
if ($field['allow_duplicate_pivots'] ?? false) {
$pivotSelectorField['allow_duplicate_pivots'] = true;
$field['subfields'] = Arr::prepend($field['subfields'], [
'name' => $field['pivot_key_name'] ?? 'id',
'type' => 'hidden',
'wrapper' => [
'class' => 'd-none',
],
]);
}
$this->setupFieldValidation($pivotSelectorField, $field['name']);
$field['subfields'] = Arr::prepend($field['subfields'], $pivotSelectorField);
break;
case 'MorphMany':
case 'HasMany':
$entity = isset($field['baseEntity']) ? $field['baseEntity'].'.'.$field['entity'] : $field['entity'];
$relationInstance = $this->getRelationInstance(['entity' => $entity]);
$localKeyField = Arr::where($field['subfields'], function ($item) use ($relationInstance) {
return $item['name'] === $relationInstance->getRelated()->getKeyName();
});
if (! empty($localKeyField)) {
break;
}
$field['subfields'] = Arr::prepend($field['subfields'], [
'name' => $relationInstance->getRelated()->getKeyName(),
'type' => 'hidden',
]);
break;
}
}
return $field;
}
/**
* Enable the tabs functionality, if a field has a tab defined.
*
* @param array $field Field definition array.
* @return void
*/
protected function enableTabsIfFieldUsesThem($field)
{
// if a tab was mentioned, we should enable it
if (isset($field['tab'])) {
if (! $this->tabsEnabled()) {
$this->enableTabs();
}
}
}
/**
* Add a field to the current operation, using the Settings API.
*
* @param array $field Field definition array.
*/
protected function addFieldToOperationSettings($field)
{
$allFields = $this->getOperationSetting('fields');
$allFields = array_merge($this->getCleanStateFields(), [$field['name'] => $field]);
$this->setOperationSetting('fields', $allFields);
}
/**
* Get the string that should be used as an array key, for the attributive array
* where the fields are stored for the current operation.
*
* @deprecated v6
*/
protected function getFieldKey(array $field): string
{
return $field['name'];
}
}