Skip to content

Commit

Permalink
Fix marshalling nested associations inside _joinData.
Browse files Browse the repository at this point in the history
The _joinData entity could have additional associations that we should
also be able to marshall.
  • Loading branch information
markstory committed Dec 25, 2013
1 parent b153a62 commit 7319a6a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 4 deletions.
14 changes: 10 additions & 4 deletions Cake/ORM/Marshaller.php
Expand Up @@ -153,16 +153,22 @@ public function many(array $data, $include = []) {
* @return array An array of built entities.
*/
protected function _belongsToMany(Association $assoc, array $data, $include = []) {
if (!in_array('_joinData', $include)) {
return $this->many($data, $include);
$records = $this->many($data, $include);
if (!in_array('_joinData', $include) && !isset($include['_joinData'])) {
return $records;
}

$joint = $assoc->junction();
$jointMarshaller = $joint->marshaller();
$records = $this->many($data, $include);

$nested = [];
if (isset($include['_joinData']['associated'])) {
$nested = (array)$include['_joinData']['associated'];
}

foreach ($records as $i => $record) {
if (isset($data[$i]['_joinData'])) {
$joinData = $jointMarshaller->one($data[$i]['_joinData'], $include);
$joinData = $jointMarshaller->one($data[$i]['_joinData'], $nested);
$record->set('_joinData', $joinData);
}
}
Expand Down
53 changes: 53 additions & 0 deletions Cake/Test/TestCase/ORM/MarshallerTest.php
Expand Up @@ -268,6 +268,59 @@ public function testOneBelongsToManyJoinData() {
);
}

/**
* Test marshalling nested associations on the _joinData structure.
*
* @return void
*/
public function testOneBelongsToManyJoinDataAssociated() {
$data = [
'title' => 'My title',
'body' => 'My content',
'author_id' => 1,
'tags' => [
[
'tag' => 'news',
'_joinData' => [
'active' => 1,
'user' => ['username' => 'Bill'],
]
],
[
'tag' => 'cakephp',
'_joinData' => [
'active' => 0,
'user' => ['username' => 'Mark'],
]
],
],
];

$articlesTags = TableRegistry::get('ArticlesTags');
$articlesTags->belongsTo('Users');

$marshall = new Marshaller($this->articles);
$result = $marshall->one($data, [
'Tags' => [
'associated' => [
'_joinData' => ['associated' => ['Users']]
]
]
]);
$this->assertInstanceOf(
'Cake\ORM\Entity',
$result->tags[0]->_joinData->user,
'joinData should contain a user entity.'
);
$this->assertEquals('Bill', $result->tags[0]->_joinData->user->username);
$this->assertInstanceOf(
'Cake\ORM\Entity',
$result->tags[1]->_joinData->user,
'joinData should contain a user entity.'
);
$this->assertEquals('Mark', $result->tags[1]->_joinData->user->username);
}

/**
* Test one() with deeper associations.
*
Expand Down

0 comments on commit 7319a6a

Please sign in to comment.