for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
<?php
declare(strict_types=1);
namespace Yiisoft\Arrays\Collection\Modifier;
use Yiisoft\Arrays\Collection\Modifier\ModifierInterface\DataModifierInterface;
/**
* This modifier inserts a value before the key given.
*/
final class InsertValueBeforeKey implements DataModifierInterface
{
* @var int|string
private $key;
private $beforeKey;
* @param int|string $key
* @param int|string $beforeKey
public function __construct($key, $beforeKey)
$this->key = $key;
$this->beforeKey = $beforeKey;
}
* @return self
public function withKey($key): self
$new = clone $this;
$new->key = $key;
return $new;
public function beforeKey($key): self
$new->beforeKey = $key;
public function apply(array $data): array
if (!array_key_exists($this->key, $data)) {
return $data;
$result = [];
foreach ($data as $k => $v) {
if ($k === $this->beforeKey) {
$result[$this->key] = $data[$this->key];
if ($k !== $this->key) {
$result[$k] = $v;
return $result;