Passed
Push — master ( abee1f...edc958 )
by Kirill
03:08
created

Prepend   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 17
dl 0
loc 43
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
A patch() 0 15 3
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Config\Patch;
13
14
use Spiral\Config\Exception\DotNotFoundException;
15
use Spiral\Config\Exception\PatchException;
16
use Spiral\Config\Patch\Traits\DotTrait;
17
use Spiral\Config\PatchInterface;
18
19
final class Prepend implements PatchInterface
20
{
21
    use DotTrait;
0 ignored issues
show
Bug introduced by
The trait Spiral\Config\Patch\Traits\DotTrait requires the property $prefix which is not provided by Spiral\Config\Patch\Prepend.
Loading history...
22
23
    /** @var string */
24
    private $position;
25
26
    /** @var null|string */
27
    private $key;
28
29
    /** @var mixed */
30
    private $value;
31
32
    /**
33
     * @param string      $position
34
     * @param null|string $key
35
     * @param mixed       $value
36
     */
37
    public function __construct(string $position, ?string $key, $value)
38
    {
39
        $this->position = $position === '.' ? '' : $position;
40
        $this->key = $key;
41
        $this->value = $value;
42
    }
43
44
    /**
45
     * @inheritdoc
46
     */
47
    public function patch(array $config): array
48
    {
49
        try {
50
            $target = &$this->dotGet($config, $this->position);
51
52
            if ($this->key !== null) {
53
                $target = array_merge([$this->key => $this->value], $target);
54
            } else {
55
                array_unshift($target, $this->value);
56
            }
57
        } catch (DotNotFoundException $e) {
58
            throw new PatchException($e->getMessage(), $e->getCode(), $e);
59
        }
60
61
        return $config;
62
    }
63
}
64