From 37cc7a76795348f9a8fc67b03b29940e0e9de44a Mon Sep 17 00:00:00 2001 From: iRaziul Date: Sun, 4 Feb 2024 17:08:14 +0600 Subject: [PATCH] set should accept 'mixed' instead of 'string' --- src/DotEnvEditor.php | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/DotEnvEditor.php b/src/DotEnvEditor.php index f63827b..a397e22 100644 --- a/src/DotEnvEditor.php +++ b/src/DotEnvEditor.php @@ -122,7 +122,7 @@ public function remove(string $key): self /** * Set an environment variable or an array of environment variables */ - public function set(string|array $key, string $value = null) + public function set(string|array $key, mixed $value = null) { if (is_array($key)) { foreach ($key as $k => $v) { @@ -132,10 +132,6 @@ public function set(string|array $key, string $value = null) return $this; } - if (is_string($value) && str_contains($value, ' ')) { - $value = '"'.$value.'"'; - } - $this->newEnv[str_replace('.', '_', strtoupper($key))] = $value; return $this; @@ -151,6 +147,8 @@ public function write(): bool // get keys for replacing and appending foreach ($this->newEnv as $key => $value) { + $value = $this->castValue($value); + if (array_key_exists($key, $this->env)) { $replace[$key.'='.$this->env[$key]] = $key.'='.$value; } else { @@ -173,6 +171,29 @@ public function write(): bool return file_put_contents($this->envFilePath, $env) !== false; } + /** + * Cast the value appropriately + */ + private function castValue(mixed $value): string + { + if (is_bool($value)) { + return $value ? 'true' : 'false'; + } + + if (is_null($value)) { + return ''; + } + + if (is_string($value) && ( + str_contains($value, ' ') + || str_starts_with($value, '${') && str_ends_with($value, '}') + )) { + return '"'.$value.'"'; + } + + return $value; + } + /** * Parse the env data to an array */