Completed
Pull Request — master (#15527)
by Nikolay
32:09 queued 29:07
created

JsonValidator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 39
ccs 11
cts 11
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 8 2
A validateValue() 0 11 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\validators;
9
10
use Yii;
11
use yii\helpers\Json;
12
13
/**
14
 * This validator checks if the attribute value is a valid JSON string.
15
 *
16
 * @since 2.0.14
17
 */
18
class JsonValidator extends Validator
19
{
20
    /**
21
     * @var string user-defined error message which is used when the validation fails.
22
     *
23
     * You may use the following placeholders in the message:
24
     *
25
     * - `{attribute}`: the label of the attribute being validated
26
     * - `{value}`: the value of the attribute being validated
27
     */
28
    public $message;
29
30
    /**
31
     * @inheritdoc
32
     */
33 22
    public function init()
34
    {
35 22
        parent::init();
36
37 22
        if ($this->message === null) {
38 22
            $this->message = Yii::t('yii', '{attribute} must be a valid JSON string.');
39
        }
40 22
    }
41
42
    /**
43
     * @inheritdoc
44
     */
45 22
    protected function validateValue($value)
46
    {
47 22
        $result = null;
48
49 22
        $isValid = Json::validate($value);
50 22
        if ($isValid === false) {
51 11
            $result = [$this->message, []];
52
        }
53
54 22
        return $result;
55
    }
56
}
57