Browse Source

Allow CollectionInterface::reject() default callback

Corey Taylor 2 years ago
parent
commit
cc7c4f0a65

+ 3 - 2
src/Collection/CollectionInterface.php

@@ -93,10 +93,11 @@ interface CollectionInterface extends Iterator, JsonSerializable, Countable
      * ```
      *
      * @param callable $callback the method that will receive each of the elements and
-     * returns true whether they should be out of the resulting collection.
+     *   returns true whether they should be out of the resulting collection.
+     *   If left null, a callback that filters out truthy values will be used.
      * @return self
      */
-    public function reject(callable $callback): CollectionInterface;
+    public function reject(?callable $callback = null): CollectionInterface;
 
     /**
      * Returns true if all values in this collection pass the truth test provided

+ 6 - 2
src/Collection/CollectionTrait.php

@@ -90,9 +90,13 @@ trait CollectionTrait
     /**
      * @inheritDoc
      */
-    public function reject(callable $callback): CollectionInterface
+    public function reject(?callable $callback = null): CollectionInterface
     {
-        return new FilterIterator($this->unwrap(), fn ($key, $value, $items) => !$callback($key, $value, $items));
+        $callback ??= function ($v, $k, $i) {
+            return (bool)$v;
+        };
+
+        return new FilterIterator($this->unwrap(), fn ($value, $key, $items) => !$callback($value, $key, $items));
     }
 
     /**

+ 5 - 1
tests/TestCase/Collection/CollectionTest.php

@@ -279,6 +279,11 @@ class CollectionTest extends TestCase
             return false;
         });
         $this->assertSame([], iterator_to_array($result));
+        $this->assertInstanceOf('Cake\Collection\Collection', $result);
+
+        $collection = new Collection(['a' => null, 'b' => 2, 'c' => false]);
+        $result = $collection->reject();
+        $this->assertEquals(['a' => null, 'c' => false], iterator_to_array($result));
 
         $items = ['a' => 1, 'b' => 2, 'c' => 3];
         $collection = new Collection($items);
@@ -288,7 +293,6 @@ class CollectionTest extends TestCase
             return $v > 2;
         });
         $this->assertEquals(['a' => 1, 'b' => 2], iterator_to_array($result));
-        $this->assertInstanceOf('Cake\Collection\Collection', $result);
     }
 
     /**