Skip to content

Commit

Permalink
#8686 Adding a method to validate hasMany and HABTM count
Browse files Browse the repository at this point in the history
  • Loading branch information
Florian Krämer committed Apr 25, 2016
1 parent c263b38 commit 006b98f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/ORM/Table.php
Expand Up @@ -2304,4 +2304,24 @@ public function __debugInfo()
'connectionName' => $conn ? $conn->configName() : null
];
}

/**
* Validates that a belongsToMany or hasMany assoc has at least one entry.
*
* @param mixed $value
* @return boolean
*/
public function validateAtLeastOne($value)
{
if (!is_array($value)) {
return false;
}
if (isset($value['_ids'])) {
if (!is_array($value['_ids'])) {
return false;
}
return (count($value['_ids']) > 0);
}
return (count($value) > 0);
}
}
16 changes: 16 additions & 0 deletions tests/TestCase/ORM/TableTest.php
Expand Up @@ -5859,4 +5859,20 @@ public function skipIfSqlServer()
'SQLServer does not support the requirements of this test.'
);
}

/**
* Test that an association has at least one entry present.
*
* @return void
*/
public function testValidateAtLeastOne()
{
$table = TableRegistry::get('Authors');
$this->assertFalse($table->validateAtLeastOne(''));
$this->assertFalse($table->validateAtLeastOne([]));
$this->assertFalse($table->validateAtLeastOne(['_ids' => '']));
$this->assertFalse($table->validateAtLeastOne(['_ids' => []]));

$this->assertTrue($table->validateAtLeastOne(['_ids' => [1, 2, 3]]));
}
}

0 comments on commit 006b98f

Please sign in to comment.