Completed
Pull Request — master (#10)
by Greg
01:41
created

EnvConfig::import()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
namespace Consolidation\Config\Util;
3
4
use Consolidation\Config\Config;
5
use Consolidation\Config\ConfigInterface;
6
7
/**
8
 * Provide a configuration object that fetches values from environment
9
 * variables.
10
 */
11
class EnvConfig implements ConfigInterface
12
{
13
    /** @var string */
14
    protected $prefix;
15
16
    /**
17
     * EnvConfig constructor
18
     *
19
     * @param $prefix The string to appear before every environment
20
     *   variable key. For example, if the prefix is 'MYAPP_', then
21
     *   the key 'foo.bar' will be fetched from the environment variable
22
     *   MYAPP_FOO_BAR.
23
     */
24
    public function __construct($prefix)
25
    {
26
        // Ensure that the prefix is always uppercase, and always
27
        // ends with a '_', regardless of the form the caller provided.
28
        $this->prefix = strtoupper(rtrim($prefix, '_')) . '_';
29
    }
30
31
    /**
32
     * @inheritdoc
33
     */
34
    public function has($key)
35
    {
36
        return $this->get($key) !== null;
37
    }
38
39
    /**
40
     * @inheritdoc
41
     */
42
    public function get($key, $defaultFallback = null)
43
    {
44
        $envKey = strtoupper(strtr($key, '.-', '__'));
45
        return getenv($envKey) ?: $defaultFallback;
46
    }
47
48
    /**
49
     * @inheritdoc
50
     */
51
    public function set($key, $value)
52
    {
53
        throw new \Exception('Cannot call "set" on environmental configuration.');
54
    }
55
56
    /**
57
     * @inheritdoc
58
     */
59
    public function import($data)
60
    {
61
        // no-op
62
    }
63
64
    /**
65
     * @inheritdoc
66
     */
67
    public function export()
68
    {
69
        return [];
70
    }
71
72
    /**
73
     * @inheritdoc
74
     */
75
    public function hasDefault($key)
76
    {
77
        return false;
78
    }
79
80
    /**
81
     * @inheritdoc
82
     */
83
    public function getDefault($key, $defaultFallback = null)
84
    {
85
        return $defaultFallback;
86
    }
87
88
    /**
89
     * @inheritdoc
90
     */
91
    public function setDefault($key, $value)
92
    {
93
        throw new \Exception('Cannot call "setDefault" on environmental configuration.');
94
    }
95
}
96