Completed
Push — master ( e9577f...1f5fd8 )
by Dmitry
05:23
created

NestedModelValidator::validateValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
ccs 0
cts 6
cp 0
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
crap 12
1
<?php
2
3
namespace hiapi\validators;
4
5
use yii\base\InvalidConfigException;
6
use yii\base\InvalidParamException;
7
use yii\base\Model;
8
use yii\validators\Validator;
9
10
class NestedModelValidator extends Validator
11
{
12
    public $modelClass;
13
14
    public function init()
15
    {
16
        if (!isset($this->modelClass)) {
17
            throw new InvalidConfigException('Property "modelClass" is missing');
18
        }
19
20
        parent::init();
21
    }
22
23
    public function validateAttribute($model, $attribute)
24
    {
25
        $oldValue = $model->$attribute;
26
27
        $newModel = $this->createModel($model->$attribute);
28
        $model->$attribute = $newModel;
29
30
        $validationResult = parent::validateAttribute($model, $attribute);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $validationResult is correct as parent::validateAttribute($model, $attribute) (which targets yii\validators\Validator::validateAttribute()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
31
        if ($validationResult === null) {
32
            return null;
33
        }
34
35
        $model->$attribute = $oldValue;
36
37
        return $validationResult;
38
    }
39
40
    private function createModel($data)
41
    {
42
        $model = new $this->modelClass;
43
        $model->load($data, '');
44
45
        return $model;
46
    }
47
48
    /**
49
     * @param Model $model
50
     * @return array|null
51
     */
52
    protected function validateValue($model)
53
    {
54
        if (!$model instanceof Model) {
55
            throw new InvalidParamException('Passed value must be instance of Model');
56
        }
57
58
        if (!$model->validate()) {
59
            return [reset($model->getFirstErrors()), []]; // todo: return more than one error
0 ignored issues
show
Bug introduced by
$model->getFirstErrors() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
60
        }
61
62
        return null;
63
    }
64
}
65