Skip to content

Commit

Permalink
Moving filter() into Set2.
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Mar 27, 2012
1 parent 885d5df commit 1315e0f
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
29 changes: 29 additions & 0 deletions lib/Cake/Test/Case/Utility/Set2Test.php
Expand Up @@ -512,4 +512,33 @@ public function testContains() {
$this->assertFalse(Set2::contains($a, $b));
}

/**
* testFilter method
*
* @return void
*/
public function testFilter() {
$result = Set2::filter(array('0', false, true, 0, array('one thing', 'I can tell you', 'is you got to be', false)));
$expected = array('0', 2 => true, 3 => 0, 4 => array('one thing', 'I can tell you', 'is you got to be'));
$this->assertSame($expected, $result);

$result = Set2::filter(array(1, array(false)));
$expected = array(1);
$this->assertEquals($expected, $result);

$result = Set2::filter(array(1, array(false, false)));
$expected = array(1);
$this->assertEquals($expected, $result);

$result = Set2::filter(array(1, array('empty', false)));
$expected = array(1, array('empty'));
$this->assertEquals($expected, $result);

$result = Set2::filter(array(1, array('2', false, array(3, null))));
$expected = array(1, array('2', 2 => array(3)));
$this->assertEquals($expected, $result);

$this->assertSame(array(), Set2::filter(array()));
}

}
27 changes: 26 additions & 1 deletion lib/Cake/Utility/Set2.php
Expand Up @@ -112,8 +112,33 @@ public static function check(array $data, $path) {

}

/**
* Recursively filters empty elements out of a route array, excluding '0'.
*
* @param array $data Either an array to filter, or value when in callback
* @return array Filtered array
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::filter
*/
public static function filter(array $data) {

foreach ($data as $k => $v) {
if (is_array($v)) {
$data[$k] = Set2::filter($v);
}
}
return array_filter($data, array('Set2', '_filter'));
}

/**
* Callback function for filtering.
*
* @param array $var Array to filter.
* @return boolean
*/
protected static function _filter($var) {
if ($var === 0 || $var === '0' || !empty($var)) {
return true;
}
return false;
}

/**
Expand Down

0 comments on commit 1315e0f

Please sign in to comment.