JsonHelperTrait::assocArrToObject()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 10
cc 2
nc 2
nop 1
crap 2.0625
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
 *
23
 * @package Onnov\JsonRpcServer\Traits
24
 */
25
trait JsonHelperTrait
26
{
27
    /**
28
     * @param  mixed[] $array
29
     * @return mixed
30
     */
31 8
    public function arrayToObject(array $array)
32
    {
33
        try {
34 8
            return json_decode(
35 8
                json_encode($array, JSON_THROW_ON_ERROR),
36 8
                false,
37 8
                512,
38 8
                JSON_THROW_ON_ERROR
39 8
            );
40
        } catch (Exception $e) {
41
            throw new ParseErrorException('', 0, $e->getPrevious());
42
        }
43
    }
44
45
    /**
46
     * @param  mixed[] $array
47
     * @return stdClass
48
     */
49 8
    public function assocArrToObject(array $array): stdClass
50
    {
51 8
        if ($this->isAssoc($array) === false) {
52
            throw new RuntimeException('Array is not associative');
53
        }
54
55 8
        return $this->arrayToObject($array);
56
    }
57
58
    /**
59
     * method from Kohana
60
     * Tests if an array is associative or not.
61
     *
62
     * @param  mixed[] $array
63
     * @return bool
64
     */
65 8
    public function isAssoc(array &$array): bool
66
    {
67
        // Keys of the array
68 8
        $keys = array_keys($array);
69
70
        // If the array keys of the keys match the keys, then the array must
71
        // not be associative (e.g. the keys array looked like {0:0, 1:1...}).
72
73 8
        return array_keys($keys) !== $keys;
74
    }
75
}
76