Debian Codegraph @

lib/3rdParty/composer/illuminate/support/Env.php

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support;
4
5 use Closure;
6 use Dotenv\Repository\Adapter\PutenvAdapter;
7 use Dotenv\Repository\RepositoryBuilder;
8 use Illuminate\Filesystem\Filesystem;
9 use PhpOption\Option;
10 use RuntimeException;
11
12 class Env
13 {
14 /**
15 * Indicates if the putenv adapter is enabled.
16 *
17 * @var bool
18 */
19 protected static $putenv = true;
20
21 /**
22 * The environment repository instance.
23 *
24 * @var \Dotenv\Repository\RepositoryInterface|null
25 */
26 protected static $repository;
27
28 /**
29 * The list of custom adapters for loading environment variables.
30 *
31 * @var array<Closure>
32 */
33 protected static $customAdapters = [];
34
35 /**
36 * Enable the putenv adapter.
37 *
38 * @return void
39 */
40 public static function enablePutenv()
41 {
42 static::$putenv = true;
43 static::$repository = null;
44 }
45
46 /**
47 * Disable the putenv adapter.
48 *
49 * @return void
50 */
51 public static function disablePutenv()
52 {
53 static::$putenv = false;
54 static::$repository = null;
55 }
56
57 /**
58 * Register a custom adapter creator Closure.
59 */
60 public static function extend(Closure $callback, ?string $name = null): void
61 {
62 if (! is_null($name)) {
63 static::$customAdapters[$name] = $callback;
64 } else {
65 static::$customAdapters[] = $callback;
66 }
67
68 static::$repository = null;
69 }
70
71 /**
72 * Get the environment repository instance.
73 *
74 * @return \Dotenv\Repository\RepositoryInterface
75 */
76 public static function getRepository()
77 {
78 if (static::$repository === null) {
79 $builder = RepositoryBuilder::createWithDefaultAdapters();
80
81 if (static::$putenv) {
82 $builder = $builder->addAdapter(PutenvAdapter::class);
83 }
84
85 foreach (static::$customAdapters as $adapter) {
86 $builder = $builder->addAdapter($adapter());
87 }
88
89 static::$repository = $builder->immutable()->make();
90 }
91
92 return static::$repository;
93 }
94
95 /**
96 * Get the value of an environment variable.
97 *
98 * @param string $key
99 * @param mixed $default
100 * @return mixed
101 */
102 public static function get($key, $default = null)
103 {
104 return self::getOption($key)->getOrCall(fn () => value($default));
105 }
106
107 /**
108 * Get the value of a required environment variable.
109 *
110 * @param string $key
111 * @return mixed
112 *
113 * @throws \RuntimeException
114 */
115 public static function getOrFail($key)
116 {
117 return self::getOption($key)->getOrThrow(new RuntimeException("Environment variable [$key] has no value."));
118 }
119
120 /**
121 * Write an array of key-value pairs to the environment file.
122 *
123 * @param array $variables
124 * @param string $pathToFile
125 * @param bool $overwrite
126 * @return void
127 *
128 * @throws \RuntimeException
129 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
130 */
131 public static function writeVariables(array $variables, string $pathToFile, bool $overwrite = false): void
132 {
133 $filesystem = new Filesystem;
134
135 if ($filesystem->missing($pathToFile)) {
136 throw new RuntimeException("The file [{$pathToFile}] does not exist.");
137 }
138
139 $lines = explode(PHP_EOL, $filesystem->get($pathToFile));
140
141 foreach ($variables as $key => $value) {
142 $lines = self::addVariableToEnvContents($key, $value, $lines, $overwrite);
143 }
144
145 $filesystem->put($pathToFile, implode(PHP_EOL, $lines));
146 }
147
148 /**
149 * Write a single key-value pair to the environment file.
150 *
151 * @param string $key
152 * @param mixed $value
153 * @param string $pathToFile
154 * @param bool $overwrite
155 * @return void
156 *
157 * @throws \RuntimeException
158 * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
159 */
160 public static function writeVariable(string $key, mixed $value, string $pathToFile, bool $overwrite = false): void
161 {
162 $filesystem = new Filesystem;
163
164 if ($filesystem->missing($pathToFile)) {
165 throw new RuntimeException("The file [{$pathToFile}] does not exist.");
166 }
167
168 $envContent = $filesystem->get($pathToFile);
169
170 $lines = explode(PHP_EOL, $envContent);
171 $lines = self::addVariableToEnvContents($key, $value, $lines, $overwrite);
172
173 $filesystem->put($pathToFile, implode(PHP_EOL, $lines));
174 }
175
176 /**
177 * Add a variable to the environment file contents.
178 *
179 * @param string $key
180 * @param mixed $value
181 * @param array $envLines
182 * @param bool $overwrite
183 * @return array
184 */
185 protected static function addVariableToEnvContents(string $key, mixed $value, array $envLines, bool $overwrite): array
186 {
187 $prefix = explode('_', $key)[0].'_';
188 $lastPrefixIndex = -1;
189
190 $shouldQuote = preg_match('/^[a-zA-Z0-9]+$/', $value) === 0;
191
192 $lineToAddVariations = [
193 $key.'='.(is_string($value) ? self::prepareQuotedValue($value) : $value),
194 $key.'='.$value,
195 ];
196
197 $lineToAdd = $shouldQuote ? $lineToAddVariations[0] : $lineToAddVariations[1];
198
199 if ($value === '') {
200 $lineToAdd = $key.'=';
201 }
202
203 foreach ($envLines as $index => $line) {
204 if (str_starts_with($line, $prefix)) {
205 $lastPrefixIndex = $index;
206 }
207
208 if (in_array($line, $lineToAddVariations)) {
209 // This exact line already exists, so we don't need to add it again.
210 return $envLines;
211 }
212
213 if ($line === $key.'=') {
214 // If the value is empty, we can replace it with the new value.
215 $envLines[$index] = $lineToAdd;
216
217 return $envLines;
218 }
219
220 if (str_starts_with($line, $key.'=')) {
221 if (! $overwrite) {
222 return $envLines;
223 }
224
225 $envLines[$index] = $lineToAdd;
226
227 return $envLines;
228 }
229 }
230
231 if ($lastPrefixIndex === -1) {
232 if (count($envLines) && $envLines[count($envLines) - 1] !== '') {
233 $envLines[] = '';
234 }
235
236 return array_merge($envLines, [$lineToAdd]);
237 }
238
239 return array_merge(
240 array_slice($envLines, 0, $lastPrefixIndex + 1),
241 [$lineToAdd],
242 array_slice($envLines, $lastPrefixIndex + 1)
243 );
244 }
245
246 /**
247 * Get the possible option for this environment variable.
248 *
249 * @param string $key
250 * @return \PhpOption\Option|\PhpOption\Some
251 */
252 protected static function getOption($key)
253 {
254 return Option::fromValue(static::getRepository()->get($key))
255 ->map(function ($value) {
256 switch (strtolower($value)) {
257 case 'true':
258 case '(true)':
259 return true;
260 case 'false':
261 case '(false)':
262 return false;
263 case 'empty':
264 case '(empty)':
265 return '';
266 case 'null':
267 case '(null)':
268 return;
269 }
270
271 if (preg_match('/\A([\'"])(.*)\1\z/', $value, $matches)) {
272 return $matches[2];
273 }
274
275 return $value;
276 });
277 }
278
279 /**
280 * Wrap a string in quotes, choosing double or single quotes.
281 *
282 * @param string $input
283 * @return string
284 */
285 protected static function prepareQuotedValue(string $input)
286 {
287 return str_contains($input, '"')
288 ? "'".self::addSlashesExceptFor($input, ['"'])."'"
289 : '"'.self::addSlashesExceptFor($input, ["'"]).'"';
290 }
291
292 /**
293 * Escape a string using addslashes, excluding the specified characters from being escaped.
294 *
295 * @param string $value
296 * @param array $except
297 * @return string
298 */
299 protected static function addSlashesExceptFor(string $value, array $except = [])
300 {
301 $escaped = addslashes($value);
302
303 foreach ($except as $character) {
304 $escaped = str_replace('\\'.$character, $character, $escaped);
305 }
306
307 return $escaped;
308 }
309 }