81 lines
2.5 KiB
PHP
81 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Traits\Models;
|
|
|
|
use App\Enums\InputType;
|
|
use App\Lib\Helpers\ToolboxHelper;
|
|
use App\Lib\Helpers\FileStorageHelper;
|
|
|
|
trait MiniCrudModel
|
|
{
|
|
/**
|
|
* Fill the model with an array of attributes.
|
|
*
|
|
* @param array $attributes
|
|
* @return void
|
|
* @throws \Illuminate\Database\Eloquent\MassAssignmentException If fill prop is not allowed.
|
|
* @phpcs:disable Squiz.Commenting.FunctionComment.EmptyThrows
|
|
*/
|
|
public function fill(array $attributes)
|
|
{
|
|
parent::fill($attributes);
|
|
if (isset($attributes['data'])) {
|
|
$this->setData($attributes['data']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Set a specific prop
|
|
*
|
|
* @param array $data
|
|
* @return void
|
|
*/
|
|
private function setData(array $data): void
|
|
{
|
|
$attrs = $this->attributes;
|
|
if (isset($attrs['data'])) {
|
|
unset($attrs['data']);
|
|
}
|
|
$data = $this->serializeData($data);
|
|
$this->setRawAttributes(\array_merge_recursive(
|
|
$attrs,
|
|
['data' => $data]
|
|
));
|
|
}
|
|
|
|
/**
|
|
* Serialize properties
|
|
*
|
|
* @param array $data
|
|
* @return string
|
|
* @throws \ErrorException If input type is no handled.
|
|
* @throws \Illuminate\Validation\ValidationException If url is a bo url.
|
|
* @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
|
|
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
|
|
*/
|
|
private function serializeData(array $data): string
|
|
{
|
|
foreach ($data as $o => $input) {
|
|
switch ($input['inputType']->value ?? $input['inputType']['value']) {
|
|
case InputType::image()->value:
|
|
$data[$o]['value'] = FileStorageHelper::storeFile($this, $input['value']);
|
|
break;
|
|
case InputType::boolean()->value:
|
|
case InputType::text()->value:
|
|
case InputType::number()->value:
|
|
case InputType::string()->value:
|
|
case InputType::videoVimeo()->value:
|
|
break;
|
|
case InputType::url()->value:
|
|
ToolboxHelper::assertNoInternalBoUrls('content', $input['value']);
|
|
break;
|
|
default:
|
|
throw new \ErrorException(sprintf(
|
|
'Unknown input Type %s',
|
|
$input['inputType']->label ?? $input['inputType']['label']
|
|
));
|
|
} //end switch
|
|
} //end foreach
|
|
return json_encode($data);
|
|
}
|
|
}
|