Skip to content

Commit

Permalink
Implement variable name whitelist (#398)
Browse files Browse the repository at this point in the history
  • Loading branch information
GrahamCampbell authored Dec 13, 2019
1 parent c9af337 commit 508fd44
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/Loader/Loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,25 @@

class Loader implements LoaderInterface
{
/**
* The variable name whitelist.
*
* @var string[]|null
*/
protected $whitelist;

/**
* Create a new loader instance.
*
* @param string[]|null $whitelist
*
* @return void
*/
public function __construct(array $whitelist = null)
{
$this->whitelist = $whitelist;
}

/**
* Load the given environment file content into the repository.
*
Expand All @@ -20,7 +39,7 @@ class Loader implements LoaderInterface
*/
public function load(RepositoryInterface $repository, $content)
{
return self::processEntries(
return $this->processEntries(
$repository,
Lines::process(Regex::split("/(\r\n|\n|\r)/", $content)->getSuccess())
);
Expand All @@ -39,14 +58,16 @@ public function load(RepositoryInterface $repository, $content)
*
* @return array<string,string|null>
*/
private static function processEntries(RepositoryInterface $repository, array $entries)
private function processEntries(RepositoryInterface $repository, array $entries)
{
$vars = [];

foreach ($entries as $entry) {
list($name, $value) = Parser::parse($entry);
$vars[$name] = self::resolveNestedVariables($repository, $value);
$repository->set($name, $vars[$name]);
if ($this->whitelist === null || in_array($name, $this->whitelist, true)) {
$vars[$name] = self::resolveNestedVariables($repository, $value);
$repository->set($name, $vars[$name]);
}
}

return $vars;
Expand Down
12 changes: 12 additions & 0 deletions tests/Dotenv/LoaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@ public function testLoaderWithNoReaders()
$this->assertSame($expected, $loader->load($repository, $content));
}

public function testLoaderWithWhitelist()
{
$adapter = new ArrayAdapter();
$repository = RepositoryBuilder::create()->withReaders([$adapter])->withWriters([$adapter])->make();
$loader = new Loader(['FOO']);

$this->assertSame(['FOO' => 'Hello'], $loader->load($repository, "FOO=\"Hello\"\nBAR=\"World!\"\n"));
$this->assertTrue($adapter->get('FOO')->isDefined());
$this->assertSame('Hello', $adapter->get('FOO')->get());
$this->assertFalse($adapter->get('BAR')->isDefined());
}

public function providesAdapters()
{
return [
Expand Down

0 comments on commit 508fd44

Please sign in to comment.