Json   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 40
ccs 0
cts 12
cp 0
rs 10
c 0
b 0
f 0
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A decode() 0 11 4
A decodeIfJson() 0 7 2
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