Passed
Push — develop ( 43a598...04e7b2 )
by nguereza
02:46
created

Loader::setValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 5
rs 10
1
<?php
2
3
/**
4
 * Platine Framework
5
 *
6
 * Platine Framework is a lightweight, high-performance, simple and elegant
7
 * PHP Web framework
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Framework
12
 * Copyright (c) 2017 Jitendra Adhikari
13
 *
14
 * Permission is hereby granted, free of charge, to any person obtaining a copy
15
 * of this software and associated documentation files (the "Software"), to deal
16
 * in the Software without restriction, including without limitation the rights
17
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
 * copies of the Software, and to permit persons to whom the Software is
19
 * furnished to do so, subject to the following conditions:
20
 *
21
 * The above copyright notice and this permission notice shall be included in all
22
 * copies or substantial portions of the Software.
23
 *
24
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
 * SOFTWARE.
31
 */
32
33
/**
34
 *  @file Loader.php
35
 *
36
 *  The Environment Loader class
37
 *
38
 *  @package    Platine\Framework\Env
39
 *  @author Platine Developers team
40
 *  @copyright  Copyright (c) 2020
41
 *  @license    http://opensource.org/licenses/MIT  MIT License
42
 *  @link   http://www.iacademy.cf
43
 *  @version 1.0.0
44
 *  @filesource
45
 */
46
47
declare(strict_types=1);
48
49
namespace Platine\Framework\Env;
50
51
use InvalidArgumentException;
52
use RuntimeException;
53
54
/**
55
 * @class Loader
56
 * @package Platine\Framework\Env
57
 */
58
class Loader
59
{
60
    /**
61
     * Put the parsed key value pair into
62
     * $_ENV super global.
63
     */
64
    public const ENV = 1;
65
66
    /**
67
     * Put the parsed key value pair into "putenv()".
68
     */
69
    public const PUTENV = 2;
70
71
    /**
72
     * Put the parsed key value pair into
73
     * $_SERVER super global.
74
     */
75
    public const SERVER = 4;
76
77
    /**
78
     * Put the parsed key value pair into all of the sources.
79
     */
80
    public const ALL = 7;
81
82
    /**
83
     * Loads environment file and puts the key value pair
84
     * in one or all of putenv()/$_ENV/$_SERVER.
85
     * @param string $file
86
     * @param bool $overwrite
87
     * @param int $mode
88
     * @return void
89
     */
90
    public function load(
91
        string $file,
92
        bool $overwrite = false,
93
        int $mode = self::PUTENV
94
    ): void {
95
        if (!is_file($file)) {
96
            throw new InvalidArgumentException(sprintf(
97
                'The [%s] file does not exist or is not readable',
98
                $file
99
            ));
100
        }
101
102
        $fileContent = (string) file_get_contents($file);
103
        // Get file contents, fix the comments and parse as ini.
104
        $content = (string) preg_replace('/^\s*#/m', ';', $fileContent);
105
        $parsed  = parse_ini_string($content, false, INI_SCANNER_RAW);
106
107
        if ($parsed === false) {
108
            throw new RuntimeException(sprintf(
109
                'The [%s] file cannot be parsed due to malformed values',
110
                $file
111
            ));
112
        }
113
114
        $this->setValues($parsed, $overwrite, $mode);
115
    }
116
117
    /**
118
     * Set the environment values from given variables.
119
     * @param array<string, mixed> $vars
120
     * @param bool $overwrite
121
     * @param int $mode
122
     * @return void
123
     */
124
    protected function setValues(
125
        array $vars,
126
        bool $overwrite,
127
        int $mode
128
    ): void {
129
        $default = microtime(true);
130
        foreach ($vars as $key => $value) {
131
            // Skip if we already have value and cant override.
132
            if (!$overwrite && $default !== Env::get($key, $default)) {
133
                continue;
134
            }
135
136
            $this->setValue($key, $value, $mode);
137
        }
138
139
        $this->resolveReferences($vars, $mode);
140
    }
141
142
    /**
143
     * Set environment value for the given key
144
     * @param string $key
145
     * @param string $value
146
     * @param int $mode
147
     * @return void
148
     */
149
    protected function setValue(string $key, string $value, int $mode): void
150
    {
151
        $this->setValueEnv($key, $value, $mode);
152
        $this->setValueServer($key, $value, $mode);
153
        $this->setValuePutenv($key, $value, $mode);
154
    }
155
156
    /**
157
     * Resolve variable references like MY_KEY=${VAR_NAME}
158
     * @param array<string, mixed> $vars
159
     * @param int $mode
160
     * @return void
161
     */
162
    protected function resolveReferences(
163
        array $vars,
164
        int $mode
165
    ): void {
166
        foreach ($vars as $key => $value) {
167
            if (!$value || strpos($value, '${') === false) {
168
                continue;
169
            }
170
171
            $value = preg_replace_callback('~\$\{(\w+)\}~', function ($m) {
172
                return (null === $ref = Env::get($m[1], null)) ? $m[0] : $ref;
173
            }, $value);
174
175
            $this->setValue($key, $value, $mode);
176
        }
177
    }
178
179
    /**
180
     * Set environment value for the given key to $_ENV
181
     * @param string $key
182
     * @param string $value
183
     * @param int $mode
184
     * @return void
185
     */
186
    protected function setValueEnv(string $key, string $value, int $mode): void
187
    {
188
        if ($mode & self::ENV) {
189
            $_ENV[$key] = $value;
190
        }
191
    }
192
193
    /**
194
     * Set environment value for the given key to $_SERVER
195
     * @param string $key
196
     * @param string $value
197
     * @param int $mode
198
     * @return void
199
     */
200
    protected function setValueServer(string $key, string $value, int $mode): void
201
    {
202
        if ($mode & self::SERVER) {
203
            $_SERVER[$key] = $value;
204
        }
205
    }
206
207
    /**
208
     * Set environment value for the given key to "putenv()"
209
     * @param string $key
210
     * @param string $value
211
     * @param int $mode
212
     * @return void
213
     */
214
    protected function setValuePutenv(string $key, string $value, int $mode): void
215
    {
216
        if ($mode & self::PUTENV) {
217
            putenv("$key=$value");
218
        }
219
    }
220
}
221