2021-08-07 09:05:46 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Tools;
|
|
|
|
|
|
|
|
class PutEnv {
|
|
|
|
private string $file;
|
|
|
|
private string $key;
|
|
|
|
private string $value;
|
|
|
|
private array $content;
|
|
|
|
public function __construct() {
|
|
|
|
$argv = $_SERVER['argv'];
|
|
|
|
$argc = sizeof($argv);
|
2021-08-07 09:17:47 +00:00
|
|
|
print_r([$argc, $argv]);
|
2021-08-07 09:05:46 +00:00
|
|
|
switch($argc) {
|
|
|
|
case 3:
|
|
|
|
$this->file = $argv[1];
|
|
|
|
$this->key = $argv[2];
|
|
|
|
$this->value -> $argv[3];
|
|
|
|
break;
|
|
|
|
|
|
|
|
case 2:
|
|
|
|
$this->file = $argv[1];
|
|
|
|
$this->key = $argv[2];
|
|
|
|
$this->value = fgets(STDIN);
|
|
|
|
break;
|
2021-08-07 09:17:47 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
echo "usage:
|
|
|
|
php8.0 putenv.php filename key value
|
|
|
|
echo value | php8.0 putenv filename key";
|
|
|
|
throw new Exception("invalid params");
|
2021-08-07 09:05:46 +00:00
|
|
|
}
|
|
|
|
if (!file_exists($this->file)) {
|
|
|
|
throw new Exception('File not found');
|
|
|
|
}
|
|
|
|
$this->content = file($this->file);
|
|
|
|
foreach ($this->content as $l => $line) {
|
|
|
|
if (!str_starts_with($line, $this->key)) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
$next = trim(substr($line, strlen($this->key)));
|
|
|
|
if (strlen($next) === 0 || $next[0] !== '=') {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
$key = $this->key;
|
|
|
|
$value = $this->value;
|
|
|
|
if (strpos($value, ' ') !== false) {
|
|
|
|
$value = '"' . addslashes($value) . '"';
|
|
|
|
}
|
|
|
|
$this->content[$l] = $key . '=' . $value;
|
|
|
|
}
|
|
|
|
$content = implode("\n", $this->content);
|
|
|
|
file_put_contents($this->file, $content);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
new PutEnv();
|