From 5e9d4893a8c91233d93727f538ea126d34d92bd3 Mon Sep 17 00:00:00 2001 From: mark_story Date: Fri, 1 May 2015 22:01:45 -0400 Subject: [PATCH] Add the {*} matcher to Hash::extract() This matcher will match anything and is useful when you just want to traverse through data and you're not too picky. I've also refactored the conditions to use a case as it is slightly more readable and uses fewer lines of code. Refs #6447 --- lib/Cake/Test/Case/Utility/HashTest.php | 22 ++++++++++++++++++++++ lib/Cake/Utility/Hash.php | 19 ++++++++++--------- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/lib/Cake/Test/Case/Utility/HashTest.php b/lib/Cake/Test/Case/Utility/HashTest.php index 43f40e5d6..0212885eb 100644 --- a/lib/Cake/Test/Case/Utility/HashTest.php +++ b/lib/Cake/Test/Case/Utility/HashTest.php @@ -836,6 +836,28 @@ class HashTest extends CakeTestCase { $this->assertEquals(array('foo'), $result); } +/** + * Test wildcard matcher + * + * @return void + */ + public function testExtractWildcard() { + $data = array( + '02000009C5560001' => array('name' => 'Mr. Alphanumeric'), + '2300000918020101' => array('name' => 'Mr. Numeric'), + '390000096AB30001' => array('name' => 'Mrs. Alphanumeric'), + 'stuff' => array('name' => 'Ms. Word'), + ); + $result = Hash::extract($data, '{*}.name'); + $expected = array( + 'Mr. Alphanumeric', + 'Mr. Numeric', + 'Mrs. Alphanumeric', + 'Ms. Word', + ); + $this->assertEquals($expected, $result); + } + /** * Test the attribute presense selector. * diff --git a/lib/Cake/Utility/Hash.php b/lib/Cake/Utility/Hash.php index 897ab64c6..142c72b0a 100644 --- a/lib/Cake/Utility/Hash.php +++ b/lib/Cake/Utility/Hash.php @@ -76,6 +76,7 @@ class Hash { * * - `{n}` Matches any numeric key, or integer. * - `{s}` Matches any string key. + * - `{*}` Matches any value. * - `Foo` Matches any key with the exact same value. * * There are a number of attribute operators: @@ -171,16 +172,16 @@ class Hash { * @return bool */ protected static function _matchToken($key, $token) { - if ($token === '{n}') { - return is_numeric($key); + switch ($token) { + case '{n}': + return is_numeric($key); + case '{s}': + return is_string($key); + case '{*}': + return true; + default: + return is_numeric($token) ? ($key == $token) : $key === $token; } - if ($token === '{s}') { - return is_string($key); - } - if (is_numeric($token)) { - return ($key == $token); - } - return ($key === $token); } /**