From ee866efca97244af2e738df46678e50e25cd13fb Mon Sep 17 00:00:00 2001 From: Claudio Dekker Date: Wed, 15 Jun 2022 13:07:34 +0200 Subject: [PATCH 1/2] [9.x] Arr::map - Fix map-by-reference w/ built-ins --- src/Illuminate/Collections/Arr.php | 9 ++++++++- tests/Support/SupportArrTest.php | 9 +++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Collections/Arr.php b/src/Illuminate/Collections/Arr.php index c217ea8e482c..944df6e58597 100644 --- a/src/Illuminate/Collections/Arr.php +++ b/src/Illuminate/Collections/Arr.php @@ -2,6 +2,7 @@ namespace Illuminate\Support; +use ArgumentCountError; use ArrayAccess; use Illuminate\Support\Traits\Macroable; use InvalidArgumentException; @@ -555,7 +556,13 @@ public static function map(array $array, callable $callback) { $keys = array_keys($array); - $items = array_map($callback, $array, $keys); + try { + $items = array_map($callback, $array, $keys); + } catch (ArgumentCountError) { + // When the callback isn't accepting the key argument, we'll simply omit it. + // This allows to map-by-reference for fixed methods such as 'strrev'. + $items = array_map($callback, $array); + } return array_combine($keys, $items); } diff --git a/tests/Support/SupportArrTest.php b/tests/Support/SupportArrTest.php index d09fe6cd9a91..a4f5bf0ce6e4 100644 --- a/tests/Support/SupportArrTest.php +++ b/tests/Support/SupportArrTest.php @@ -632,6 +632,15 @@ public function testMap() $this->assertEquals(['first' => 'taylor', 'last' => 'otwell'], $data); } + public function testMapByReference() + { + $data = ['first' => 'taylor', 'last' => 'otwell']; + $mapped = Arr::map($data, 'strrev'); + + $this->assertEquals(['first' => 'rolyat', 'last' => 'llewto'], $mapped); + $this->assertEquals(['first' => 'taylor', 'last' => 'otwell'], $data); + } + public function testPrepend() { $array = Arr::prepend(['one', 'two', 'three', 'four'], 'zero'); From e5ffda2f02aa21a552239e6ae635dff7b41df37f Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Wed, 15 Jun 2022 07:44:34 -1000 Subject: [PATCH 2/2] Update Arr.php --- src/Illuminate/Collections/Arr.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Illuminate/Collections/Arr.php b/src/Illuminate/Collections/Arr.php index 944df6e58597..731fa2949dec 100644 --- a/src/Illuminate/Collections/Arr.php +++ b/src/Illuminate/Collections/Arr.php @@ -559,8 +559,6 @@ public static function map(array $array, callable $callback) try { $items = array_map($callback, $array, $keys); } catch (ArgumentCountError) { - // When the callback isn't accepting the key argument, we'll simply omit it. - // This allows to map-by-reference for fixed methods such as 'strrev'. $items = array_map($callback, $array); }