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. */ 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. */ private function mergeBlockDataByType(Block $block, array $existingData, array $newData): array { $mergedData = array_replace_recursive($existingData, $newData); $visibility = $mergedData['visibility']['value'] ?? true; if (! $visibility) { return $mergedData; } 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; } }