Passed
Pull Request — master (#2)
by Sergey
04:29
created

JsonHelperTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 76.92%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 4
eloc 13
c 3
b 1
f 0
dl 0
loc 40
ccs 10
cts 13
cp 0.7692
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A assocArrToObject() 0 15 3
A isAssoc() 0 9 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 stdClass
29
     */
30 5
    public function assocArrToObject(array $array): stdClass
31
    {
32
        try {
33 5
            if ($this->isAssoc($array) === false) {
34
                throw new RuntimeException('Array is not associative');
35
            }
36
37 5
            return json_decode(
38 5
                json_encode($array, JSON_THROW_ON_ERROR),
39 5
                false,
40 5
                512,
41 5
                JSON_THROW_ON_ERROR
42
            );
43
        } catch (Exception $e) {
44
            throw new ParseErrorException('', 0, $e->getPrevious());
45
        }
46
    }
47
48
    /**
49
     * method from Kohana
50
     * Tests if an array is associative or not.
51
     *
52
     * @param mixed[] $array
53
     * @return bool
54
     */
55 5
    public function isAssoc(array &$array): bool
56
    {
57
        // Keys of the array
58 5
        $keys = array_keys($array);
59
60
        // If the array keys of the keys match the keys, then the array must
61
        // not be associative (e.g. the keys array looked like {0:0, 1:1...}).
62
63 5
        return array_keys($keys) !== $keys;
64
    }
65
}
66