Skip to content

Commit ce73ff3

Browse files
committed
Added property that always converts back to the original type
1 parent 8006bf0 commit ce73ff3

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/behaviors/JsonAttributeBehavior.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
*
3232
* @property Model $owner
3333
* @property string[] $_convertedAttributes
34+
* @property bool $alwaysConvertBackToOriginalType
3435
*/
3536
class JsonAttributeBehavior extends AttributeBehavior
3637
{
@@ -41,6 +42,13 @@ class JsonAttributeBehavior extends AttributeBehavior
4142
*/
4243
private array $_convertedAttributes = [];
4344

45+
/**
46+
* Whether to always convert the attribute back to its original type, even if no validation errors occur.
47+
*
48+
* @var bool
49+
*/
50+
public bool $alwaysConvertBackToOriginalType = false;
51+
4452
/**
4553
* @inheritdoc
4654
*/
@@ -77,10 +85,10 @@ public function beforeValidate(): void
7785
*/
7886
public function afterValidate(): void
7987
{
80-
if ($this->owner->hasErrors()) {
88+
if ($this->owner->hasErrors() || $this->alwaysConvertBackToOriginalType) {
8189
foreach ($this->attributes as $attribute) {
8290
// If the attribute was originally a string, convert it back to a string.
83-
if (in_array($this->owner->$attribute, $this->_convertedAttributes)) {
91+
if (in_array($attribute, $this->_convertedAttributes)) {
8492
// Convert the attribute back to its original type.
8593
$this->owner->$attribute = Json::encode($this->owner->$attribute);
8694
// Remove the attribute from the list of converted attributes.

tests/JsonAttributeBehaviorTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@ public function testValueIsOriginalTypeAfterValidationForArray(): void
4444
$item->validate();
4545
$this->assertIsArray($item->data_json);
4646
}
47+
48+
public function testValueIsOriginalTypeAfterValidationForStringButConvertBackToString(): void
49+
{
50+
$item = new Item2(['data_json' => '{"a": "b"}']);
51+
$item->validate();
52+
$this->assertIsString($item->data_json);
53+
}
4754
}
4855

4956
class Item extends Model
@@ -92,3 +99,16 @@ public function rules(): array
9299
return $rules;
93100
}
94101
}
102+
103+
class Item2 extends Item {
104+
105+
/**
106+
* @inheritdoc
107+
*/
108+
public function behaviors(): array
109+
{
110+
$behaviors = parent::behaviors();
111+
$behaviors['json-attribute']['alwaysConvertBackToOriginalType'] = true;
112+
return $behaviors;
113+
}
114+
}

0 commit comments

Comments
 (0)