Skip to content

Commit

Permalink
Entity to array conversion improves to support has many associations.
Browse files Browse the repository at this point in the history
  • Loading branch information
Yosuke Basuke Suzuki committed Sep 26, 2011
1 parent f36ec70 commit 86db21b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
21 changes: 20 additions & 1 deletion models/entity.php
Expand Up @@ -94,7 +94,26 @@ public function __toString() {
}

public function toArray() {
return Set::reverse($this);
$data = Set::reverse($this);

foreach (array_keys($data[$this->_name_]) as $name) {
// has many association
if (is_array($data[$this->_name_][$name]) and Set::numeric(array_keys($data[$this->_name_][$name]))) {
$list = $data[$this->_name_][$name];
unset($data[$this->_name_][$name]);

$name = Inflector::classify($name);
$data[$name] = array();
foreach ($list as $sub) {
if (is_array($sub)) {
$sub = current($sub);
}
$data[$name][] = $sub;
}
}
}

return $data;
}

private function magicFetch($key, &$value) {
Expand Down
2 changes: 1 addition & 1 deletion models/entity_model.php
Expand Up @@ -172,7 +172,7 @@ public function assignAttribute(Entity $entity, $alias, $value) {
$entity->{$name} = $value;
}

protected function getAssociatedModel($alias) {
public function getAssociatedModel($alias) {
if ($this->schema($alias) or !preg_match('/^[A-Z]/', $alias)) {
return null;
}
Expand Down
9 changes: 4 additions & 5 deletions tests/cases/models/entity_model.test.php
Expand Up @@ -501,24 +501,23 @@ public function testEntityToArray() {
'name' => 'Basuke',
'programmer' => 'Programmer',
),
'Post' => array(
'Comment' => array(
array(
'id' => '1',
'author_id' => '123',
'title' => 'Hello',
'comment' => 'Hello',
),
array(
'id' => '2',
'author_id' => '123',
'title' => 'World',
'comment' => 'World',
),
),
);

$author = $this->Author->entity($data);
$reversed = $author->toArray();
// $this->assertEqual($reversed, $data);

$this->assertEqual($reversed, $data);
}

public function testEntityGetModel() {
Expand Down

0 comments on commit 86db21b

Please sign in to comment.