Browse Source

Merge pull request #4846 from dakota/3.0-counter-cache

3.0 counter cache error with lambda counters
Mark Story 11 years ago
parent
commit
187e37c74e

+ 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);
 			}
 		}

+ 38 - 0
tests/TestCase/Model/Behavior/CounterCacheBehaviorTest.php

@@ -258,6 +258,44 @@ class CounterCacheBehaviorTest extends TestCase {
 	}
 
 /**
+ * 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
  *
  * @return void