@@ -16,6 +16,21 @@ public function testValidateAttributeWithArray(): void
16
16
$ this ->assertTrue ((new Item (['data_json ' => ['a ' => 'b ' ]]))->validate ());
17
17
}
18
18
19
+ public function testAllowNull (): void
20
+ {
21
+ $ this ->assertTrue ((new Item (['data_json ' => null , 'scenario ' => Item::SCENARIO_ALLOW_EMPTY ]))->validate ());
22
+ }
23
+
24
+ public function testAllowEmptyString (): void
25
+ {
26
+ $ this ->assertTrue ((new Item (['data_json ' => '' , 'scenario ' => Item::SCENARIO_ALLOW_EMPTY ]))->validate ());
27
+ }
28
+
29
+ public function testAllowEmptyArray (): void
30
+ {
31
+ $ this ->assertTrue ((new Item (['data_json ' => [], 'scenario ' => Item::SCENARIO_ALLOW_EMPTY ]))->validate ());
32
+ }
33
+
19
34
public function testValueIsOriginalTypeAfterValidationForString (): void
20
35
{
21
36
$ item = new Item (['data_json ' => '{"a": "b"} ' ]);
@@ -33,6 +48,19 @@ public function testValueIsOriginalTypeAfterValidationForArray(): void
33
48
34
49
class Item extends Model
35
50
{
51
+
52
+ public const SCENARIO_ALLOW_EMPTY = 'allowEmpty ' ;
53
+
54
+ /**
55
+ * @inheritdoc
56
+ */
57
+ public function scenarios (): array
58
+ {
59
+ $ scenarios = parent ::scenarios ();
60
+ $ scenarios [self ::SCENARIO_ALLOW_EMPTY ] = ['data_json ' ];
61
+ return $ scenarios ;
62
+ }
63
+
36
64
/**
37
65
* @var string|array
38
66
*/
@@ -52,4 +80,15 @@ public function behaviors(): array
52
80
];
53
81
return $ behaviors ;
54
82
}
83
+
84
+ /**
85
+ * @inheritdoc
86
+ */
87
+ public function rules (): array
88
+ {
89
+ $ rules = parent ::rules ();
90
+ $ rules [] = [['data_json ' ], 'required ' , 'except ' => 'allowEmpty ' ];
91
+ $ rules [] = [['data_json ' ], 'safe ' , 'on ' => 'allowEmpty ' ];
92
+ return $ rules ;
93
+ }
55
94
}
0 commit comments