Skip to content

Commit

Permalink
Added a Model.buildRules event
Browse files Browse the repository at this point in the history
This will help listeners such as behaviors to inject rules only in a
table lifetime.
  • Loading branch information
lorenzo committed Dec 5, 2014
1 parent 13bdebb commit be30281
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/ORM/Table.php
Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}

/**
Expand Down
21 changes: 21 additions & 0 deletions tests/TestCase/ORM/RulesCheckerIntegrationTest.php
Expand Up @@ -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));
}

}

0 comments on commit be30281

Please sign in to comment.