Skip to content

Commit b5fe20a

Browse files
authored
Merge pull request #193 from php-school/collection-func-and-each
Collection enhancements
2 parents 340e9cb + b6c60ec commit b5fe20a

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

src/Utils/ArrayObject.php

+13
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,19 @@ public function map(callable $callback): self
4545
return new static(array_map($callback, $this->array));
4646
}
4747

48+
/**
49+
* Run a callable function over each item in the array
50+
*
51+
* @param callable $callback
52+
* @return static
53+
*/
54+
public function each(callable $callback): self
55+
{
56+
array_walk($this->array, $callback);
57+
58+
return new static($this->array);
59+
}
60+
4861
/**
4962
* @param callable $callback
5063
* @return static

src/functions.php

+14
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
declare(strict_types=1);
44

5+
use PhpSchool\PhpWorkshop\Utils\Collection;
56
use PhpSchool\PhpWorkshop\Utils\StringUtils;
67

78
if (!function_exists('mb_str_pad')) {
@@ -45,3 +46,16 @@ function canonicalise_path(string $path): string
4546
return StringUtils::canonicalisePath($path);
4647
}
4748
}
49+
50+
if (!function_exists('collect')) {
51+
52+
/**
53+
* @template T
54+
* @param array<T> $array
55+
* @return Collection<T>
56+
*/
57+
function collect(array $array): Collection
58+
{
59+
return new Collection($array);
60+
}
61+
}

test/Util/ArrayObjectTest.php

+12
Original file line numberDiff line numberDiff line change
@@ -163,4 +163,16 @@ public function testFirst(): void
163163

164164
$this->assertEquals(10, $arrayObject->first());
165165
}
166+
167+
public function testEach(): void
168+
{
169+
$c = new ArrayObject($original = [1, 2, 3, 4]);
170+
171+
$result = [];
172+
$c->each(function ($item, $key) use (&$result) {
173+
$result[$key] = $item;
174+
});
175+
176+
$this->assertEquals($original, $result);
177+
}
166178
}

0 commit comments

Comments
 (0)