From 885d5dfd802a699fbb2f4813f64cebb1815307a9 Mon Sep 17 00:00:00 2001 From: mark_story Date: Sat, 21 Jan 2012 21:53:28 -0500 Subject: [PATCH] Make contains() non-recursive. Add a few more tests for contains(). --- lib/Cake/Test/Case/Utility/Set2Test.php | 16 ++++++++++++++-- lib/Cake/Utility/Set2.php | 19 ++++++++++++++++--- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/lib/Cake/Test/Case/Utility/Set2Test.php b/lib/Cake/Test/Case/Utility/Set2Test.php index 52816afa8..5e292d56d 100644 --- a/lib/Cake/Test/Case/Utility/Set2Test.php +++ b/lib/Cake/Test/Case/Utility/Set2Test.php @@ -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)); } } diff --git a/lib/Cake/Utility/Set2.php b/lib/Cake/Utility/Set2.php index cbf2d06d2..c8ff756d5 100644 --- a/lib/Cake/Utility/Set2.php +++ b/lib/Cake/Utility/Set2.php @@ -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; }