diff --git a/src/Modifier/InsertValueBeforeKey.php b/src/Modifier/InsertValueBeforeKey.php new file mode 100644 index 0000000..6b0106b --- /dev/null +++ b/src/Modifier/InsertValueBeforeKey.php @@ -0,0 +1,66 @@ + new InsertValueBeforeKey('some-value', 'a-key-to-insert-before'), + * ``` + * + * ```php + * $a = [ + * 'name' => 'Yii', + * 'version' => '1.0', + * ]; + * + * $b = [ + * 'version' => '1.1', + * 'options' => [], + * 'vendor' => new InsertValueBeforeKey('Yiisoft', 'name'), + * ]; + * + * $result = ArrayHelper::merge($a, $b); + * ``` + * + * Will result in: + * + * ```php + * [ + * 'vendor' => 'Yiisoft', + * 'name' => 'Yii', + * 'version' => '1.1', + * 'options' => [], + * ]; + */ +final class InsertValueBeforeKey implements ModifierInterface +{ + /** @var mixed value of any type */ + private $value; + + private string $key; + + public function __construct($value, string $key) + { + $this->value = $value; + $this->key = $key; + } + + public function apply(array $data, $key): array + { + $res = []; + foreach ($data as $k => $v) { + if ($k === $this->key) { + $res[$key] = $this->value; + } + $res[$k] = $v; + } + + return $res; + } +} diff --git a/tests/ArrayMergeTest.php b/tests/ArrayMergeTest.php index 3b81e3a..600973a 100644 --- a/tests/ArrayMergeTest.php +++ b/tests/ArrayMergeTest.php @@ -6,6 +6,7 @@ use PHPUnit\Framework\TestCase; use Yiisoft\Arrays\ArrayHelper; +use Yiisoft\Arrays\Modifier\InsertValueBeforeKey; use Yiisoft\Arrays\Modifier\RemoveKeys; use Yiisoft\Arrays\Modifier\ReplaceValue; use Yiisoft\Arrays\Modifier\ReverseBlockMerge; @@ -245,7 +246,6 @@ public function testMergeWithNullValues(): void $this->assertEquals($expected, $result); } - public function testMergeIntegerKeyedArraysWithSameValue(): void { $a = ['2019-01-25']; @@ -257,4 +257,27 @@ public function testMergeIntegerKeyedArraysWithSameValue(): void $this->assertEquals($expected, $result); } + + public function testMergeWithInsertValueBeforekey(): void + { + $a = [ + 'name' => 'Yii', + 'version' => '1.0', + ]; + $b = [ + 'version' => '1.1', + 'options' => [], + 'vendor' => new InsertValueBeforeKey('Yiisoft', 'name'), + ]; + + $result = ArrayHelper::merge($a, $b); + $expected = [ + 'vendor' => 'Yiisoft', + 'name' => 'Yii', + 'version' => '1.1', + 'options' => [], + ]; + + $this->assertSame($expected, $result); + } }