data_get()   B
last analyzed

Complexity

Conditions 9
Paths 8

Size

Total Lines 19
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
eloc 17
nc 8
nop 3
dl 0
loc 19
ccs 15
cts 15
cp 1
crap 9
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the overtrue/wechat.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace EasyWeChat\Kernel;
13
14
use EasyWeChat\Kernel\Contracts\Arrayable;
15
use EasyWeChat\Kernel\Exceptions\RuntimeException;
16
use EasyWeChat\Kernel\Support\Arr;
17
use EasyWeChat\Kernel\Support\Collection;
18
19
function data_get($data, $key, $default = null)
20
{
21
    switch (true) {
22 2
        case is_array($data):
23 2
            return Arr::get($data, $key, $default);
24 1
        case $data instanceof Collection:
25 1
            return $data->get($key, $default);
26 1
        case $data instanceof Arrayable:
27 1
            return Arr::get($data->toArray(), $key, $default);
28 1
        case $data instanceof \ArrayIterator:
29 1
            return $data->getArrayCopy()[$key] ?? $default;
30 1
        case $data instanceof \ArrayAccess:
31 1
            return $data[$key] ?? $default;
32 1
        case $data instanceof \IteratorAggregate && $data->getIterator() instanceof \ArrayIterator:
33 1
            return $data->getIterator()->getArrayCopy()[$key] ?? $default;
34 1
        case is_object($data):
35 1
            return $data->{$key} ?? $default;
36
        default:
37 1
            throw new RuntimeException(sprintf('Can\'t access data with key "%s"', $key));
38
    }
39
}
40
41
function data_to_array($data)
42
{
43
    switch (true) {
44 1
        case is_array($data):
45 1
            return $data;
46 1
        case $data instanceof Collection:
47 1
            return $data->all();
48 1
        case $data instanceof Arrayable:
49 1
            return $data->toArray();
50 1
        case $data instanceof \IteratorAggregate && $data->getIterator() instanceof \ArrayIterator:
51 1
            return $data->getIterator()->getArrayCopy();
52 1
        case $data instanceof \ArrayIterator:
53 1
            return $data->getArrayCopy();
54
        default:
55 1
            throw new RuntimeException(sprintf('Can\'t transform data to array'));
56
    }
57
}
58