72 lines
2.0 KiB
PHP
72 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace Modules\CCMS\Traits;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Http\Request;
|
|
|
|
trait UpdateCustomFields
|
|
{
|
|
public static function bootUpdateCustomFields()
|
|
{
|
|
static::saving(function (Model $model) {
|
|
if (method_exists($model, 'processCustomFields')) {
|
|
$model->processCustomFields(
|
|
request: app(Request::class),
|
|
model: $model,
|
|
);
|
|
}
|
|
});
|
|
}
|
|
|
|
public function processCustomFields(Request $request, Model $model)
|
|
{
|
|
if ($this->sectionWasRemoved($model)) {
|
|
$this->custom = null;
|
|
return;
|
|
}
|
|
|
|
if ($this->validateCustomFieldsInput($request)) {
|
|
$this->custom = $this->transformCustomFields($request);
|
|
}
|
|
}
|
|
|
|
public function sectionWasRemoved(Model $model): bool
|
|
{
|
|
return is_array($model->section) && !in_array("custom-field-section", $model->section, true);
|
|
}
|
|
|
|
protected function validateCustomFieldsInput(Request $request): bool
|
|
{
|
|
return $request->filled('key') && is_array($request->key) &&
|
|
(!isset($request->icon) || is_array($request->icon)) &&
|
|
(!isset($request->value) || is_array($request->value));
|
|
}
|
|
|
|
protected function transformCustomFields(Request $request): array
|
|
{
|
|
return collect($request->key)
|
|
->map(function ($key, $index) use ($request) {
|
|
return [
|
|
'icon' => $this->sanitizeField($request->icon[$index] ?? null),
|
|
'key' => $this->sanitizeField($key),
|
|
'value' => $this->sanitizeField($request->value[$index] ?? null),
|
|
];
|
|
})
|
|
->filter(function ($item) {
|
|
return !empty($item['key']);
|
|
})
|
|
->values()
|
|
->all();
|
|
}
|
|
|
|
protected function sanitizeField($value)
|
|
{
|
|
if (is_string($value)) {
|
|
return trim(strip_tags($value));
|
|
}
|
|
|
|
return $value;
|
|
}
|
|
}
|