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

JsonHelper   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 4
eloc 9
c 1
b 0
f 1
dl 0
loc 33
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A decode() 0 8 2
A encode() 0 9 2
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