Skip to content
This repository was archived by the owner on Mar 12, 2024. It is now read-only.

Commit 1916fb5

Browse files
committed
dump as collection option
1 parent 4d282c4 commit 1916fb5

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

src/Traits/LoopFunctions.php

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace MichaelRubel\LoopFunctions\Traits;
66

77
use Illuminate\Database\Eloquent\Model;
8+
use Illuminate\Support\Collection;
89

910
trait LoopFunctions
1011
{
@@ -75,12 +76,16 @@ public function arrayToProperties(array|\ArrayAccess|null $data, mixed $rescue =
7576
*
7677
* @param string|object|null $class
7778
* @param int|null $filter
79+
* @param bool $asCollection
7880
*
79-
* @return array
81+
* @return array|Collection
8082
* @throws \ReflectionException
8183
*/
82-
public function dumpProperties(string|object|null $class = null, ?int $filter = null): array
83-
{
84+
public function dumpProperties(
85+
string|object|null $class = null,
86+
?int $filter = null,
87+
bool $asCollection = false
88+
): array|Collection {
8489
$class = match (true) {
8590
is_string($class) => app($class),
8691
is_object($class) => $class,
@@ -90,10 +95,16 @@ public function dumpProperties(string|object|null $class = null, ?int $filter =
9095
$properties = (new \ReflectionClass($class))
9196
->getProperties($filter);
9297

93-
return collect($properties)->mapWithKeys(
98+
$collection = collect($properties)->mapWithKeys(
9499
fn (\ReflectionProperty $property) => [
95100
$property->getName() => $property->getValue($class),
96101
]
97-
)->all();
102+
);
103+
104+
if ($asCollection) {
105+
return $collection;
106+
}
107+
108+
return $collection->all();
98109
}
99110
}

tests/RecursiveClassDumpTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,15 @@ public function testCanDumpPassedObjectProperties()
3333
$this->assertArrayHasKey('escapeWhenCastingToString', $properties);
3434
$this->assertFalse($properties['escapeWhenCastingToString']);
3535
}
36+
37+
/** @test */
38+
public function testCanDumpAsCollection()
39+
{
40+
$properties = app(TestClass::class)->dumpProperties(
41+
class: Collection::class,
42+
asCollection: true,
43+
);
44+
45+
$this->assertInstanceOf(Collection::class, $properties);
46+
}
3647
}

0 commit comments

Comments
 (0)