Skip to content

Commit ba7e642

Browse files
committed
Check invalid value
1 parent 18f5a10 commit ba7e642

File tree

2 files changed

+24
-13
lines changed

2 files changed

+24
-13
lines changed

src/LinkManyBehavior.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Yii;
66
use yii\base\Behavior;
7+
use yii\base\InvalidArgumentException;
78
use yii\base\InvalidConfigException;
89
use yii\base\UnknownPropertyException;
910
use yii\db\ActiveRecord;
@@ -123,7 +124,7 @@ public function afterValidate()
123124
}
124125

125126
$errors = [];
126-
$models = isset($this->_inserteds[$name]) ? $this->_inserteds[$name] : [];
127+
$models = ArrayHelper::getValue($this->_inserteds, $name, []);
127128

128129
foreach ($models as $model) {
129130
if (!$model->validate()) {
@@ -149,6 +150,10 @@ public function __set($name, $value)
149150
try {
150151
parent::__set($name, $value);
151152
} catch (UnknownPropertyException $exception) {
153+
if (!is_array($value)) {
154+
throw new InvalidArgumentException("The '$name' property must be an array");
155+
}
156+
152157
$definition = $this->findDefinition($name);
153158
if ($definition !== null) {
154159
$this->prepareRelation($definition, [$name => $value]);

tests/LinkManyBehaviorTest.php

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,41 @@
44

55
use solutosoft\linkmany\LinkManyBehavior;
66
use solutosoft\linkmany\tests\models\Post;
7-
use solutosoft\linkmany\tests\models\Tag;
87

9-
//use solutosoft\linkmany\tests\models\PostLanguage;
10-
//use solutosoft\linkmany\tests\models\Tag;
118

129
class LinkManyBehaviorTest extends TestCase
1310
{
14-
public function testInitException()
11+
public function testInitSuccess()
1512
{
16-
$this->setExpectedException('\yii\base\InvalidConfigException');
17-
1813
new LinkManyBehavior([
1914
'relations' => [
20-
['invalid' => true]
15+
'relation_1',
16+
'relation_2' => [
17+
'formName' => 'test'
18+
]
2119
]
2220
]);
2321
}
2422

25-
public function testInitSuccess()
23+
public function testInitException()
2624
{
25+
$this->setExpectedException('\yii\base\InvalidConfigException');
26+
2727
new LinkManyBehavior([
2828
'relations' => [
29-
'relation_1',
30-
'relation_2' => [
31-
'formName' => 'test'
32-
]
29+
['invalid' => true]
3330
]
3431
]);
3532
}
3633

34+
public function testInvalidRelationValue()
35+
{
36+
$this->setExpectedException('\yii\base\InvalidArgumentException');
37+
38+
$post = new Post();
39+
$post->comments = null;
40+
}
41+
3742
public function testFillNewRecord()
3843
{
3944
$post = new Post();
@@ -234,6 +239,7 @@ public function testSetRelation()
234239
$post->tags = [1];
235240

236241
$post->save();
242+
$post->refresh();
237243
$this->assertCount(1, $post->tags);
238244
}
239245
}

0 commit comments

Comments
 (0)