Browse Source

Prevent counterCache error when updating foreignkey with lambda counter

Walther Lalk 11 years ago
parent
commit
b2a3d74804

+ 6 - 2
src/Model/Behavior/CounterCacheBehavior.php

@@ -165,7 +165,7 @@ class CounterCacheBehavior extends Behavior {
 			}
 
 			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);
 			}
@@ -173,7 +173,11 @@ class CounterCacheBehavior extends Behavior {
 			$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);
 			}
 		}

+ 6 - 2
tests/TestCase/Model/Behavior/CounterCacheBehaviorTest.php

@@ -270,11 +270,15 @@ class CounterCacheBehaviorTest extends TestCase {
 
 		$this->post->addBehavior('CounterCache', [
 			'Users' => [
-				'posts_published' => function (Event $orgEvent, Entity $orgEntity, Table $orgTable) use ($entity, $table) {
+				'posts_published' => function (Event $orgEvent, Entity $orgEntity, Table $orgTable, $original) use ($entity, $table) {
 					$this->assertSame($orgTable, $table);
 					$this->assertSame($orgEntity, $entity);
 
-					return 2;
+					if (!$original) {
+						return 2;
+					} else {
+						return 1;
+					}
 				}
 			]
 		]);