From fc3f318b83fb19d3dedabdfd0dbc0346df71d539 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vencel=20K=C3=A1tai?= Date: Tue, 10 Dec 2024 20:42:42 +0100 Subject: [PATCH] Fix attribute mutators --- src/HasTranslations.php | 2 +- tests/TranslatableTest.php | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/HasTranslations.php b/src/HasTranslations.php index 2eddb13..b6ce506 100644 --- a/src/HasTranslations.php +++ b/src/HasTranslations.php @@ -71,7 +71,7 @@ public function translate(string $key, string $locale = '', bool $useFallbackLoc public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true): mixed { // if column value is `null` then we have nothing to do, return `null` - if (is_null(parent::getAttributeValue($key))) { + if (is_null(parent::getAttributeFromArray($key))) { return null; } diff --git a/tests/TranslatableTest.php b/tests/TranslatableTest.php index 3976048..6196882 100644 --- a/tests/TranslatableTest.php +++ b/tests/TranslatableTest.php @@ -1,5 +1,6 @@ getTranslations('field_with_mutator'))->toEqual($translations); }); +it('uses the attribute to mutate the translated value', function () { + $testModel = (new class () extends TestModel { + public $mutatedValues = []; + + protected function name(): Attribute + { + return Attribute::get(function ($value) { + $this->mutatedValues[] = $value; + + return 'mutated'; + }); + } + }); + + $testModel->name = 'hello'; + $testModel->save(); + + expect($testModel->name)->toEqual('mutated'); + expect($testModel->mutatedValues)->toBe(['hello']); +}); + it('can translate a field based on the translations of another one', function () { $testModel = (new class () extends TestModel { public function setOtherFieldAttribute($value, $locale = 'en')