From 1995ec2d89313119c6edf7c6c5c82d9a789f7b36 Mon Sep 17 00:00:00 2001 From: Bastian Allgeier Date: Wed, 13 Nov 2024 14:01:25 +0100 Subject: [PATCH] Add the latest version of a translation automatically --- src/Content/Version.php | 14 +++++++++++++ tests/Content/VersionTest.php | 38 +++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/Content/Version.php b/src/Content/Version.php index 93228f09ff..ac622c64c0 100644 --- a/src/Content/Version.php +++ b/src/Content/Version.php @@ -95,6 +95,20 @@ public function create( Language|string $language = 'default' ): void { $language = Language::ensure($language); + $latest = $this->model->version(VersionId::latest()); + + // if the latest version of the translation does not exist yet, + // we have to copy over the content from the default language first. + if ( + $this->isLatest() === false && + $language->isDefault() === false && + $latest->exists($language) === false + ) { + $latest->create( + fields: $latest->read(Language::ensure('default')), + language: $language + ); + } // check if creating is allowed VersionRules::create($this, $fields, $language); diff --git a/tests/Content/VersionTest.php b/tests/Content/VersionTest.php index f59d12b50d..001a112819 100644 --- a/tests/Content/VersionTest.php +++ b/tests/Content/VersionTest.php @@ -188,6 +188,44 @@ public function testCreateMultiLanguage(): void $this->assertContentFileExists('de'); } + /** + * @covers ::create + */ + public function testCreateMultiLanguageWhenLatestTranslationIsMissing(): void + { + $this->setUpMultiLanguage(); + + $latest = new Version( + model: $this->model, + id: VersionId::latest() + ); + + $changes = new Version( + model: $this->model, + id: VersionId::changes() + ); + + $this->assertContentFileDoesNotExist('en', $latest->id()); + $this->assertContentFileDoesNotExist('en', $changes->id()); + $this->assertContentFileDoesNotExist('de', $latest->id()); + $this->assertContentFileDoesNotExist('de', $changes->id()); + + // create the latest version for the default translation + $latest->save([ + 'title' => 'Test' + ], $this->app->language('en')); + + // create a changes version in the other language + $changes->save([ + 'title' => 'Translated Test', + ], $this->app->language('de')); + + $this->assertContentFileExists('en', $latest->id()); + $this->assertContentFileDoesNotExist('en', $changes->id()); + $this->assertContentFileExists('de', $latest->id()); + $this->assertContentFileExists('de', $changes->id()); + } + /** * @covers ::create */