Skip to content

Commit

Permalink
Throw a RuntimeException if the validation method does not return a v…
Browse files Browse the repository at this point in the history
…alidator
  • Loading branch information
dakota committed Jun 14, 2016
1 parent 61f83c0 commit 0860d8d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/Validation/ValidatorAwareTrait.php
Expand Up @@ -14,6 +14,7 @@
*/
namespace Cake\Validation;

use \RuntimeException;
use Cake\Event\EventDispatcherInterface;

/**
Expand Down Expand Up @@ -107,6 +108,10 @@ public function validator($name = null, Validator $validator = null)
if ($this instanceof EventDispatcherInterface) {
$this->dispatchEvent('Model.buildValidator', compact('validator', 'name'));
}

if (!$validator instanceof Validator) {
throw new RuntimeException(sprintf('The %s::%s validation method must return an instance of %s.', self::class, 'validation' . ucfirst($name), Validator::class));
}
}

$validator->provider(self::VALIDATOR_PROVIDER_NAME, $this);
Expand Down
19 changes: 18 additions & 1 deletion tests/TestCase/ORM/TableTest.php
Expand Up @@ -3224,7 +3224,7 @@ public function testValidatorDefault()
*
* @return void
*/
public function functionTestValidationWithDefiner()
public function testValidationWithDefiner()
{
$table = $this->getMockBuilder('\Cake\ORM\Table')
->setMethods(['validationForOtherStuff'])
Expand All @@ -3237,6 +3237,23 @@ public function functionTestValidationWithDefiner()
$this->assertSame($table, $other->provider('table'));
}

/**
* Tests that a RuntimeException is thrown if the custom validator does not return an Validator instance
*
* @return void
* @expectedException \RuntimeException
* @expectedExceptionMessage The Cake\ORM\Table::validationBad validation method must return an instance of Cake\Validation\Validator.
*/
public function testValidationWithBadDefiner()
{
$table = $this->getMockBuilder('\Cake\ORM\Table')
->setMethods(['validationBad'])
->getMock();
$table->expects($this->once())
->method('validationBad');
$table->validator('bad');
}

/**
* Tests that it is possible to set a custom validator under a name
*
Expand Down

0 comments on commit 0860d8d

Please sign in to comment.