Completed
Push — master ( 73ec48...bf1cd2 )
by Nate
03:32
created

ModelValidator::validateValue()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 27
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 0
cts 18
cp 0
rs 8.439
c 0
b 0
f 0
cc 5
eloc 12
nc 9
nop 1
crap 30
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember
7
 */
8
9
namespace flipbox\ember\validators;
10
11
use yii\base\Model;
12
use yii\validators\Validator;
13
14
/**
15
 * @author Flipbox Factory <[email protected]>
16
 * @since 1.0.0
17
 */
18
class ModelValidator extends Validator
19
{
20
    /**
21
     * @var array list of attribute names that should be validated.
22
     * If this parameter is empty, it means any attribute listed in the applicable
23
     * validation rules should be validated.
24
     */
25
    public $modelAttributeNames = null;
26
27
    /**
28
     * @var bool whether to call [[clearErrors()]] before performing validation
29
     */
30
    public $clearErrors = true;
31
32
    /**
33
     * @var string the scenario used to validate the model.
34
     * Defaults to null, meaning no limit.
35
     * @see tooSmall for the customized message for a file that is too small.
36
     */
37
    public $scenario;
38
39
    /**
40
     * Validates a value.
41
     * A validator class can implement this method to support data validation out of the context of a data model.
42
     * @param mixed $value the data value to be validated.
43
     * @return array|null the error message and the parameters to be inserted into the error message.
44
     * Null should be returned if the data is valid.
45
     */
46
    protected function validateValue($value)
47
    {
48
        if (!$value instanceof Model) {
49
            return null;
50
        }
51
52
        // Current scenario
53
        $defaultScenarios = $value->getScenario();
54
55
        // Change to validation scenario
56
        if ($this->scenario) {
57
            $value->setScenario($this->scenario);
58
        }
59
60
        // Validate
61
        $errors = null;
62
        if (!$value->validate($this->modelAttributeNames, $this->clearErrors)) {
63
            $errors = [$this->message, []];
64
        }
65
66
        // Revert back to prior scenario
67
        if ($this->scenario) {
68
            $value->setScenario($defaultScenarios);
69
        }
70
71
        return $errors;
72
    }
73
}
74