Completed
Push — master ( 39b3fc...3ebb26 )
by Sergey
12:04 queued 07:06
created

JsonHelperTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 80%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 5
eloc 14
c 3
b 1
f 0
dl 0
loc 49
ccs 12
cts 15
cp 0.8
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isAssoc() 0 9 1
A arrayToObject() 0 11 2
A assocArrToObject() 0 7 2
1
<?php
2
3
/**
4
 * Created by PhpStorm.
5
 * Project: json-rpc-server
6
 * User: sv
7
 * Date: 06.01.2021
8
 * Time: 15:37
9
 */
10
11
declare(strict_types=1);
12
13
namespace Onnov\JsonRpcServer\Traits;
14
15
use Exception;
16
use Onnov\JsonRpcServer\Exception\ParseErrorException;
17
use RuntimeException;
18
use stdClass;
19
20
/**
21
 * Class JsonHelperTrait
22
 * @package Onnov\JsonRpcServer\Traits
23
 */
24
trait JsonHelperTrait
25
{
26
    /**
27
     * @param mixed[] $array
28
     * @return mixed
29
     */
30 8
    public function arrayToObject(array $array)
31
    {
32
        try {
33 8
            return json_decode(
34 8
                json_encode($array, JSON_THROW_ON_ERROR),
35 8
                false,
36 8
                512,
37 8
                JSON_THROW_ON_ERROR
38
            );
39
        } catch (Exception $e) {
40
            throw new ParseErrorException('', 0, $e->getPrevious());
41
        }
42
    }
43
44
    /**
45
     * @param mixed[] $array
46
     * @return stdClass
47
     */
48 8
    public function assocArrToObject(array $array): stdClass
49
    {
50 8
        if ($this->isAssoc($array) === false) {
51
            throw new RuntimeException('Array is not associative');
52
        }
53
54 8
        return $this->arrayToObject($array);
55
    }
56
57
    /**
58
     * method from Kohana
59
     * Tests if an array is associative or not.
60
     *
61
     * @param mixed[] $array
62
     * @return bool
63
     */
64 8
    public function isAssoc(array &$array): bool
65
    {
66
        // Keys of the array
67 8
        $keys = array_keys($array);
68
69
        // If the array keys of the keys match the keys, then the array must
70
        // not be associative (e.g. the keys array looked like {0:0, 1:1...}).
71
72 8
        return array_keys($keys) !== $keys;
73
    }
74
}
75