Skip to content

Commit

Permalink
Merge pull request #4846 from dakota/3.0-counter-cache
Browse files Browse the repository at this point in the history
3.0 counter cache error with lambda counters
  • Loading branch information
markstory committed Oct 10, 2014
2 parents b2f9bbf + b2a3d74 commit 187e37c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Model/Behavior/CounterCacheBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,15 +165,19 @@ protected function _processAssociation(Event $event, Entity $entity, Association
}

if (!is_string($config) && is_callable($config)) {
$count = $config($event, $entity, $this->_table);
$count = $config($event, $entity, $this->_table, false);
} else {
$count = $this->_getCount($config, $countConditions);
}

$assoc->target()->updateAll([$field => $count], $updateConditions);

if (isset($updateOriginalConditions)) {
$count = $this->_getCount($config, $countOriginalConditions);
if (!is_string($config) && is_callable($config)) {
$count = $config($event, $entity, $this->_table, true);
} else {
$count = $this->_getCount($config, $countOriginalConditions);
}
$assoc->target()->updateAll([$field => $count], $updateOriginalConditions);
}
}
Expand Down
38 changes: 38 additions & 0 deletions tests/TestCase/Model/Behavior/CounterCacheBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,44 @@ public function testLambdaNumber() {
$this->assertEquals(2, $after->get('posts_published'));
}

/**
* Testing counter cache with lambda returning number and changing of related ID
*
* @return void
*/
public function testLambdaNumberUpdate() {
$this->post->belongsTo('Users');

$table = $this->post;
$entity = $this->_getEntity();

$this->post->addBehavior('CounterCache', [
'Users' => [
'posts_published' => function (Event $orgEvent, Entity $orgEntity, Table $orgTable, $original) use ($entity, $table) {
$this->assertSame($orgTable, $table);
$this->assertSame($orgEntity, $entity);

if (!$original) {
return 2;
} else {
return 1;
}
}
]
]);

$this->post->save($entity);
$between = $this->_getUser();
$entity->user_id = 2;
$this->post->save($entity);
$afterUser1 = $this->_getUser(1);
$afterUser2 = $this->_getUser(2);

$this->assertEquals(2, $between->get('posts_published'));
$this->assertEquals(1, $afterUser1->get('posts_published'));
$this->assertEquals(2, $afterUser2->get('posts_published'));
}

/**
* Testing counter cache with lambda returning subqueryn
*
Expand Down

0 comments on commit 187e37c

Please sign in to comment.