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

ConsulEnvManager   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 42
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B getEnvVarsFromConsul() 0 12 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