diff --git a/lib/Cake/Test/Case/Utility/Set2Test.php b/lib/Cake/Test/Case/Utility/Set2Test.php index 5e292d56d..456e153e2 100644 --- a/lib/Cake/Test/Case/Utility/Set2Test.php +++ b/lib/Cake/Test/Case/Utility/Set2Test.php @@ -512,4 +512,33 @@ class Set2Test extends CakeTestCase { $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())); + } + } diff --git a/lib/Cake/Utility/Set2.php b/lib/Cake/Utility/Set2.php index c8ff756d5..71ea8d37d 100644 --- a/lib/Cake/Utility/Set2.php +++ b/lib/Cake/Utility/Set2.php @@ -112,8 +112,33 @@ class Set2 { } +/** + * 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; } /**