Skip to content

Commit d37e10a

Browse files
committed
Move contains() across.
Fix a few issues in contains() with nested needle values.
1 parent ad65098 commit d37e10a

2 files changed

Lines changed: 49 additions & 1 deletion

File tree

lib/Cake/Test/Case/Utility/Set2Test.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,4 +473,31 @@ public function testNormalize() {
473473
$expected = array('one' => array('a', 'b', 'c' => 'cee'), 'two' => 2, 'three' => null);
474474
$this->assertEquals($expected, $result);
475475
}
476+
477+
/**
478+
* testContains method
479+
*
480+
* @return void
481+
*/
482+
public function testContains() {
483+
$data = array('apple', 'bee', 'cyclops');
484+
// $this->assertTrue(Set2::contains($data, array('apple')));
485+
// $this->assertFalse(Set2::contains($data, array('data')));
486+
487+
$a = array(
488+
0 => array('name' => 'main'),
489+
1 => array('name' => 'about')
490+
);
491+
$b = array(
492+
0 => array('name' => 'main'),
493+
1 => array('name' => 'about'),
494+
2 => array('name' => 'contact'),
495+
'a' => 'b'
496+
);
497+
498+
$this->assertTrue(Set2::contains($a, $a));
499+
$this->assertFalse(Set2::contains($a, $b));
500+
$this->assertTrue(Set2::contains($b, $a));
501+
}
502+
476503
}

lib/Cake/Utility/Set2.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,29 @@ public static function combine(array $data, $keyPath, $valuePath = null) {
7070

7171
}
7272

73-
public static function contains(array $data, $needle) {
73+
/**
74+
* Determines if one array contains the exact keys and values of another.
75+
*
76+
* @param array $data The data to search through.
77+
* @param array $needle The values to file in $data
78+
* @return boolean true if $data contains $needle, false otherwise
79+
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::contains
80+
*/
81+
public static function contains(array $data, array $needle) {
82+
if (empty($data) || empty($needle)) {
83+
return false;
84+
}
7485

86+
foreach ($needle as $key => $val) {
87+
if (isset($data[$key]) && is_array($val)) {
88+
if (!Set2::contains($data[$key], $val)) {
89+
return false;
90+
}
91+
} elseif (!isset($data[$key]) || $data[$key] != $val) {
92+
return false;
93+
}
94+
}
95+
return true;
7596
}
7697

7798
public static function check(array $data, $path) {

0 commit comments

Comments
 (0)