Skip to content
This repository was archived by the owner on Apr 7, 2025. It is now read-only.

Commit 0a53cc9

Browse files
author
Andrey Helldar
authored
Merge pull request #1 from TheDragonCode/1.x
[1.x] Added the ability to convert to an array
2 parents 678f91f + e8f6f04 commit 0a53cc9

File tree

3 files changed

+55
-1
lines changed

3 files changed

+55
-1
lines changed

src/DataTransferObject.php

+20-1
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,18 @@
33
namespace Helldar\SimpleDataTransferObject;
44

55
use Helldar\Contracts\DataTransferObject\DataTransferObject as Contract;
6+
use Helldar\Contracts\Support\Arrayable;
67
use Helldar\SimpleDataTransferObject\Contracts\Reflection;
78
use Helldar\Support\Concerns\Makeable;
89
use Helldar\Support\Facades\Helpers\Arr;
910
use Helldar\Support\Facades\Helpers\Str;
11+
use ReflectionClass;
12+
use ReflectionProperty;
1013

1114
/**
1215
* @method static static make(array $items = [])
1316
*/
14-
abstract class DataTransferObject implements Contract
17+
abstract class DataTransferObject implements Contract, Arrayable
1518
{
1619
use Makeable;
1720
use Reflection;
@@ -31,6 +34,22 @@ public function __construct(array $items = [])
3134
$this->setItems($items);
3235
}
3336

37+
public function toArray(): array
38+
{
39+
$reflect = new ReflectionClass($this);
40+
41+
$properties = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
42+
$result = [];
43+
44+
foreach ($properties as $property) {
45+
$name = $property->getName();
46+
47+
$result[$name] = $this->{$name};
48+
}
49+
50+
return $result;
51+
}
52+
3453
/**
3554
* @param array $items
3655
*

tests/Unit/MapTest.php

+20
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,24 @@ public function testConstruct()
4040
$this->assertSame($this->bar, $object->bar);
4141
$this->assertSame($this->baz, $object->baz);
4242
}
43+
44+
public function testToArray()
45+
{
46+
$object = new Map([
47+
'wa' => [
48+
'sd' => $this->foo,
49+
],
50+
51+
'qwe.rty' => $this->bar,
52+
'baz' => $this->baz,
53+
]);
54+
55+
$this->assertIsArray($object->toArray());
56+
57+
$this->assertSame([
58+
'foo' => $this->foo,
59+
'bar' => $this->bar,
60+
'baz' => $this->baz,
61+
], $object->toArray());
62+
}
4363
}

tests/Unit/SimpleTest.php

+15
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,19 @@ public function testConstruct()
3838

3939
$this->assertNull($object->getBaz());
4040
}
41+
42+
public function testToArray()
43+
{
44+
$object = new Simple([
45+
'foo' => $this->foo,
46+
'bar' => $this->bar,
47+
'baz' => $this->baz,
48+
]);
49+
50+
$this->assertIsArray($object->toArray());
51+
52+
$this->assertSame([
53+
'foo' => $this->foo,
54+
], $object->toArray());
55+
}
4156
}

0 commit comments

Comments
 (0)