Move contains() across.

Fix a few issues in contains() with nested needle values.
This commit is contained in:
mark_story 2012-01-15 22:42:58 -05:00
parent ad65098348
commit d37e10a8a9
2 changed files with 49 additions and 1 deletions

View file

@ -473,4 +473,31 @@ class Set2Test extends CakeTestCase {
$expected = array('one' => array('a', 'b', 'c' => 'cee'), 'two' => 2, 'three' => null); $expected = array('one' => array('a', 'b', 'c' => 'cee'), 'two' => 2, 'three' => null);
$this->assertEquals($expected, $result); $this->assertEquals($expected, $result);
} }
/**
* testContains method
*
* @return void
*/
public function testContains() {
$data = array('apple', 'bee', 'cyclops');
// $this->assertTrue(Set2::contains($data, array('apple')));
// $this->assertFalse(Set2::contains($data, array('data')));
$a = array(
0 => array('name' => 'main'),
1 => array('name' => 'about')
);
$b = array(
0 => array('name' => 'main'),
1 => array('name' => 'about'),
2 => array('name' => 'contact'),
'a' => 'b'
);
$this->assertTrue(Set2::contains($a, $a));
$this->assertFalse(Set2::contains($a, $b));
$this->assertTrue(Set2::contains($b, $a));
}
} }

View file

@ -70,8 +70,29 @@ class Set2 {
} }
public static function contains(array $data, $needle) { /**
* Determines if one array contains the exact keys and values of another.
*
* @param array $data The data to search through.
* @param array $needle The values to file in $data
* @return boolean true if $data contains $needle, false otherwise
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::contains
*/
public static function contains(array $data, array $needle) {
if (empty($data) || empty($needle)) {
return false;
}
foreach ($needle as $key => $val) {
if (isset($data[$key]) && is_array($val)) {
if (!Set2::contains($data[$key], $val)) {
return false;
}
} elseif (!isset($data[$key]) || $data[$key] != $val) {
return false;
}
}
return true;
} }
public static function check(array $data, $path) { public static function check(array $data, $path) {