diff --git a/src/Collection.php b/src/Collection.php index d0dc73b..5723937 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -57,8 +57,7 @@ class Collection implements IteratorAggregate, Countable public function map(callable $fn): Collection { - $tmp = array_map($fn, $this->elements); - return new Collection($tmp); + return new Collection(array_map($fn, $this->elements)); } public function each(callable $fn): void @@ -68,9 +67,24 @@ class Collection implements IteratorAggregate, Countable public function filter(callable $fn): Collection { - $tmp = array_filter($this->elements, $fn, ARRAY_FILTER_USE_BOTH); - $collect = new Collection($tmp); - return $collect; + return new Collection(array_filter($this->elements, $fn, ARRAY_FILTER_USE_BOTH)); + } + + public function pluck(string $key): Collection + { + return new Collection(array_map(function ($item) use ($key) { + if (is_object($item)) { + return isset($item->$key) ? $item->$key : null; + } + if (is_array($item)) { + return isset($item[$key]) ? $item[$key] : null; + } + }, $this->elements)); + } + + public function toArray(): array + { + return $this->elements; } public function empty(): bool diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php index 58a443b..57db513 100644 --- a/tests/CollectionTest.php +++ b/tests/CollectionTest.php @@ -50,5 +50,26 @@ test("collection", function () { return $item + $carry; },$init); expect($reduce)->toBe(55); + + $array = $coll->toArray(); + expect($array)->toBeArray(); + expect(count($array))->toBe(11); + + $obj = new \stdClass(); + $obj->key = "test"; + $obj->val = 1; + + $obj2 = new \stdClass(); + $obj2->key = "test2"; + $obj2->val = 2; + + $collo = new Collection([$obj,$obj2]); + expect($collo)->toBeInstanceOf(Collection::class); + expect(count($collo))->toBe(2); + + $pluck = $collo->pluck("key"); + expect($pluck)->toBeInstanceOf(Collection::class); + expect(count($pluck))->toBe(2); + expect($pluck->first())->toBe("test"); }); \ No newline at end of file