95 lines
2.9 KiB
PHP
95 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Services\StaticPage;
|
|
|
|
use App\Enums\Block\BlockContentTypeEnum;
|
|
use App\Enums\BlockTypeEnum;
|
|
use App\Models\Block;
|
|
|
|
class BlockService
|
|
{
|
|
/**
|
|
* Get the data object of a given block.
|
|
*
|
|
* @param Block $block The block to retrieve data from.
|
|
* @return object
|
|
*/
|
|
public function getBlockData(Block $block): object
|
|
{
|
|
return $block->data;
|
|
}
|
|
|
|
/**
|
|
* Create and persist a new block with the given validated attributes.
|
|
*
|
|
* @param array $validated Validated input
|
|
*/
|
|
public function store(array $validated): Block
|
|
{
|
|
return Block::create([
|
|
'section_id' => $validated['section_id'],
|
|
'type' => $validated['type'],
|
|
'data' => $validated['data'] ?? [],
|
|
'order' => $validated['order'] ?? 0,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Update a block by merging existing data with new validated attributes.
|
|
* Applies type-specific merge rules before persisting.
|
|
*
|
|
* @param Block $block The block to update.
|
|
* @param array $validated Validated input containing type, data, order.
|
|
* @return Block
|
|
*/
|
|
public function update(Block $block, array $validated): Block
|
|
{
|
|
$existingData = json_decode(json_encode($block->data), true) ?? [];
|
|
$newData = $validated['data'] ?? [];
|
|
|
|
$mergedData = $this->mergeBlockDataByType($block, $existingData, $newData);
|
|
|
|
$block->update([
|
|
'type' => $validated['type'] ?? $block->type,
|
|
'data' => $mergedData,
|
|
'order' => $validated['order'] ?? $block->order,
|
|
]);
|
|
|
|
return $block->fresh();
|
|
}
|
|
|
|
/**
|
|
* Merge existing and new block data according to the block type rules.
|
|
* For redirection blocks, mutually exclusive fields (CTA vs article) are cleared accordingly.
|
|
*
|
|
* @param Block $block The block being updated.
|
|
* @param array $existingData Current block data.
|
|
* @param array $newData Incoming data to merge.
|
|
* @return array
|
|
*/
|
|
private function mergeBlockDataByType(Block $block, array $existingData, array $newData): array
|
|
{
|
|
$mergedData = array_replace_recursive($existingData, $newData);
|
|
|
|
if ($block->type === BlockTypeEnum::redirection) {
|
|
$contentType = BlockContentTypeEnum::make($mergedData['block_type']['value']);
|
|
|
|
if (
|
|
$contentType === BlockContentTypeEnum::Cta
|
|
&& (!empty($mergedData['cta_url']['value']) || !empty($mergedData['cta_label']['value']))
|
|
) {
|
|
$mergedData['article_id']['value'] = null;
|
|
}
|
|
|
|
if (
|
|
$contentType === BlockContentTypeEnum::Actu
|
|
&& !empty($mergedData['article_id']['value'])
|
|
) {
|
|
$mergedData['cta_url']['value'] = null;
|
|
$mergedData['cta_label']['value'] = null;
|
|
}
|
|
}
|
|
|
|
return $mergedData;
|
|
}
|
|
}
|