JsonHelper::encode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 4
c 1
b 0
f 1
dl 0
loc 9
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Smoren\EncryptionTools\Helpers;
4
5
use Smoren\EncryptionTools\Exceptions\JsonException;
6
7
/**
8
 * Class JsonHelper
9
 * @author Smoren <[email protected]>
10
 */
11
class JsonHelper
12
{
13
    /**
14
     * Converts value to JSON format
15
     * @param mixed $value
16
     * @return string
17
     * @throws JsonException
18
     */
19
    public static function encode($value): string
20
    {
21
        $result = json_encode($value);
22
        if($error = json_last_error()) {
23
            throw new JsonException(json_last_error_msg(), $error);
24
        }
25
26
        /** @var string $result */
27
        return $result;
28
    }
29
30
    /**
31
     * Parses JSON to PHP value
32
     * @param string $json
33
     * @return mixed
34
     * @throws JsonException
35
     */
36
    public static function decode(string $json)
37
    {
38
        $result = json_decode($json, true);
39
        if($error = json_last_error()) {
40
            throw new JsonException(json_last_error_msg(), $error);
41
        }
42
43
        return $result;
44
    }
45
}
46