Completed
Pull Request — 1.x (#13)
by
unknown
17:47
created

JsonPaser::parse()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 4
nc 3
nop 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: loic
5
 * Date: 06/11/18
6
 * Time: 11:03
7
 */
8
9
namespace MetaHydrator\Parser;
10
11
12
use MetaHydrator\Exception\ParsingException;
13
14
class JsonPaser extends AbstractParser
15
{
16
    /**
17
     * @param string $value
18
     * @return mixed
19
     * @throws ParsingException
20
     */
21
    public function jsonValid($value) {
22
        $result = json_decode($value);
23
24
        switch (json_last_error()) {
25
            case JSON_ERROR_NONE:
26
                $error = '';
27
                break;
28
            case JSON_ERROR_DEPTH:
29
                $error = 'The maximum stack depth has been exceeded.';
30
                break;
31
            case JSON_ERROR_STATE_MISMATCH:
32
                $error = 'Invalid or malformed JSON.';
33
                break;
34
            case JSON_ERROR_CTRL_CHAR:
35
                $error = 'Control character error, possibly incorrectly encoded.';
36
                break;
37
            case JSON_ERROR_SYNTAX:
38
                $error = 'Syntax error, malformed JSON.';
39
                break;
40
            case JSON_ERROR_UTF8:
41
                $error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
42
                break;
43
            case JSON_ERROR_RECURSION:
44
                $error = 'One or more recursive references in the value to be encoded.';
45
                break;
46
            case JSON_ERROR_INF_OR_NAN:
47
                $error = 'One or more NAN or INF values in the value to be encoded.';
48
                break;
49
            case JSON_ERROR_UNSUPPORTED_TYPE:
50
                $error = 'A value of a type that cannot be encoded was given.';
51
                break;
52
            default:
53
                $error = 'Unknown JSON error occured.';
54
                break;
55
        }
56
57
        if ($error !== '') {
58
            throw new ParsingException($error);
59
        }
60
61
        return $result;
62
    }
63
64
    /**
65
     * @param string $rawValue
66
     * @return mixed|null
67
     * @throws \MetaHydrator\Exception\ParsingException
68
     */
69
    public function parse($rawValue)
70
    {
71
        if ($rawValue === null || $rawValue === '') {
72
            return null;
73
        } else {
74
            $value = filter_var($rawValue, FILTER_CALLBACK, array('options' => 'jsonValid'));
75
            if ($value === null) {
76
                $this->throw();
77
            }
78
            return $value;
79
        }
80
    }
81
}
82