Browse Source

Add default callback for CollectionTrait::filter().

Refs #3128
mark_story 12 years ago
parent
commit
35df107eea
2 changed files with 22 additions and 3 deletions
  1. 9 3
      src/Collection/CollectionTrait.php
  2. 13 0
      tests/TestCase/Collection/CollectionTest.php

+ 9 - 3
src/Collection/CollectionTrait.php

@@ -72,15 +72,21 @@ trait CollectionTrait {
  *
  *
  * {{{
  * {{{
  * $collection = (new Collection([1, 2, 3]))->filter(function($value, $key) {
  * $collection = (new Collection([1, 2, 3]))->filter(function($value, $key) {
- *	return $value % 2 === 0;
+ *  return $value % 2 === 0;
  * });
  * });
  * }}}
  * }}}
  *
  *
  * @param callable $c the method that will receive each of the elements and
  * @param callable $c the method that will receive each of the elements and
- * returns true whether or not they should be in the resulting collection.
+ *   returns true whether or not they should be in the resulting collection.
+ *   If left null, a callback that filters out falsey values will be used.
  * @return \Cake\Collection\Iterator\FilterIterator
  * @return \Cake\Collection\Iterator\FilterIterator
  */
  */
-	public function filter(callable $c) {
+	public function filter(callable $c = null) {
+		if ($c === null) {
+			$c = function ($v) {
+				return !!$v;
+			};
+		}
 		return new FilterIterator($this, $c);
 		return new FilterIterator($this, $c);
 	}
 	}
 
 

+ 13 - 0
tests/TestCase/Collection/CollectionTest.php

@@ -68,6 +68,19 @@ class CollectionTest extends TestCase {
 	}
 	}
 
 
 /**
 /**
+ * Test filter() with no callback.
+ *
+ * @return void
+ */
+	public function testFilterNoCallback() {
+		$items = [1, 2, 0, 3, false, 4, null, 5, ''];
+		$collection = new Collection($items);
+		$result = $collection->filter()->toArray();
+		$expected = [1, 2, 3, 4, 5];
+		$this->assertEquals($expected, array_values($result));
+	}
+
+/**
  * Tests that it is possible to chain filter() as it returns a collection object
  * Tests that it is possible to chain filter() as it returns a collection object
  *
  *
  * @return void
  * @return void