Browse Source

Adding more tests and a check on \Countable for ValidCount

Florian Krämer 10 years ago
parent
commit
f4bf293522
2 changed files with 23 additions and 4 deletions
  1. 4 3
      src/ORM/Rule/ValidCount.php
  2. 19 1
      tests/TestCase/ORM/RulesCheckerIntegrationTest.php

+ 4 - 3
src/ORM/Rule/ValidCount.php

@@ -14,6 +14,7 @@
  */
 namespace Cake\ORM\Rule;
 
+use Countable;
 use Cake\Datasource\EntityInterface;
 use Cake\ORM\Association;
 use Cake\Validation\Validation;
@@ -44,14 +45,14 @@ class ValidCount
     /**
      * Performs the count check
      *
-     * @param \Cake\Datasource\EntityInterface $entity The entity from where to extract the fields
+     * @param \Cake\Datasource\EntityInterface $entity The entity from where to extract the fields.
      * @param array $options Options passed to the check.
-     * @return bool
+     * @return bool True if successful, else false.
      */
     public function __invoke(EntityInterface $entity, array $options)
     {
         $value = $entity->{$this->_field};
-        if (!is_array($value)) {
+        if (!is_array($value) && !$value instanceof Countable) {
             return false;
         }
 

+ 19 - 1
tests/TestCase/ORM/RulesCheckerIntegrationTest.php

@@ -882,17 +882,35 @@ class RulesCheckerIntegrationTest extends TestCase
             ])
         ];
 
+        TableRegistry::get('ArticlesTags');
+
         $table = TableRegistry::get('articles');
         $table->belongsToMany('tags');
 
         $rules = $table->rulesChecker();
         $rules->add($rules->validCount('tags', 3));
 
-        $table->save($entity);
+        $this->assertFalse($table->save($entity));
         $this->assertEquals($entity->errors(), [
             'tags' => [
                 '_validCount' => 'The count does not match >3'
             ]
         ]);
+
+        // Testing that undesired types fail
+        $entity->tags = null;
+        $this->assertFalse($table->save($entity));
+
+        $entity->tags = new \stdClass();
+        $this->assertFalse($table->save($entity));
+
+        $entity->tags = 'string';
+        $this->assertFalse($table->save($entity));
+
+        $entity->tags = 123456;
+        $this->assertFalse($table->save($entity));
+
+        $entity->tags = 0.512;
+        $this->assertFalse($table->save($entity));
     }
 }