Browse Source

Making jsonSerialize be called recursively in entities

Jose Lorenzo Rodriguez 10 years ago
parent
commit
590d135b0e
2 changed files with 16 additions and 1 deletions
  1. 1 1
      src/Datasource/EntityTrait.php
  2. 15 0
      tests/TestCase/ORM/EntityTest.php

+ 1 - 1
src/Datasource/EntityTrait.php

@@ -467,7 +467,7 @@ trait EntityTrait
      */
      */
     public function jsonSerialize()
     public function jsonSerialize()
     {
     {
-        return $this->toArray();
+        return $this->extract($this->visibleProperties());
     }
     }
 
 
     /**
     /**

+ 15 - 0
tests/TestCase/ORM/EntityTest.php

@@ -646,6 +646,21 @@ class EntityTest extends TestCase
     }
     }
 
 
     /**
     /**
+     * Tests that jsonSerialize is called recursivily for contained entities
+     *
+     * @return void
+     */
+    public function testJsonSerializeRecursive()
+    {
+        $phone = $this->getMock(Entity::class, ['jsonSerialize']);
+        $phone->expects($this->once())->method('jsonSerialize')->will($this->returnValue('12345'));
+        $data = ['name' => 'James', 'age' => 20, 'phone' => $phone];
+        $entity = new Entity($data);
+        $expected = ['name' => 'James', 'age' => 20, 'phone' => '12345'];
+        $this->assertEquals(json_encode($expected), json_encode($entity));
+    }
+
+    /**
      * Tests the extract method
      * Tests the extract method
      *
      *
      * @return void
      * @return void