File tree Expand file tree Collapse file tree 2 files changed +30
-2
lines changed Expand file tree Collapse file tree 2 files changed +30
-2
lines changed Original file line number Diff line number Diff line change 31
31
*
32
32
* @property Model $owner
33
33
* @property string[] $_convertedAttributes
34
+ * @property bool $alwaysConvertBackToOriginalType
34
35
*/
35
36
class JsonAttributeBehavior extends AttributeBehavior
36
37
{
@@ -41,6 +42,13 @@ class JsonAttributeBehavior extends AttributeBehavior
41
42
*/
42
43
private array $ _convertedAttributes = [];
43
44
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
+
44
52
/**
45
53
* @inheritdoc
46
54
*/
@@ -77,10 +85,10 @@ public function beforeValidate(): void
77
85
*/
78
86
public function afterValidate (): void
79
87
{
80
- if ($ this ->owner ->hasErrors ()) {
88
+ if ($ this ->owner ->hasErrors () || $ this -> alwaysConvertBackToOriginalType ) {
81
89
foreach ($ this ->attributes as $ attribute ) {
82
90
// 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 )) {
84
92
// Convert the attribute back to its original type.
85
93
$ this ->owner ->$ attribute = Json::encode ($ this ->owner ->$ attribute );
86
94
// Remove the attribute from the list of converted attributes.
Original file line number Diff line number Diff line change @@ -44,6 +44,13 @@ public function testValueIsOriginalTypeAfterValidationForArray(): void
44
44
$ item ->validate ();
45
45
$ this ->assertIsArray ($ item ->data_json );
46
46
}
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
+ }
47
54
}
48
55
49
56
class Item extends Model
@@ -92,3 +99,16 @@ public function rules(): array
92
99
return $ rules ;
93
100
}
94
101
}
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
+ }
You can’t perform that action at this time.
0 commit comments