Helpers.php ➔ data_get()   B
last analyzed

Complexity

Conditions 8
Paths 7

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
cc 8
nc 7
nop 3
dl 0
loc 19
ccs 0
cts 18
cp 0
crap 72
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
namespace Kaylyu\Alipay\Kernel;
4
5
use Kaylyu\Alipay\Kernel\Contracts\Arrayable;
6
use Kaylyu\Alipay\Kernel\Exceptions\RuntimeException;
7
use Kaylyu\Alipay\Kernel\Support\Arr;
8
use Kaylyu\Alipay\Kernel\Support\Collection;
9
10
function data_get($data, $key, $default = null)
11
{
12
    switch (true) {
13
        case is_array($data):
14
            return Arr::get($data, $key, $default);
15
        case $data instanceof Collection:
16
            return $data->get($key, $default);
17
        case $data instanceof Arrayable:
18
            return Arr::get($data->toArray(), $key, $default);
19
        case $data instanceof \ArrayIterator:
20
            return $data->getArrayCopy()[$key] ?? $default;
21
        case $data instanceof \ArrayAccess:
22
            return $data[$key] ?? $default;
23
        case $data instanceof \IteratorAggregate && $data->getIterator() instanceof \ArrayIterator:
24
            return $data->getIterator()->getArrayCopy()[$key] ?? $default;
25
        default:
26
            throw new RuntimeException(sprintf('Can\'t access data with key "%s"', $key));
27
    }
28
}
29
30
function data_to_array($data)
31
{
32
    switch (true) {
33
        case is_array($data):
34
            return $data;
35
        case $data instanceof Collection:
36
            return $data->all();
37
        case $data instanceof Arrayable:
38
            return $data->toArray();
39
        case $data instanceof \IteratorAggregate && $data->getIterator() instanceof \ArrayIterator:
40
            return $data->getIterator()->getArrayCopy();
41
        case $data instanceof \ArrayIterator:
42
            return $data->getArrayCopy();
43
        default:
44
            throw new RuntimeException(sprintf('Can\'t transform data to array'));
45
    }
46
}
47