From e68a61c375f42b73775aec177bfc92767838f3bc Mon Sep 17 00:00:00 2001 From: davidsteinsland Date: Thu, 31 Oct 2013 23:31:48 +0100 Subject: [PATCH] Added configurable default value to Hash::get() --- lib/Cake/Test/Case/Utility/HashTest.php | 4 ++++ lib/Cake/Utility/Hash.php | 7 ++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/Cake/Test/Case/Utility/HashTest.php b/lib/Cake/Test/Case/Utility/HashTest.php index c14efc8c5..bfebc3a55 100644 --- a/lib/Cake/Test/Case/Utility/HashTest.php +++ b/lib/Cake/Test/Case/Utility/HashTest.php @@ -205,6 +205,10 @@ class HashTest extends CakeTestCase { $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); diff --git a/lib/Cake/Utility/Hash.php b/lib/Cake/Utility/Hash.php index fa14c6702..e335eebf6 100644 --- a/lib/Cake/Utility/Hash.php +++ b/lib/Cake/Utility/Hash.php @@ -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); @@ -53,7 +54,7 @@ class Hash { if (is_array($data) && isset($data[$key])) { $data =& $data[$key]; } else { - return null; + return $default; } } return $data;