Skip to content

Commit

Permalink
set should accept 'mixed' instead of 'string'
Browse files Browse the repository at this point in the history
  • Loading branch information
iRaziul committed Feb 4, 2024
1 parent 7b04200 commit 37cc7a7
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions src/DotEnvEditor.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
Expand All @@ -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 {
Expand All @@ -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
*/
Expand Down

0 comments on commit 37cc7a7

Please sign in to comment.