diff --git a/src/Content/ContentStorageHandler.php b/src/Content/ContentStorageHandler.php index 3b022a8127..5093bb21bb 100644 --- a/src/Content/ContentStorageHandler.php +++ b/src/Content/ContentStorageHandler.php @@ -118,6 +118,33 @@ public function ensure(VersionId $versionId, Language $language): void */ abstract public function exists(VersionId $versionId, Language $language): bool; + /** + * Creates a new storage instance with all the versions + * from the given storage instance. + */ + public static function from(self $fromStorage): static + { + $toStorage = new static( + model: $fromStorage->model() + ); + + // copy all versions from the given storage instance + // and add them to the new storage instance. + foreach ($fromStorage->all() as $versionId => $language) { + $toStorage->create($versionId, $language, $fromStorage->read($versionId, $language)); + } + + return $toStorage; + } + + /** + * Returns the related model + */ + public function model(): ModelWithContent + { + return $this->model; + } + /** * Returns the modification timestamp of a version if it exists */ diff --git a/tests/Content/ContentStorageHandlerTest.php b/tests/Content/ContentStorageHandlerTest.php index 311a6673f1..ca11afca7e 100644 --- a/tests/Content/ContentStorageHandlerTest.php +++ b/tests/Content/ContentStorageHandlerTest.php @@ -329,6 +329,66 @@ public function testDynamicVersionsForUser() $this->assertSame(VersionId::PUBLISHED, $versions[1]->value()); } + /** + * @covers ::from + */ + public function testFrom() + { + $this->setUpMultiLanguage(); + + $handlerA = new PlainTextContentStorageHandler( + model: $this->model + ); + + $versionPublished = VersionId::published(); + $versionChanges = VersionId::changes(); + + $en = $this->app->language('en'); + $de = $this->app->language('de'); + + // create all possible versions + $handlerA->create($versionPublished, $en, $publishedEN = [ + 'title' => 'Published EN' + ]); + + $handlerA->create($versionPublished, $de, $publishedDE = [ + 'title' => 'Published DE' + ]); + + $handlerA->create($versionChanges, $en, $changesEN = [ + 'title' => 'Changes EN' + ]); + + $handlerA->create($versionChanges, $de, $changesDE = [ + 'title' => 'Changes DE' + ]); + + // create a new handler with all the versions from the first one + $handlerB = TestContentStorageHandler::from($handlerA); + + $this->assertNotSame($handlerA, $handlerB); + + $this->assertSame($publishedEN, $handlerB->read($versionPublished, $en)); + $this->assertSame($publishedDE, $handlerB->read($versionPublished, $de)); + + $this->assertSame($changesEN, $handlerB->read($versionChanges, $en)); + $this->assertSame($changesDE, $handlerB->read($versionChanges, $de)); + } + + /** + * @covers ::model + */ + public function testModel() + { + $this->setUpSingleLanguage(); + + $handler = new TestContentStorageHandler( + model: $this->model + ); + + $this->assertSame($this->model, $handler->model()); + } + /** * @covers ::move */