Skip to content

Commit be30281

Browse files
committed
Added a Model.buildRules event
This will help listeners such as behaviors to inject rules only in a table lifetime.
1 parent 13bdebb commit be30281

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/ORM/Table.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,9 @@
8383
* $primary parameter indicates whether or not this is the root query,
8484
* or an associated query.
8585
*
86+
* - `buildRules(Event $event, RulesChecker $rules)`
87+
* Allows listeners to modify the rules checker by adding more rules.
88+
*
8689
* - `beforeRules(Event $event, Entity $entity, RulesChecker $rules)`
8790
* Fired before an entity is validated using the rules checker. By stopping this event,
8891
* you can return the final value of the rules checking operation.
@@ -1876,7 +1879,9 @@ public function rulesChecker() {
18761879
if ($this->_rulesChecker !== null) {
18771880
return $this->_rulesChecker;
18781881
}
1879-
return $this->_rulesChecker = $this->buildRules(new RulesChecker(['repository' => $this]));
1882+
$this->_rulesChecker = $this->buildRules(new RulesChecker(['repository' => $this]));
1883+
$this->dispatchEvent('Model.buildRules', ['rules' => $this->_rulesChecker]);
1884+
return $this->_rulesChecker;
18801885
}
18811886

18821887
/**

tests/TestCase/ORM/RulesCheckerIntegrationTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,4 +429,25 @@ public function testUseAfterRules() {
429429

430430
$this->assertSame($entity, $table->save($entity));
431431
}
432+
433+
/**
434+
* Tests that rules can be changed using the buildRules event
435+
*
436+
* @group save
437+
* @return void
438+
*/
439+
public function testUseBuildRulesEvent() {
440+
$entity = new Entity([
441+
'title' => 'An Article',
442+
'author_id' => 500
443+
]);
444+
445+
$table = TableRegistry::get('Articles');
446+
$table->eventManager()->attach(function ($event, $rules) {
447+
$rules->add($rules->existsIn('author_id', TableRegistry::get('Authors'), 'Nope'));
448+
}, 'Model.buildRules');
449+
450+
$this->assertFalse($table->save($entity));
451+
}
452+
432453
}

0 commit comments

Comments
 (0)