Json::getValue()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 0
cts 3
cp 0
rs 10
cc 1
nc 1
nop 2
crap 2
1
<?php
2
/*******************************************************************************
3
 *  This file is part of the GraphQL Bundle package.
4
 *
5
 *  (c) YnloUltratech <[email protected]>
6
 *
7
 *  For the full copyright and license information, please view the LICENSE
8
 *  file that was distributed with this source code.
9
 ******************************************************************************/
10
11
namespace Ynlo\GraphQLBundle\Util;
12
13
use Symfony\Component\HttpFoundation\Response;
14
use function JmesPath\search;
15
16
/**
17
 * JSON Utility class to work with json
18
 */
19
class Json
20
{
21
    /**
22
     * Get value inside given json using expression path
23
     *
24
     * Example: getValue($json, 'user.username')
25
     * Example: getValue($json, 'pos[0].title')
26
     *
27
     * @see `JMESPath Tutorial <http://jmespath.org/tutorial.html>
28
     * @see `JMESPath Grammar <http://jmespath.org/specification.html#grammar>
29
     *
30
     * @param string|array|Response $json
31
     * @param string                $path
32
     *
33
     * @return mixed|null
34
     */
35
    public static function getValue($json, string $path)
36
    {
37
        return search($path, Json::decode($json));
38
    }
39
40
    /**
41
     * Decode a json, unlike the build-in
42
     * decode, support a Response as argument
43
     *
44
     * @param string|array|Response $json
45
     * @param boolean               $assoc
46
     *
47
     * @return mixed
48
     */
49
    public static function decode($json, $assoc = false)
50
    {
51
        if ($json instanceof Response) {
52
            return json_decode($json->getContent(), $assoc);
53
        }
54
55
        return json_decode($json, $assoc);
0 ignored issues
show
Bug introduced by
It seems like $json can also be of type array; however, parameter $json of json_decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

55
        return json_decode(/** @scrutinizer ignore-type */ $json, $assoc);
Loading history...
56
    }
57
}
58