diff --git a/src/LinkManyBehavior.php b/src/LinkManyBehavior.php index 2d2ddb3..09f10e6 100644 --- a/src/LinkManyBehavior.php +++ b/src/LinkManyBehavior.php @@ -4,6 +4,7 @@ use Yii; use yii\base\Behavior; +use yii\base\InvalidArgumentException; use yii\base\InvalidConfigException; use yii\base\UnknownPropertyException; use yii\db\ActiveRecord; @@ -123,7 +124,7 @@ public function afterValidate() } $errors = []; - $models = isset($this->_inserteds[$name]) ? $this->_inserteds[$name] : []; + $models = ArrayHelper::getValue($this->_inserteds, $name, []); foreach ($models as $model) { if (!$model->validate()) { @@ -149,6 +150,10 @@ public function __set($name, $value) try { parent::__set($name, $value); } catch (UnknownPropertyException $exception) { + if (!is_array($value)) { + throw new InvalidArgumentException("The '$name' property must be an array"); + } + $definition = $this->findDefinition($name); if ($definition !== null) { $this->prepareRelation($definition, [$name => $value]); diff --git a/tests/LinkManyBehaviorTest.php b/tests/LinkManyBehaviorTest.php index f9b4677..dea56cc 100644 --- a/tests/LinkManyBehaviorTest.php +++ b/tests/LinkManyBehaviorTest.php @@ -4,36 +4,41 @@ use solutosoft\linkmany\LinkManyBehavior; use solutosoft\linkmany\tests\models\Post; -use solutosoft\linkmany\tests\models\Tag; -//use solutosoft\linkmany\tests\models\PostLanguage; -//use solutosoft\linkmany\tests\models\Tag; class LinkManyBehaviorTest extends TestCase { - public function testInitException() + public function testInitSuccess() { - $this->setExpectedException('\yii\base\InvalidConfigException'); - new LinkManyBehavior([ 'relations' => [ - ['invalid' => true] + 'relation_1', + 'relation_2' => [ + 'formName' => 'test' + ] ] ]); } - public function testInitSuccess() + public function testInitException() { + $this->setExpectedException('\yii\base\InvalidConfigException'); + new LinkManyBehavior([ 'relations' => [ - 'relation_1', - 'relation_2' => [ - 'formName' => 'test' - ] + ['invalid' => true] ] ]); } + public function testInvalidRelationValue() + { + $this->setExpectedException('\yii\base\InvalidArgumentException'); + + $post = new Post(); + $post->comments = null; + } + public function testFillNewRecord() { $post = new Post(); @@ -234,6 +239,7 @@ public function testSetRelation() $post->tags = [1]; $post->save(); + $post->refresh(); $this->assertCount(1, $post->tags); } } \ No newline at end of file