first change
This commit is contained in:
71
Modules/CCMS/app/Traits/UpdateCustomFields.php
Normal file
71
Modules/CCMS/app/Traits/UpdateCustomFields.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user