Skip to content

Commit

Permalink
fixed issue with json functions double encoding it
Browse files Browse the repository at this point in the history
  • Loading branch information
spacedevin committed Jan 27, 2016
1 parent 81d8321 commit ed88b36
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
24 changes: 13 additions & 11 deletions src/Looper.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,23 @@

namespace Tipsy;

class Looper implements \Iterator {
class Looper implements \Iterator, \JsonSerializable {
private $_items;
private $_position;

const DONE = 'looper\break';

public function jsonSerialize() {
foreach ($this->_items as $key => $item) {
if (is_object($item) && method_exists($item, 'exports')) {
$items[$key] = $item->exports();
} else {
$items[$key] = $item;
}
}
return $items;
}

public function __construct() {
$items = [];
$args = func_get_args();
Expand Down Expand Up @@ -88,16 +99,7 @@ public function each($func, $params = []) {
}

public function json($args = []) {
foreach ($this->_items as $key => $item) {
if (is_object($item) && (is_callable($item, 'json') || method_exists($item, 'json'))) {
$items[$key] = (new \ReflectionMethod($item, 'json'))->invokeArgs($item, $args);
} elseif (is_object($item) && method_exists($item, 'exports')) {
$items[$key] = $item->exports();
} else {
$items[$key] = $item;
}
}
return json_encode($items);
return json_encode($this->jsonSerialize());
}

public function e($f) {
Expand Down
7 changes: 6 additions & 1 deletion tests/LooperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public function __toString() {
}

class LoopItemJson {
public function json() {
public function exports() {
return ['test' => true, 'other' => 'asd'];
}
}
Expand Down Expand Up @@ -297,6 +297,11 @@ public function testJsonFunction() {
$this->assertEquals('[{"test":true,"other":"asd"}]', $loop->json());
}

public function testJsonSerialize() {
$loop = new \Tipsy\Looper(new LoopItemJson);
$this->assertEquals('[{"test":true,"other":"asd"}]', json_encode($loop));
}

public function testCount() {
$loop = new \Tipsy\Looper([4,5,6]);
$this->assertEquals(3, $loop->count());
Expand Down

0 comments on commit ed88b36

Please sign in to comment.