Skip to content

Commit 4c16343

Browse files
committed
feat: add Arrayizes that converts data to array
1 parent ba7b1fd commit 4c16343

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/Arrayizes.php

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
3+
namespace Ahc\Underscore;
4+
5+
trait Arrayizes
6+
{
7+
/**
8+
* Get data as array.
9+
*
10+
* @param mixed $data Arbitrary data.
11+
* @param bool $cast Force casting to array!
12+
*
13+
* @return array
14+
*/
15+
public function asArray($data, $cast = true)
16+
{
17+
if (\is_array($data)) {
18+
return $data;
19+
}
20+
21+
if ($data instanceof static) {
22+
return $data->get();
23+
}
24+
25+
// @codeCoverageIgnoreStart
26+
if ($data instanceof \Traversable) {
27+
return \iterator_to_array($data);
28+
}
29+
// @codeCoverageIgnoreEnd
30+
31+
if ($data instanceof \JsonSerializable) {
32+
return $data->jsonSerialize();
33+
}
34+
35+
if (\method_exists($data, 'toArray')) {
36+
return $data->toArray();
37+
}
38+
39+
return $cast ? (array) $data : $data;
40+
}
41+
42+
/**
43+
* Convert the data items to array.
44+
*
45+
* @return array
46+
*/
47+
public function toArray()
48+
{
49+
return \array_map(function ($value) {
50+
if (\is_scalar($value)) {
51+
return $value;
52+
}
53+
54+
return $this->asArray($value, false);
55+
}, $this->getData());
56+
}
57+
}

0 commit comments

Comments
 (0)