Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions src/Modifier/InsertValueBeforeKey.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Arrays\Modifier;

/**
* Inserts given value before specified key while performing {@see ArrayHelper::merge()}.
*
* The modifier should be specified as
*
* ```php
* 'some-key' => 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;
}
}
25 changes: 24 additions & 1 deletion tests/ArrayMergeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -245,7 +246,6 @@ public function testMergeWithNullValues(): void
$this->assertEquals($expected, $result);
}


public function testMergeIntegerKeyedArraysWithSameValue(): void
{
$a = ['2019-01-25'];
Expand All @@ -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);
}
}