diff --git a/src/Concerns/HasDrafts.php b/src/Concerns/HasDrafts.php index cb3992f..5db2d61 100644 --- a/src/Concerns/HasDrafts.php +++ b/src/Concerns/HasDrafts.php @@ -192,40 +192,7 @@ public function setLive(): void $published->setCurrent(); $published->saveQuietly(); - collect($this->getDraftableRelations())->each(function (string $relationName) use ($published) { - $relation = $published->{$relationName}(); - switch (true) { - case $relation instanceof HasOne: - if ($related = $this->{$relationName}) { - $replicated = $related->replicate(); - - $method = method_exists($replicated, 'getDraftableAttributes') - ? 'getDraftableAttributes' - : 'getAttributes'; - - $published->{$relationName}()->create($replicated->$method()); - } - - break; - case $relation instanceof HasMany: - $this->{$relationName}()->get()->each(function ($model) use ($published, $relationName) { - $replicated = $model->replicate(); - - $method = method_exists($replicated, 'getDraftableAttributes') - ? 'getDraftableAttributes' - : 'getAttributes'; - - $published->{$relationName}()->create($replicated->$method()); - }); - - break; - case $relation instanceof MorphToMany: - case $relation instanceof BelongsToMany: - $published->{$relationName}()->sync($this->{$relationName}()->pluck('id')); - - break; - } - }); +; $this->replicateAndAssociateDraftableRelations($published); }); $this->{$this->getIsPublishedColumn()} = false; @@ -235,6 +202,44 @@ public function setLive(): void $this->shouldCreateRevision = false; } + public function replicateAndAssociateDraftableRelations(Model $published): void + { + collect($this->getDraftableRelations())->each(function (string $relationName) use ($published) { + $relation = $published->{$relationName}(); + switch (true) { + case $relation instanceof HasOne: + if ($related = $this->{$relationName}) { + $replicated = $related->replicate(); + + $method = method_exists($replicated, 'getDraftableAttributes') + ? 'getDraftableAttributes' + : 'getAttributes'; + + $published->{$relationName}()->create($replicated->$method()); + } + + break; + case $relation instanceof HasMany: + $this->{$relationName}()->get()->each(function ($model) use ($published, $relationName) { + $replicated = $model->replicate(); + + $method = method_exists($replicated, 'getDraftableAttributes') + ? 'getDraftableAttributes' + : 'getAttributes'; + + $published->{$relationName}()->create($replicated->$method()); + }); + + break; + case $relation instanceof MorphToMany: + case $relation instanceof BelongsToMany: + $published->{$relationName}()->sync($this->{$relationName}()->pluck('id')); + + break; + } + }); + } + public function getDraftableRelations(): array { return property_exists($this, 'draftableRelations') ? $this->draftableRelations : [];