Skip to content
Permalink
Browse files

Making EntityTrait::toArray smarter about how it handles input

  • Loading branch information...
Patrick Conroy
Patrick Conroy committed May 13, 2015
1 parent c7c32b6 commit 529a427236cc343d492286f930842bc294c5f001
Showing with 31 additions and 3 deletions.
  1. +7 −3 src/Datasource/EntityTrait.php
  2. +24 −0 tests/TestCase/ORM/EntityTest.php
@@ -437,12 +437,16 @@ public function toArray()
$result = [];
foreach ($this->visibleProperties() as $property) {
$value = $this->get($property);
if (is_array($value) && isset($value[0]) && $value[0] instanceof EntityInterface) {
if (is_array($value)) {
$result[$property] = [];
foreach ($value as $k => $entity) {
$result[$property][$k] = $entity->toArray();
if (method_exists($entity, 'toArray')) {
$result[$property][$k] = $entity->toArray();
} else {
$result[$property][$k] = $entity;
}
}
} elseif ($value instanceof EntityInterface) {
} elseif (method_exists($value, 'toArray')) {
$result[$property] = $value->toArray();
} else {
$result[$property] = $value;
@@ -806,6 +806,30 @@ public function testToArrayRecursive()
$this->assertEquals($expected, $user->toArray());
}
/**
* Tests that an entity with entities and other misc types can be properly toArray'd
*
* @return void
*/
public function testToArrayMixed()
{
$test = new Entity([
'id' => 1,
'foo' => [
new Entity(['hi' => 'test']),
'notentity' => 1
]
]);
$expected = [
'id' => 1,
'foo' => [
['hi' => 'test'],
'notentity' => 1
]
];
$this->assertEquals($expected, $test->toArray());
}
/**
* Test that get accessors are called when converting to arrays.
*

0 comments on commit 529a427

Please sign in to comment.
You can’t perform that action at this time.