Browse Source

Added the Model.buildValidation event to tje tables

This covers most of the cases for which beforeValidate was being used.
Jose Lorenzo Rodriguez 11 years ago
parent
commit
07cc015184
2 changed files with 24 additions and 1 deletions
  1. 5 1
      src/ORM/Table.php
  2. 19 0
      tests/TestCase/ORM/TableTest.php

+ 5 - 1
src/ORM/Table.php

@@ -83,7 +83,10 @@ use RuntimeException;
  *   $primary parameter indicates whether or not this is the root query,
  *   or an associated query.
  *
- *   - `buildRules(Event $event, RulesChecker $rules)`
+ * - `buildValidator(Event $event, Validator $validator, string $name)`
+ *   Allows listeners to modify validation rules for the provided named validator.
+ *
+ * - `buildRules(Event $event, RulesChecker $rules)`
  *   Allows listeners to modify the rules checker by adding more rules.
  *
  * - `beforeRules(Event $event, Entity $entity, RulesChecker $rules)`
@@ -1064,6 +1067,7 @@ class Table implements RepositoryInterface, EventListenerInterface {
 		if ($validator === null) {
 			$validator = new Validator();
 			$validator = $this->{'validation' . ucfirst($name)}($validator);
+			$this->dispatchEvent('Model.buildValidator', compact('validator', 'name'));
 		}
 
 		$validator->provider('table', $this);

+ 19 - 0
tests/TestCase/ORM/TableTest.php

@@ -3059,4 +3059,23 @@ class TableTest extends TestCase {
 		EventManager::instance()->detach($cb, 'Model.initialize');
 	}
 
+/**
+ * Tests that calling validator() trigger the buildValidator event
+ *
+ * @return void
+ */
+	public function testBuildValidatorEvent() {
+		$count = 0;
+		$cb = function ($event) use (&$count){
+			$count++;
+		};
+		EventManager::instance()->attach($cb, 'Model.buildValidator');
+		$articles = TableRegistry::get('Articles');
+		$articles->validator();
+		$this->assertEquals(1, $count, 'Callback should be called');
+
+		$articles->validator();
+		$this->assertEquals(1, $count, 'Callback should be called only once');
+	}
+
 }