|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Yuges\Contentable\Actions; |
| 4 | + |
| 5 | +use Illuminate\Support\Collection; |
| 6 | +use Yuges\Contentable\Models\Block; |
| 7 | +use Yuges\Contentable\Models\Content; |
| 8 | + |
| 9 | +class SyncBlocksAction |
| 10 | +{ |
| 11 | + public function __construct( |
| 12 | + protected Content $content |
| 13 | + ) { |
| 14 | + } |
| 15 | + |
| 16 | + public static function create(Content $content): self |
| 17 | + { |
| 18 | + return new static($content); |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * @param Collection<array-key, Block> $blocks |
| 23 | + */ |
| 24 | + public function execute(Collection $blocks): array |
| 25 | + { |
| 26 | + $changes = [ |
| 27 | + 'created' => [], 'deleted' => [], 'updated' => [], |
| 28 | + ]; |
| 29 | + |
| 30 | + $models = $this->content->blocks()->get(); |
| 31 | + |
| 32 | + $ids = [ |
| 33 | + 'current' => $models->modelKeys(), |
| 34 | + 'records' => $blocks->map(fn (Block $block) => $block->getKey())->filter()->toArray(), |
| 35 | + ]; |
| 36 | + |
| 37 | + $deleted = array_diff($ids['current'], $ids['records']); |
| 38 | + |
| 39 | + if (count($deleted)) { |
| 40 | + $models->filter(fn (Block $block) => in_array($block->getKey(), $deleted))->each->delete(); |
| 41 | + |
| 42 | + $changes['deleted'] = $deleted; |
| 43 | + } |
| 44 | + |
| 45 | + $blocks->each(function (Block $block) use ($ids, $models, &$changes) { |
| 46 | + $block->content_id = $this->content->getKey(); |
| 47 | + |
| 48 | + if (! in_array($block->getKey(), $ids['current'])) { |
| 49 | + $block->save(); |
| 50 | + |
| 51 | + $changes['created'][] = $block->getKey(); |
| 52 | + } else { |
| 53 | + $model = $models->find($block)->first(); |
| 54 | + |
| 55 | + $model->setRawAttributes( |
| 56 | + array_merge( |
| 57 | + $model->getAttributes(), |
| 58 | + $block->getAttributes() |
| 59 | + ) |
| 60 | + ); |
| 61 | + |
| 62 | + if ($model->isDirty()) { |
| 63 | + $model->save(); |
| 64 | + |
| 65 | + $changes['updated'][] = $block->getKey(); |
| 66 | + } |
| 67 | + } |
| 68 | + }); |
| 69 | + |
| 70 | + return $changes; |
| 71 | + } |
| 72 | +} |
0 commit comments