File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 22
33namespace Tipsy ;
44
5- class Looper implements \Iterator {
5+ class Looper implements \Iterator, \JsonSerializable {
66 private $ _items ;
77 private $ _position ;
88
99 const DONE = 'looper\break ' ;
1010
11+ public function jsonSerialize () {
12+ foreach ($ this ->_items as $ key => $ item ) {
13+ if (is_object ($ item ) && method_exists ($ item , 'exports ' )) {
14+ $ items [$ key ] = $ item ->exports ();
15+ } else {
16+ $ items [$ key ] = $ item ;
17+ }
18+ }
19+ return $ items ;
20+ }
21+
1122 public function __construct () {
1223 $ items = [];
1324 $ args = func_get_args ();
@@ -88,16 +99,7 @@ public function each($func, $params = []) {
8899 }
89100
90101 public function json ($ args = []) {
91- foreach ($ this ->_items as $ key => $ item ) {
92- if (is_object ($ item ) && (is_callable ($ item , 'json ' ) || method_exists ($ item , 'json ' ))) {
93- $ items [$ key ] = (new \ReflectionMethod ($ item , 'json ' ))->invokeArgs ($ item , $ args );
94- } elseif (is_object ($ item ) && method_exists ($ item , 'exports ' )) {
95- $ items [$ key ] = $ item ->exports ();
96- } else {
97- $ items [$ key ] = $ item ;
98- }
99- }
100- return json_encode ($ items );
102+ return json_encode ($ this ->jsonSerialize ());
101103 }
102104
103105 public function e ($ f ) {
Original file line number Diff line number Diff line change @@ -15,7 +15,7 @@ public function __toString() {
1515}
1616
1717class LoopItemJson {
18- public function json () {
18+ public function exports () {
1919 return ['test ' => true , 'other ' => 'asd ' ];
2020 }
2121}
@@ -297,6 +297,11 @@ public function testJsonFunction() {
297297 $ this ->assertEquals ('[{"test":true,"other":"asd"}] ' , $ loop ->json ());
298298 }
299299
300+ public function testJsonSerialize () {
301+ $ loop = new \Tipsy \Looper (new LoopItemJson );
302+ $ this ->assertEquals ('[{"test":true,"other":"asd"}] ' , json_encode ($ loop ));
303+ }
304+
300305 public function testCount () {
301306 $ loop = new \Tipsy \Looper ([4 ,5 ,6 ]);
302307 $ this ->assertEquals (3 , $ loop ->count ());
You can’t perform that action at this time.
0 commit comments