Skip to content

Commit 270fab3

Browse files
committed
json encode an entity
1 parent 8c41629 commit 270fab3

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

system/Entity.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
/**
4747
* Entity encapsulation, for use with CodeIgniter\Model
4848
*/
49-
class Entity
49+
class Entity implements \JsonSerializable
5050
{
5151
/**
5252
* Maps names used in sets and gets against unique
@@ -614,4 +614,15 @@ private function castAsJson($value, bool $asArray = false)
614614
}
615615
return $tmp;
616616
}
617+
618+
/**
619+
* Support for json_encode()
620+
*
621+
* @return array|mixed
622+
* @throws \Exception
623+
*/
624+
public function jsonSerialize()
625+
{
626+
return $this->toArray();
627+
}
617628
}

tests/system/EntityTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,13 @@ public function testIssetKeyMap()
685685
$this->assertTrue(isset($entity->FakeBar));
686686
}
687687

688+
public function testJsonSerializableEntity()
689+
{
690+
$entity = $this->getEntity();
691+
$entity->setBar('foo');
692+
$this->assertEquals(json_encode($entity->toArray()), json_encode($entity));
693+
}
694+
688695
protected function getEntity()
689696
{
690697
return new class extends Entity

0 commit comments

Comments
 (0)