map and mapSelf : support $process with only one parameter

master 3.5.2
Julien Rosset 2 years ago
parent 281885a2d5
commit 99fee95357

@ -155,7 +155,7 @@ class Collection extends ImmutableCollection implements ICollection {
* @inheritDoc * @inheritDoc
*/ */
public function mapSelf (Closure $process): static { public function mapSelf (Closure $process): static {
$this->elements = array_map($process, $this->elements); $this->elements = $this->map($process)->elements;
return $this; return $this;
} }

@ -6,6 +6,7 @@ use ArrayIterator;
use Closure; use Closure;
use InvalidArgumentException; use InvalidArgumentException;
use OutOfBoundsException; use OutOfBoundsException;
use ReflectionFunction;
use Traversable; use Traversable;
/** /**
@ -336,9 +337,20 @@ class ImmutableCollection implements IImmutableCollection {
* @inheritDoc * @inheritDoc
*/ */
public function map (Closure $process): static { 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(); $output = new static();
foreach ($this->elements as $key => $value) { foreach ($this->elements as $key => $value) {
$output->_set($key, $process($key, $value)); $output->_set($key, $callProcessWithKey ? $process($key, $value) : $process($value));
} }
return $output; return $output;
} }

Loading…
Cancel
Save