Extracting duplicate loops.

This commit is contained in:
mark_story 2012-01-25 22:41:20 -05:00
parent e72127e359
commit 6b69ed269a
2 changed files with 26 additions and 34 deletions

View file

@ -687,8 +687,10 @@ class Set2Test extends CakeTestCase {
$data = self::articleData(); $data = self::articleData();
$result = Set2::extract($data, '{n}.{s}.user'); $result = Set2::extract($data, '{n}.{s}.user');
$expected = array( $expected = array(
'mariano', 'mariano', 'mariano',
'mariano', 'mariano', 'mariano',
'mariano',
'mariano',
'mariano' 'mariano'
); );
$this->assertEquals($expected, $result); $this->assertEquals($expected, $result);

View file

@ -133,39 +133,10 @@ class Set2 {
} }
foreach ($context[$_key] as $item) { foreach ($context[$_key] as $item) {
if ($token === '{n}') {
// any numeric key
foreach ($item as $k => $v) { foreach ($item as $k => $v) {
if (is_numeric($k)) { if (self::_matchToken($k, $token)) {
$next[] =& $v;
}
unset($v);
}
} elseif ($token === '{s}') {
// any string key
foreach ($item as $k => $v) {
if (is_string($k)) {
$next[] = $v; $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);
}
} }
} }
@ -187,6 +158,25 @@ class Set2 {
return array_map($callback, $context[$_key]); return array_map($callback, $context[$_key]);
} }
/**
* 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 * Checks whether or not $data matches the selector
* *