Skip to content

Commit 1dc4acd

Browse files
committed
feat(helper): add asArray(), arrayColumn()
1 parent 253e4ef commit 1dc4acd

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

src/Helper.php

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
<?php
2+
3+
namespace Ahc\Underscore;
4+
5+
class Helper
6+
{
7+
/**
8+
* Get data as array.
9+
*
10+
* @param mixed $data
11+
*
12+
* @return array
13+
*/
14+
public static function asArray($data)
15+
{
16+
if (\is_array($data)) {
17+
return $data;
18+
}
19+
20+
if (\method_exists($data, 'toArray')) {
21+
return $data->toArray();
22+
}
23+
24+
if ($data instanceof Underscore) {
25+
return $data->get();
26+
}
27+
28+
if ($data instanceof \Traversable) {
29+
return \iterator_to_array($data);
30+
}
31+
32+
if ($data instanceof \JsonSerializable) {
33+
return $data->jsonSerialize();
34+
}
35+
36+
return (array) $data;
37+
}
38+
39+
public static function arrayColumn($array, $columnKey, $indexKey = null)
40+
{
41+
$result = [];
42+
43+
if (!\is_array($array)) {
44+
\trigger_error('array_column() expects parameter 1 to be array', E_USER_WARNING);
45+
46+
return null;
47+
}
48+
49+
if (null !== $columnKey) {
50+
if (\is_object($columnKey) && !\method_exists($columnKey, '__toString')) {
51+
\trigger_error('array_column() expects parameter 2 to be number/string/null', E_USER_WARNING);
52+
53+
return null;
54+
}
55+
56+
$columnKey = \is_float($columnKey) ? (int) $columnKey : (string) $columnKey;
57+
}
58+
59+
if (null !== $indexKey) {
60+
if (\is_object($indexKey) && !\method_exists($indexKey, '__toString')) {
61+
\trigger_error('array_column() expects parameter 3 to be number/string/null', E_USER_WARNING);
62+
63+
return null;
64+
}
65+
66+
$indexKey = \is_float($indexKey) ? (int) $indexKey : (string) $indexKey;
67+
}
68+
69+
foreach ($array as $value) {
70+
$objectVars = \is_object($value) ? \get_object_vars($value) : array();
71+
72+
$key = null;
73+
if (null !== $indexKey) {
74+
if (\is_array($value) && \array_key_exists($indexKey, $value)) {
75+
$key = $value[$indexKey];
76+
} elseif (\array_key_exists($indexKey, $objectVars) || isset($value->{$indexKey})) {
77+
$key = $value->{$indexKey};
78+
}
79+
}
80+
81+
if (null !== $columnKey) {
82+
if (\is_array($value) && \array_key_exists($columnKey, $value)) {
83+
$value = $value[$columnKey];
84+
} elseif (\array_key_exists($columnKey, $objectVars) || isset($value->{$columnKey})) {
85+
$value = $value->{$columnKey};
86+
} else {
87+
continue;
88+
}
89+
}
90+
91+
if (null === $key) {
92+
$result[] = $value;
93+
} else {
94+
$result[$key] = $value;
95+
}
96+
}
97+
98+
return $result;
99+
}
100+
}

0 commit comments

Comments
 (0)