Skip to content

Commit

Permalink
Make contains() non-recursive.
Browse files Browse the repository at this point in the history
Add a few more tests for contains().
  • Loading branch information
markstory committed Mar 27, 2012
1 parent d37e10a commit 885d5df
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
16 changes: 14 additions & 2 deletions lib/Cake/Test/Case/Utility/Set2Test.php
Expand Up @@ -481,8 +481,8 @@ public function testNormalize() {
*/
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'),
Expand All @@ -498,6 +498,18 @@ public function testContains() {
$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));
}

}
19 changes: 16 additions & 3 deletions lib/Cake/Utility/Set2.php
Expand Up @@ -82,15 +82,28 @@ public static function contains(array $data, array $needle) {
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;
}
Expand Down

0 comments on commit 885d5df

Please sign in to comment.