Throw exceptions from Hash::combine()

When the key + value counts do not match Hash should throw an exception.
Silently doing the wrong thing is generally not a good idea. While this
change could break existing applications, those applications were
probably behaving incorrectly anyways.

Fixes #2470
This commit is contained in:
mark_story 2013-12-21 17:46:05 -05:00
parent df4b978ce4
commit 62e89734ab
2 changed files with 36 additions and 3 deletions

View file

@ -1473,6 +1473,34 @@ class HashTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* test combine() giving errors on key/value length mismatches.
*
* @expectedException CakeException
* @return void
*/
public function testCombineErrorMissingValue() {
$data = array(
array('User' => array('id' => 1, 'name' => 'mark')),
array('User' => array('name' => 'jose')),
);
Hash::combine($data, '{n}.User.id', '{n}.User.name');
}
/**
* test combine() giving errors on key/value length mismatches.
*
* @expectedException CakeException
* @return void
*/
public function testCombineErrorMissingKey() {
$data = array(
array('User' => array('id' => 1, 'name' => 'mark')),
array('User' => array('id' => 2)),
);
Hash::combine($data, '{n}.User.id', '{n}.User.name');
}
/**
* test combine() with a group path.
*

View file

@ -346,10 +346,15 @@ class Hash {
} elseif (!empty($valuePath)) {
$vals = self::extract($data, $valuePath);
}
if (empty($vals)) {
$vals = array_fill(0, count($keys), null);
}
$count = count($keys);
for ($i = 0; $i < $count; $i++) {
$vals[$i] = isset($vals[$i]) ? $vals[$i] : null;
if (count($keys) !== count($vals)) {
throw new CakeException(__d(
'cake_dev',
'Hash::combine() needs an equal number of keys + values.'
));
}
if ($groupPath !== null) {