Passed
Push — master ( cb1f40...bdcc87 )
by Smoren
01:46
created

JsonHelper::encode()   A

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
class JsonHelper
8
{
9
    /**
10
     * Converts value to JSON format
11
     * @param mixed $value
12
     * @return string
13
     * @throws JsonException
14
     */
15
    public static function encode($value): string
16
    {
17
        $result = json_encode($value);
18
        if($error = json_last_error()) {
19
            throw new JsonException(json_last_error_msg(), $error);
20
        }
21
22
        /** @var string $result */
23
        return $result;
24
    }
25
26
    /**
27
     * Parses JSON to PHP value
28
     * @param string $json
29
     * @return mixed
30
     * @throws JsonException
31
     */
32
    public static function decode(string $json)
33
    {
34
        $result = json_decode($json, true);
35
        if($error = json_last_error()) {
36
            throw new JsonException(json_last_error_msg(), $error);
37
        }
38
39
        return $result;
40
    }
41
}
42