Browse Source

Merge pull request #8983 from dakota/make-validation-unsurprising

Throw a RuntimeException if the validation method does not return a validator
José Lorenzo Rodríguez 9 years ago
parent
commit
ade756932e
2 changed files with 24 additions and 1 deletions
  1. 6 0
      src/Validation/ValidatorAwareTrait.php
  2. 18 1
      tests/TestCase/ORM/TableTest.php

+ 6 - 0
src/Validation/ValidatorAwareTrait.php

@@ -15,6 +15,7 @@
 namespace Cake\Validation;
 
 use Cake\Event\EventDispatcherInterface;
+use RuntimeException;
 
 /**
  * A trait that provides methods for building and
@@ -91,6 +92,7 @@ trait ValidatorAwareTrait
      * @param \Cake\Validation\Validator|null $validator The validator instance to store,
      *   use null to get a validator.
      * @return \Cake\Validation\Validator
+     * @throws \RuntimeException
      */
     public function validator($name = null, Validator $validator = null)
     {
@@ -107,6 +109,10 @@ trait ValidatorAwareTrait
             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.', __CLASS__, 'validation' . ucfirst($name), Validator::class));
+            }
         }
 
         $validator->provider(self::VALIDATOR_PROVIDER_NAME, $this);

+ 18 - 1
tests/TestCase/ORM/TableTest.php

@@ -3224,7 +3224,7 @@ class TableTest extends TestCase
      *
      * @return void
      */
-    public function functionTestValidationWithDefiner()
+    public function testValidationWithDefiner()
     {
         $table = $this->getMockBuilder('\Cake\ORM\Table')
             ->setMethods(['validationForOtherStuff'])
@@ -3238,6 +3238,23 @@ class TableTest extends TestCase
     }
 
     /**
+     * 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
      *
      * @return void