From 86db21b5213f66352054426d61a043332e9c81e3 Mon Sep 17 00:00:00 2001 From: Yosuke Basuke Suzuki Date: Mon, 26 Sep 2011 15:06:45 +0900 Subject: [PATCH] Entity to array conversion improves to support has many associations. --- models/entity.php | 21 ++++++++++++++++++++- models/entity_model.php | 2 +- tests/cases/models/entity_model.test.php | 9 ++++----- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/models/entity.php b/models/entity.php index 3884936..90f2b73 100644 --- a/models/entity.php +++ b/models/entity.php @@ -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) { diff --git a/models/entity_model.php b/models/entity_model.php index 5abd2ad..0d2c4fd 100644 --- a/models/entity_model.php +++ b/models/entity_model.php @@ -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; } diff --git a/tests/cases/models/entity_model.test.php b/tests/cases/models/entity_model.test.php index a1584fe..fe0c1ea 100644 --- a/tests/cases/models/entity_model.test.php +++ b/tests/cases/models/entity_model.test.php @@ -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() {