Skip to content

Commit

Permalink
Making EntityTrait::toArray smarter about how it handles input
Browse files Browse the repository at this point in the history
  • Loading branch information
Patrick Conroy committed May 13, 2015
1 parent c7c32b6 commit 529a427
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/Datasource/EntityTrait.php
Expand Up @@ -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;
Expand Down
24 changes: 24 additions & 0 deletions tests/TestCase/ORM/EntityTest.php
Expand Up @@ -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.
*
Expand Down

0 comments on commit 529a427

Please sign in to comment.