Skip to content

Commit

Permalink
bug #21 Added custom dotenv variable value formatter (Marius Sprunskas)
Browse files Browse the repository at this point in the history
This PR was merged into the master branch.

Discussion
----------

Added custom dotenv variable value formatter

Jackiedo\DotenvEditor\DotenvFormatter::formatValue method makes assumption, that value must be escaped if slashes are present. It does not work properly, when type of env variable is JSON (https://symfony.com/blog/new-in-symfony-3-4-advanced-environment-variables), example:
```
#.env.dist
SPECIAL_IPS="[\"127.0.0.1/8\", \"172.17.0.1/16\"]"
```
we get
```
#.env
SPECIAL_IPS="\"[\\\"127.0.0.1/8\\\", \\\"172.17.0.1/16\\\"]\""
```
Ideallly, helper generated .env file shoud be identical file to dist file, but without comments.

Commits
-------

d182b15 Added custom dotenv variable value formatter
  • Loading branch information
sroze committed Mar 18, 2019
2 parents 67591cb + d182b15 commit bff66f3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Companienv/Companion.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@

use Companienv\DotEnv\Block;
use Companienv\DotEnv\MissingVariable;
use Companienv\DotEnv\ValueFormatter;
use Companienv\DotEnv\Parser;
use Companienv\IO\FileSystem\FileSystem;
use Companienv\IO\Interaction;
use Jackiedo\DotenvEditor\DotenvFormatter;
use Jackiedo\DotenvEditor\DotenvWriter;

class Companion
Expand Down Expand Up @@ -89,7 +89,7 @@ private function writeVariable(string $name, string $value)

$variablesInFileHash = $this->getDefinedVariablesHash();

$writer = new DotenvWriter(new DotenvFormatter());
$writer = new DotenvWriter(new ValueFormatter());
$fileContents = $this->fileSystem->getContents($this->envFileName);
$writer->setBuffer($fileContents);

Expand Down
21 changes: 21 additions & 0 deletions src/Companienv/DotEnv/ValueFormatter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Companienv\DotEnv;

use Jackiedo\DotenvEditor\DotenvFormatter;

class ValueFormatter extends DotenvFormatter
{
public function formatValue($value, $forceQuotes = false)
{
if (!$forceQuotes) {
return $value;
}

$value = str_replace('\\', '\\\\', $value);
$value = str_replace('"', '\"', $value);
$value = "\"{$value}\"";

return $value;
}
}

0 comments on commit bff66f3

Please sign in to comment.