Skip to content

Commit

Permalink
Added configurable default value to Hash::get()
Browse files Browse the repository at this point in the history
  • Loading branch information
davidsteinsland committed Oct 31, 2013
1 parent e5c2d4f commit e68a61c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
4 changes: 4 additions & 0 deletions lib/Cake/Test/Case/Utility/HashTest.php
Expand Up @@ -205,6 +205,10 @@ public function testGet() {
$result = Hash::get($data, '5.Article.title');
$this->assertNull($result);

$default = array('empty');
$this->assertEquals($default, Hash::get($data, '5.Article.title', $default));
$this->assertEquals($default, Hash::get(array(), '5.Article.title', $default));

$result = Hash::get($data, '1.Article.title.not_there');
$this->assertNull($result);

Expand Down
7 changes: 4 additions & 3 deletions lib/Cake/Utility/Hash.php
Expand Up @@ -37,12 +37,13 @@ class Hash {
* @param array $data Array of data to operate on.
* @param string|array $path The path being searched for. Either a dot
* separated string, or an array of path segments.
* @param mixed $default The return value when the path does not exist
* @return mixed The value fetched from the array, or null.
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::get
*/
public static function get(array $data, $path) {
public static function get(array $data, $path, $default = null) {
if (empty($data)) {
return null;
return $default;
}
if (is_string($path) || is_numeric($path)) {
$parts = explode('.', $path);
Expand All @@ -53,7 +54,7 @@ public static function get(array $data, $path) {
if (is_array($data) && isset($data[$key])) {
$data =& $data[$key];
} else {
return null;
return $default;
}
}
return $data;
Expand Down

0 comments on commit e68a61c

Please sign in to comment.