Permalink
Browse files

Extracting duplicate loops.

  • Loading branch information...
1 parent e72127e commit 6b69ed269a32a4155d22ab7fd6b7802dc9036a52 @markstory markstory committed Jan 26, 2012
Showing with 26 additions and 34 deletions.
  1. +4 −2 lib/Cake/Test/Case/Utility/Set2Test.php
  2. +22 −32 lib/Cake/Utility/Set2.php
@@ -687,8 +687,10 @@ public function testExtractStringKey() {
$data = self::articleData();
$result = Set2::extract($data, '{n}.{s}.user');
$expected = array(
- 'mariano', 'mariano',
- 'mariano', 'mariano',
+ 'mariano',
+ 'mariano',
+ 'mariano',
+ 'mariano',
'mariano'
);
$this->assertEquals($expected, $result);
View
@@ -133,38 +133,9 @@ protected static function _traverse(array &$data, $path, $callback) {
}
foreach ($context[$_key] as $item) {
- if ($token === '{n}') {
- // any numeric key
- foreach ($item as $k => $v) {
- if (is_numeric($k)) {
- $next[] =& $v;
- }
- unset($v);
- }
- } elseif ($token === '{s}') {
- // any string key
- foreach ($item as $k => $v) {
- if (is_string($k)) {
- $next[] = $v;
- }
- unset($v);
- }
- } elseif (is_numeric($token)) {
- // numeric keys like 0, 1, 2
- foreach ($item as $k => $v) {
- if ($k == $token) {
- $next[] = $v;
- }
- unset($v);
- }
- } else {
- // bare string key
- foreach ($item as $k => $v) {
- // index or key match.
- if ($k === $token) {
- $next[] = $v;
- }
- unset($v);
+ foreach ($item as $k => $v) {
+ if (self::_matchToken($k, $token)) {
+ $next[] = $v;
}
}
}
@@ -188,6 +159,25 @@ protected static function _traverse(array &$data, $path, $callback) {
}
/**
+ * Check a key against a token.
+ *
+ * @param string $key The key in the array being searched.
+ * @param string $token The token being matched.
+ * @return boolean
+ */
+ protected static function _matchToken($key, $token) {
+ if ($token === '{n}') {
+ return is_numeric($key);
+ } elseif ($token === '{s}') {
+ return is_string($key);
+ } elseif (is_numeric($token)) {
+ return ($key == $token);
+ } else {
+ return ($key === $token);
+ }
+ }
+
+/**
* Checks whether or not $data matches the selector
*
* @param array $data Array of data to match.

0 comments on commit 6b69ed2

Please sign in to comment.