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
![]() |
|||
56 | } |
||
57 | } |
||
58 |