Loader::setValues()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
c 3
b 0
f 0
nc 3
nop 3
dl 0
loc 17
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   https://www.platine-php.com
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) === false) {
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
131
        foreach ($vars as $key => $value) {
132
            // Skip if we already have value and cant override.
133
            if ($overwrite === false && $default !== Env::get($key, $default)) {
134
                continue;
135
            }
136
137
            $this->setValue($key, $value, $mode);
138
        }
139
140
        $this->resolveReferences($vars, $mode);
141
    }
142
143
    /**
144
     * Set environment value for the given key
145
     * @param string $key
146
     * @param string $value
147
     * @param int $mode
148
     * @return void
149
     */
150
    protected function setValue(string $key, string $value, int $mode): void
151
    {
152
        $this->setValueEnv($key, $value, $mode);
153
        $this->setValueServer($key, $value, $mode);
154
        $this->setValuePutenv($key, $value, $mode);
155
    }
156
157
    /**
158
     * Resolve variable references like MY_KEY=${VAR_NAME}
159
     * @param array<string, mixed> $vars
160
     * @param int $mode
161
     * @return void
162
     */
163
    protected function resolveReferences(
164
        array $vars,
165
        int $mode
166
    ): void {
167
        foreach ($vars as $key => $value) {
168
            if (!$value || strpos($value, '${') === false) {
169
                continue;
170
            }
171
172
            $value = preg_replace_callback('~\$\{(\w+)\}~', function ($m) {
173
                return (null === $ref = Env::get($m[1], null)) ? $m[0] : $ref;
174
            }, $value);
175
176
            $this->setValue($key, $value, $mode);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type null; however, parameter $value of Platine\Framework\Env\Loader::setValue() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

176
            $this->setValue($key, /** @scrutinizer ignore-type */ $value, $mode);
Loading history...
177
        }
178
    }
179
180
    /**
181
     * Set environment value for the given key to $_ENV
182
     * @param string $key
183
     * @param string $value
184
     * @param int $mode
185
     * @return void
186
     */
187
    protected function setValueEnv(string $key, string $value, int $mode): void
188
    {
189
        if ($mode & self::ENV) {
190
            $_ENV[$key] = $value;
191
        }
192
    }
193
194
    /**
195
     * Set environment value for the given key to $_SERVER
196
     * @param string $key
197
     * @param string $value
198
     * @param int $mode
199
     * @return void
200
     */
201
    protected function setValueServer(string $key, string $value, int $mode): void
202
    {
203
        if ($mode & self::SERVER) {
204
            $_SERVER[$key] = $value;
205
        }
206
    }
207
208
    /**
209
     * Set environment value for the given key to "putenv()"
210
     * @param string $key
211
     * @param string $value
212
     * @param int $mode
213
     * @return void
214
     */
215
    protected function setValuePutenv(string $key, string $value, int $mode): void
216
    {
217
        if ($mode & self::PUTENV) {
218
            putenv("$key=$value");
219
        }
220
    }
221
}
222