Skip to content

Commit

Permalink
Throw exceptions from Hash::combine()
Browse files Browse the repository at this point in the history
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
  • Loading branch information
markstory committed Dec 21, 2013
1 parent df4b978 commit 62e8973
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
28 changes: 28 additions & 0 deletions lib/Cake/Test/Case/Utility/HashTest.php
Expand Up @@ -1473,6 +1473,34 @@ public function testCombine() {
$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.
*
Expand Down
11 changes: 8 additions & 3 deletions lib/Cake/Utility/Hash.php
Expand Up @@ -346,10 +346,15 @@ public static function combine(array $data, $keyPath, $valuePath = null, $groupP
} 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) {
Expand Down

0 comments on commit 62e8973

Please sign in to comment.