Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Traits/Commands/EnvironmentWriterTrait.php
10284 views
1
<?php
2
3
namespace Pterodactyl\Traits\Commands;
4
5
use Pterodactyl\Exceptions\PterodactylException;
6
7
trait EnvironmentWriterTrait
8
{
9
/**
10
* Escapes an environment value by looking for any characters that could
11
* reasonably cause environment parsing issues. Those values are then wrapped
12
* in quotes before being returned.
13
*/
14
public function escapeEnvironmentValue(?string $value): string
15
{
16
if (is_null($value)) {
17
return '';
18
}
19
20
if (!preg_match('/^\"(.*)\"$/', $value) && preg_match('/([^\w.\-+\/])+/', $value)) {
21
return sprintf('"%s"', addslashes($value));
22
}
23
24
return $value;
25
}
26
27
/**
28
* Update the .env file for the application using the passed in values.
29
*
30
* @throws PterodactylException
31
*/
32
public function writeToEnvironment(array $values = []): void
33
{
34
$path = base_path('.env');
35
if (!file_exists($path)) {
36
throw new PterodactylException('Cannot locate .env file, was this software installed correctly?');
37
}
38
39
$saveContents = file_get_contents($path);
40
collect($values)->each(function ($value, $key) use (&$saveContents) {
41
$key = strtoupper($key);
42
$saveValue = sprintf('%s=%s', $key, $this->escapeEnvironmentValue($value));
43
44
if (preg_match_all('/^' . $key . '=(.*)$/m', $saveContents) < 1) {
45
$saveContents = $saveContents . PHP_EOL . $saveValue;
46
} else {
47
$saveContents = preg_replace('/^' . $key . '=(.*)$/m', $saveValue, $saveContents);
48
}
49
});
50
51
file_put_contents($path, $saveContents);
52
}
53
}
54
55