Skip to content

Commit

Permalink
Add the {*} matcher to Hash::extract()
Browse files Browse the repository at this point in the history
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
  • Loading branch information
markstory committed May 2, 2015
1 parent 345d8d8 commit 5e9d489
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
22 changes: 22 additions & 0 deletions lib/Cake/Test/Case/Utility/HashTest.php
Expand Up @@ -836,6 +836,28 @@ public function testExtractStringKey() {
$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.
*
Expand Down
19 changes: 10 additions & 9 deletions lib/Cake/Utility/Hash.php
Expand Up @@ -76,6 +76,7 @@ public static function get(array $data, $path, $default = null) {
*
* - `{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:
Expand Down Expand Up @@ -171,16 +172,16 @@ protected static function _splitConditions($token) {
* @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);
}

/**
Expand Down

0 comments on commit 5e9d489

Please sign in to comment.