put env tool

This commit is contained in:
Sieciech 2021-08-07 11:05:46 +02:00
parent e6b52c6d87
commit 69a6029555
3 changed files with 55 additions and 15 deletions

View File

@ -1,15 +0,0 @@
<?php
namespace Tools;
class PutEnv {
private string $file;
private string $key;
private string $value;
public function __construct() {
$argv = $_SERVER['argv'];
print_r($argv);
}
}
new PutEnv();

5
tools/putenv/env Normal file
View File

@ -0,0 +1,5 @@
name=value
name2="value 2"
#name3=value3
name4 = value4
name5 = "value 5"

50
tools/putenv/putenv.php Normal file
View File

@ -0,0 +1,50 @@
<?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);
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;
}
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();