Passed
Push — master ( 956163...dedbc7 )
by Christian
03:02
created

EnvironmentSubstitution::restrict()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Cocotte\Shell\EnvironmentSubstitution;
4
5
use Assert\Assertion;
6
use Symfony\Component\Process\Process;
7
8
final class EnvironmentSubstitution
9
{
10
11
    /**
12
     * @var string[]
13
     */
14
    private $restrictions;
15
16
    /**
17
     * @var array
18
     */
19
    private $exports;
20
21
    public function __construct(array $restrictions, array $exports)
22
    {
23
        $this->restrictions = $restrictions;
24
        $this->exports = $exports;
25
    }
26
27
    public static function withDefaults()
28
    {
29
        return new self([], []);
30
    }
31
32
    public static function formatEnvFile(array $lines): string
33
    {
34
        $lines[] = "";
35
36
        Assertion::allString($lines);
37
38
        return implode(
39
            "\n",
40
            $lines
41
        );
42
    }
43
44
    public function restrict(array $restrictions)
45
    {
46
        return new self($restrictions, $this->exports);
47
    }
48
49
    public function export(array $exports)
50
    {
51
        return new self($this->restrictions, $exports);
52
    }
53
54
    public function substitute(SubstitutionStrategy $substitutionStrategy)
55
    {
56
        $command = ['envsubst'];
57
        if (!empty($this->restrictions)) {
58
            $command[] = implode(',', $this->shellFormat($this->restrictions));
59
        }
60
        $substitutionStrategy->substitute(new Process($command, null, $this->exports));
61
    }
62
63
    private function shellFormat(array $keys = [])
64
    {
65
        $shellFormat = [];
66
        foreach ($keys as $key) {
67
            $shellFormat[] = '${'.$key.'}';
68
        }
69
70
        return $shellFormat;
71
    }
72
73
}