This repository was archived by the owner on Apr 7, 2025. It is now read-only.
File tree 3 files changed +55
-1
lines changed
3 files changed +55
-1
lines changed Original file line number Diff line number Diff line change 3
3
namespace Helldar \SimpleDataTransferObject ;
4
4
5
5
use Helldar \Contracts \DataTransferObject \DataTransferObject as Contract ;
6
+ use Helldar \Contracts \Support \Arrayable ;
6
7
use Helldar \SimpleDataTransferObject \Contracts \Reflection ;
7
8
use Helldar \Support \Concerns \Makeable ;
8
9
use Helldar \Support \Facades \Helpers \Arr ;
9
10
use Helldar \Support \Facades \Helpers \Str ;
11
+ use ReflectionClass ;
12
+ use ReflectionProperty ;
10
13
11
14
/**
12
15
* @method static static make(array $items = [])
13
16
*/
14
- abstract class DataTransferObject implements Contract
17
+ abstract class DataTransferObject implements Contract, Arrayable
15
18
{
16
19
use Makeable;
17
20
use Reflection;
@@ -31,6 +34,22 @@ public function __construct(array $items = [])
31
34
$ this ->setItems ($ items );
32
35
}
33
36
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
+
34
53
/**
35
54
* @param array $items
36
55
*
Original file line number Diff line number Diff line change @@ -40,4 +40,24 @@ public function testConstruct()
40
40
$ this ->assertSame ($ this ->bar , $ object ->bar );
41
41
$ this ->assertSame ($ this ->baz , $ object ->baz );
42
42
}
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
+ }
43
63
}
Original file line number Diff line number Diff line change @@ -38,4 +38,19 @@ public function testConstruct()
38
38
39
39
$ this ->assertNull ($ object ->getBaz ());
40
40
}
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
+ }
41
56
}
You can’t perform that action at this time.
0 commit comments