Test Failed
Pull Request — master (#2)
by Sergey
03:54
created

JsonHelperTrait::isAssoc()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 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|null
29
     */
30
    public function assocArrToObject(array $array): ?stdClass
31
    {
32
        try {
33
            if ($this->isAssoc($array) === false) {
34
                throw new RuntimeException('Array is not associative');
35
            }
36
37
            return json_decode(
38
                json_encode($array, JSON_THROW_ON_ERROR),
39
                false,
40
                512,
41
                JSON_THROW_ON_ERROR
42
            );
43
        } catch (Exception $e) {
44
            throw new ParseErrorException(
45
                $e->getMessage(),
46
                $e->getCode(),
47
                $e->getPrevious()
48
            );
49
        }
50
    }
51
52
    /**
53
     * @param mixed[] $data
54
     * @return bool
55
     */
56
    public function isAssoc(array &$data): bool
57
    {
58
        return array_keys($data) !== range(0, count($data) - 1);
59
    }
60
}
61