Completed
Push — master ( 8e9c3c...46228f )
by Rick
07:43 queued 05:16
created

Json::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 7
nc 3
nop 1
crap 3
1
<?php
2
/**
3
 * Particle.
4
 *
5
 * @link      http://github.com/particle-php for the canonical source repository
6
 * @copyright Copyright (c) 2005-2015 Particle (http://particle-php.com)
7
 * @license   https://github.com/particle-php/validator/blob/master/LICENSE New BSD License
8
 */
9
namespace Particle\Validator\Rule;
10
11
use Particle\Validator\Rule;
12
13
/**
14
 * This rule is for validating if a value is a valid JSON string.
15
 *
16
 * @package Particle\Validator\Rule
17
 */
18
class Json extends Rule
19
{
20
    /**
21
     * A constant that will be used when the value is not a valid JSON string.
22
     */
23
    const INVALID_FORMAT = 'Json::INVALID_VALUE';
24
25
    /**
26
     * The message templates which can be returned by this validator.
27
     *
28
     * @var array
29
     */
30
    protected $messageTemplates = [
31
        self::INVALID_FORMAT => '{{ name }} must be a valid JSON string',
32
    ];
33
34
    /**
35
     * Validates if the value is a valid JSON string.
36
     *
37
     * @param mixed $value
38
     * @return bool
39
     */
40 11
    public function validate($value)
41
    {
42 11
        if (!is_string($value)) {
43 1
            return $this->error(self::INVALID_FORMAT);
44
        }
45
46 10
        json_decode($value);
47 10
        if (json_last_error() !== JSON_ERROR_NONE) {
48 3
            return $this->error(self::INVALID_FORMAT);
49
        }
50
51 7
        return true;
52
    }
53
}
54