From b6c60ec7f5eee71480f63b582b502cb174b262e3 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sat, 12 Dec 2020 12:47:47 +0100 Subject: [PATCH] Add collect each method and add a collect method to easily create a collection --- src/Utils/ArrayObject.php | 13 +++++++++++++ src/functions.php | 14 ++++++++++++++ test/Util/ArrayObjectTest.php | 12 ++++++++++++ 3 files changed, 39 insertions(+) diff --git a/src/Utils/ArrayObject.php b/src/Utils/ArrayObject.php index 849a01c9..c6b33579 100644 --- a/src/Utils/ArrayObject.php +++ b/src/Utils/ArrayObject.php @@ -45,6 +45,19 @@ public function map(callable $callback): self return new static(array_map($callback, $this->array)); } + /** + * Run a callable function over each item in the array + * + * @param callable $callback + * @return static + */ + public function each(callable $callback): self + { + array_walk($this->array, $callback); + + return new static($this->array); + } + /** * @param callable $callback * @return static diff --git a/src/functions.php b/src/functions.php index 58a54126..78d0d774 100644 --- a/src/functions.php +++ b/src/functions.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use PhpSchool\PhpWorkshop\Utils\Collection; use PhpSchool\PhpWorkshop\Utils\StringUtils; if (!function_exists('mb_str_pad')) { @@ -45,3 +46,16 @@ function canonicalise_path(string $path): string return StringUtils::canonicalisePath($path); } } + +if (!function_exists('collect')) { + + /** + * @template T + * @param array $array + * @return Collection + */ + function collect(array $array): Collection + { + return new Collection($array); + } +} diff --git a/test/Util/ArrayObjectTest.php b/test/Util/ArrayObjectTest.php index eb7a8c94..bca6899c 100644 --- a/test/Util/ArrayObjectTest.php +++ b/test/Util/ArrayObjectTest.php @@ -163,4 +163,16 @@ public function testFirst(): void $this->assertEquals(10, $arrayObject->first()); } + + public function testEach(): void + { + $c = new ArrayObject($original = [1, 2, 3, 4]); + + $result = []; + $c->each(function ($item, $key) use (&$result) { + $result[$key] = $item; + }); + + $this->assertEquals($original, $result); + } }