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
|
|
|
|