Make contains() non-recursive.

Add a few more tests for contains().
This commit is contained in:
mark_story 2012-01-21 21:53:28 -05:00
parent d37e10a8a9
commit 885d5dfd80
2 changed files with 30 additions and 5 deletions

View file

@ -481,8 +481,8 @@ class Set2Test extends CakeTestCase {
*/
public function testContains() {
$data = array('apple', 'bee', 'cyclops');
// $this->assertTrue(Set2::contains($data, array('apple')));
// $this->assertFalse(Set2::contains($data, array('data')));
$this->assertTrue(Set2::contains($data, array('apple')));
$this->assertFalse(Set2::contains($data, array('data')));
$a = array(
0 => array('name' => 'main'),
@ -498,6 +498,18 @@ class Set2Test extends CakeTestCase {
$this->assertTrue(Set2::contains($a, $a));
$this->assertFalse(Set2::contains($a, $b));
$this->assertTrue(Set2::contains($b, $a));
$a = array(
array('User' => array('id' => 1)),
array('User' => array('id' => 2)),
);
$b = array(
array('User' => array('id' => 1)),
array('User' => array('id' => 2)),
array('User' => array('id' => 3))
);
$this->assertTrue(Set2::contains($b, $a));
$this->assertFalse(Set2::contains($a, $b));
}
}

View file

@ -82,15 +82,28 @@ class Set2 {
if (empty($data) || empty($needle)) {
return false;
}
$stack = array();
$i = 1;
while (!empty($needle)) {
$key = key($needle);
$val = $needle[$key];
unset($needle[$key]);
foreach ($needle as $key => $val) {
if (isset($data[$key]) && is_array($val)) {
if (!Set2::contains($data[$key], $val)) {
return false;
$next = $data[$key];
unset($data[$key]);
if (!empty($val)) {
$stack[] = array($val, $next);
}
} elseif (!isset($data[$key]) || $data[$key] != $val) {
return false;
}
if (empty($needle) && !empty($stack)) {
list($needle, $data) = array_pop($stack);
}
}
return true;
}