Json::decode()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 3
nop 2
dl 0
loc 11
ccs 0
cts 8
cp 0
crap 20
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * SEOmatic plugin for Craft CMS
4
 *
5
 * A turnkey SEO implementation for Craft CMS that is comprehensive, powerful,
6
 * and flexible
7
 *
8
 * @link      https://nystudio107.com
9
 * @copyright Copyright (c) 2017 nystudio107
10
 */
11
12
namespace nystudio107\seomatic\helpers;
13
14
use yii\base\InvalidArgumentException;
15
16
/**
17
 * @author    nystudio107
18
 * @package   Seomatic
19
 * @since     3.0.0
20
 */
21
class Json extends \yii\helpers\Json
22
{
23
    // Public Methods
24
    // =========================================================================
25
26
    /**
27
     * Decodes the given JSON string into a PHP data structure, only if the string is valid JSON.
28
     *
29
     * @param string $str The string to be decoded, if it's valid JSON.
30
     * @param bool $asArray Whether to return objects in terms of associative arrays.
31
     * @return mixed The PHP data, or the given string if it wasn’t valid JSON.
32
     */
33
    public static function decodeIfJson(string $str, bool $asArray = true)
34
    {
35
        try {
36
            return static::decode($str, $asArray);
37
        } catch (InvalidArgumentException $e) {
38
            // Wasn't JSON
39
            return $str;
40
        }
41
    }
42
43
    /**
44
     * Decodes the given JSON string into a PHP data structure.
45
     * @param array|string|null $json the JSON string to be decoded
46
     * @param bool $asArray whether to return objects in terms of associative arrays.
47
     * @return mixed the PHP data
48
     * @throws InvalidArgumentException if there is any decoding error
49
     */
50
    public static function decode($json, $asArray = true)
51
    {
52
        if (is_array($json)) {
53
            throw new InvalidArgumentException('Invalid JSON data.');
54
        } elseif ($json === null || $json === '') {
55
            return null;
56
        }
57
        $decode = json_decode((string)$json, $asArray, 512, JSON_BIGINT_AS_STRING);
58
        static::handleJsonError(json_last_error());
59
60
        return $decode;
61
    }
62
}
63