From 740c86923c084e3852ff12e0477816c5ceb34b1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederic=20G=2E=20=C3=98stby?= Date: Fri, 23 Jun 2023 22:07:25 +0200 Subject: [PATCH] Added Arr::append() method --- CHANGELOG.md | 8 ++++++++ src/mako/Mako.php | 4 ++-- src/mako/utility/Arr.php | 26 ++++++++++++++++++++++++++ tests/unit/utility/ArrTest.php | 16 ++++++++++++++++ 4 files changed, 52 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb0298007..fd4bcb481 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +### 9.1.1 (2023-06-23) + +#### New + +* Added `Arr::append()` method. + +-------------------------------------------------------- + ### 9.1.0 (2023-04-15) #### New diff --git a/src/mako/Mako.php b/src/mako/Mako.php index c8d9cadaa..cd007cfa4 100644 --- a/src/mako/Mako.php +++ b/src/mako/Mako.php @@ -17,7 +17,7 @@ class Mako * * @var string */ - public const VERSION = '9.1.0'; + public const VERSION = '9.1.1'; /** * Mako major version. @@ -38,5 +38,5 @@ class Mako * * @var int */ - public const VERSION_PATCH = 0; + public const VERSION_PATCH = 1; } diff --git a/src/mako/utility/Arr.php b/src/mako/utility/Arr.php index 5ef10c7ff..7d2cf2a8f 100644 --- a/src/mako/utility/Arr.php +++ b/src/mako/utility/Arr.php @@ -56,6 +56,32 @@ public static function set(array &$array, string $path, mixed $value): void $array[array_shift($segments)] = $value; } + /** + * Appends an array value using "dot notation". + * + * @param array &$array Array you want to modify + * @param string $path Array path + * @param mixed $value Value to append + */ + public static function append(array &$array, string $path, mixed $value): void + { + $segments = explode('.', $path); + + while(count($segments) > 1) + { + $segment = array_shift($segments); + + if(!isset($array[$segment]) || !is_array($array[$segment])) + { + $array[$segment] = []; + } + + $array =& $array[$segment]; + } + + $array[array_shift($segments)][] = $value; + } + /** * Search for an array value using "dot notation". Returns TRUE if the array key exists and FALSE if not. * diff --git a/tests/unit/utility/ArrTest.php b/tests/unit/utility/ArrTest.php index 49c181b5a..fe8ace77a 100644 --- a/tests/unit/utility/ArrTest.php +++ b/tests/unit/utility/ArrTest.php @@ -33,6 +33,22 @@ public function testSet(): void $this->assertEquals(['foo' => '123', 'bar' => ['baz' => '456', 'bax' => ['789']]], $arr); } + /** + * + */ + public function testAppend(): void + { + $arr = ['foo' => ['bar' => []]]; + + Arr::append($arr, 'foo.bar', 'a'); + + Arr::append($arr, 'foo.bar', 'b'); + + Arr::append($arr, 'foo.bar', 'c'); + + $this->assertEquals(['a', 'b', 'c'], $arr['foo']['bar']); + } + /** * */