From be30281dcc75ffd98fad0ad881ef9bff92a58a27 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Fri, 5 Dec 2014 13:52:02 +0100 Subject: [PATCH] Added a Model.buildRules event This will help listeners such as behaviors to inject rules only in a table lifetime. --- src/ORM/Table.php | 7 ++++++- .../ORM/RulesCheckerIntegrationTest.php | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/ORM/Table.php b/src/ORM/Table.php index f70531ff280..d92ab0bcb9a 100644 --- a/src/ORM/Table.php +++ b/src/ORM/Table.php @@ -83,6 +83,9 @@ * $primary parameter indicates whether or not this is the root query, * or an associated query. * + * - `buildRules(Event $event, RulesChecker $rules)` + * Allows listeners to modify the rules checker by adding more rules. + * * - `beforeRules(Event $event, Entity $entity, RulesChecker $rules)` * Fired before an entity is validated using the rules checker. By stopping this event, * you can return the final value of the rules checking operation. @@ -1876,7 +1879,9 @@ public function rulesChecker() { if ($this->_rulesChecker !== null) { return $this->_rulesChecker; } - return $this->_rulesChecker = $this->buildRules(new RulesChecker(['repository' => $this])); + $this->_rulesChecker = $this->buildRules(new RulesChecker(['repository' => $this])); + $this->dispatchEvent('Model.buildRules', ['rules' => $this->_rulesChecker]); + return $this->_rulesChecker; } /** diff --git a/tests/TestCase/ORM/RulesCheckerIntegrationTest.php b/tests/TestCase/ORM/RulesCheckerIntegrationTest.php index 6b2bcc13529..93c1a4c853b 100644 --- a/tests/TestCase/ORM/RulesCheckerIntegrationTest.php +++ b/tests/TestCase/ORM/RulesCheckerIntegrationTest.php @@ -429,4 +429,25 @@ public function testUseAfterRules() { $this->assertSame($entity, $table->save($entity)); } + +/** + * Tests that rules can be changed using the buildRules event + * + * @group save + * @return void + */ + public function testUseBuildRulesEvent() { + $entity = new Entity([ + 'title' => 'An Article', + 'author_id' => 500 + ]); + + $table = TableRegistry::get('Articles'); + $table->eventManager()->attach(function ($event, $rules) { + $rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope')); + }, 'Model.buildRules'); + + $this->assertFalse($table->save($entity)); + } + }