Completed
Push — master ( 7a412d...12f3d9 )
by Petre
02:34
created

ConsulEnvManager::getEnvVarsFromConsul()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 7
nc 5
nop 1
crap 5
1
<?php
2
declare(strict_types = 1);
3
4
namespace DL\ConsulPhpEnvVar\Service;
5
6
use SensioLabs\Consul\Services\KV;
7
8
/**
9
 * Manages environment variables through Consul.
10
 *
11
 * @package DL\ConsulPhpEnvVar\Service
12
 * @author  Petre Pătrașc <[email protected]>
13
 */
14
class ConsulEnvManager
15
{
16
    /**
17
     * @var KV
18
     */
19
    protected $kv;
20
21
    /**
22
     * @var bool
23
     */
24
    protected $overwriteEvenIfDefined = false;
25
26
    /**
27
     * ConsulEnvManager constructor.
28
     *
29
     * @param KV   $kv
30
     * @param bool $overwriteEvenIfDefined
31
     */
32 7
    public function __construct(KV $kv, bool $overwriteEvenIfDefined = false)
33
    {
34 7
        $this->kv                     = $kv;
35 7
        $this->overwriteEvenIfDefined = $overwriteEvenIfDefined;
36 7
    }
37
38
    /**
39
     * Get environment variables from Consul.
40
     *
41
     * @param array $mappings
42
     */
43 3
    public function getEnvVarsFromConsul(array $mappings)
44
    {
45 3
        foreach ($mappings as $envKey => $kvPath) {
46 3
            $keyExists = (false === getenv($envKey)) ? false : true;
47 3
            if ($keyExists && !$this->overwriteEvenIfDefined) {
48 1
                continue;
49
            }
50
51 2
            $kvValue = $this->kv->get($kvPath)->getBody();
52 2
            putenv("{$envKey}={$kvValue}");
53
        }
54 3
    }
55
}
56