From 99fee9535751a05e6b2712afe3602582da2a31e5 Mon Sep 17 00:00:00 2001 From: Julien Rosset Date: Wed, 11 Oct 2023 19:33:09 +0200 Subject: [PATCH] map and mapSelf : support $process with only one parameter --- src/Collections/Collection.php | 2 +- src/Collections/ImmutableCollection.php | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Collections/Collection.php b/src/Collections/Collection.php index 211a2eb..b0a01c9 100644 --- a/src/Collections/Collection.php +++ b/src/Collections/Collection.php @@ -155,7 +155,7 @@ class Collection extends ImmutableCollection implements ICollection { * @inheritDoc */ public function mapSelf (Closure $process): static { - $this->elements = array_map($process, $this->elements); + $this->elements = $this->map($process)->elements; return $this; } diff --git a/src/Collections/ImmutableCollection.php b/src/Collections/ImmutableCollection.php index 9a5188a..4f2694f 100644 --- a/src/Collections/ImmutableCollection.php +++ b/src/Collections/ImmutableCollection.php @@ -6,6 +6,7 @@ use ArrayIterator; use Closure; use InvalidArgumentException; use OutOfBoundsException; +use ReflectionFunction; use Traversable; /** @@ -336,9 +337,20 @@ class ImmutableCollection implements IImmutableCollection { * @inheritDoc */ public function map (Closure $process): static { + //region Regarde si $process doit être appelée avec la clé en plus de la valeur + $callProcessWithKey = false; + /** @noinspection PhpUnhandledExceptionInspection */ + $processReflection = new ReflectionFunction($process); + if (count($processReflection->getParameters()) >= 2) { + if (!$processReflection->getParameters()[1]->isDefaultValueAvailable()) { + $callProcessWithKey = true; + } + } + //endregion + $output = new static(); foreach ($this->elements as $key => $value) { - $output->_set($key, $process($key, $value)); + $output->_set($key, $callProcessWithKey ? $process($key, $value) : $process($value)); } return $output; }