Skip to content

Commit ed88b36

Browse files
committed
fixed issue with json functions double encoding it
1 parent 81d8321 commit ed88b36

2 files changed

Lines changed: 19 additions & 12 deletions

File tree

src/Looper.php

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,23 @@
22

33
namespace 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) {

tests/LooperTest.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public function __toString() {
1515
}
1616

1717
class 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());

0 commit comments

Comments
 (0)