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

JsonHelperTrait::isAssoc()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 2
c 1
b 1
f 0
dl 0
loc 9
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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