upgraded dependencies

This commit is contained in:
RafficMohammed
2023-01-08 01:59:16 +05:30
parent 51056e3aad
commit f9ae387337
6895 changed files with 133617 additions and 178680 deletions

View File

@@ -16,30 +16,43 @@
}
],
"require": {
"php": "^5.4 || ^7.0 || ^8.0",
"phpoption/phpoption": "^1.5.2",
"php": "^5.5.9 || ^7.0 || ^8.0",
"phpoption/phpoption": "^1.7.3",
"symfony/polyfill-ctype": "^1.17"
},
"require-dev": {
"ext-filter": "*",
"ext-pcre": "*",
"phpunit/phpunit": "^4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.21"
"bamarni/composer-bin-plugin": "^1.4.1",
"phpunit/phpunit": "^4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.30"
},
"autoload": {
"psr-4": {
"Dotenv\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Dotenv\\Tests\\": "tests/Dotenv/"
}
},
"suggest": {
"ext-filter": "Required to use the boolean validator.",
"ext-pcre": "Required to use most of the library."
},
"config": {
"allow-plugins": {
"bamarni/composer-bin-plugin": true
},
"preferred-install": "dist"
},
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": true
},
"branch-alias": {
"dev-master": "3.6-dev"
"dev-master": "4.3-dev"
}
}
}

View File

@@ -2,127 +2,178 @@
namespace Dotenv;
use Dotenv\Environment\DotenvFactory;
use Dotenv\Environment\FactoryInterface;
use Dotenv\Exception\InvalidPathException;
use Dotenv\Loader\Loader;
use Dotenv\Loader\LoaderInterface;
use Dotenv\Repository\Adapter\ArrayAdapter;
use Dotenv\Repository\RepositoryBuilder;
use Dotenv\Repository\RepositoryInterface;
use Dotenv\Store\FileStore;
use Dotenv\Store\StoreBuilder;
use Dotenv\Store\StringStore;
/**
* This is the dotenv class.
*
* It's responsible for loading a `.env` file in the given directory and
* setting the environment variables.
*/
class Dotenv
{
/**
* The loader instance.
*
* @var \Dotenv\Loader
* @var \Dotenv\Loader\LoaderInterface
*/
protected $loader;
/**
* The repository instance.
*
* @var \Dotenv\Repository\RepositoryInterface
*/
protected $repository;
/**
* The store instance.
*
* @var \Dotenv\Store\StoreInterface
*/
protected $store;
/**
* Create a new dotenv instance.
*
* @param \Dotenv\Loader $loader
* @param \Dotenv\Loader\LoaderInterface $loader
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param \Dotenv\Store\StoreInterface|string[] $store
*
* @return void
*/
public function __construct(Loader $loader)
public function __construct(LoaderInterface $loader, RepositoryInterface $repository, $store)
{
$this->loader = $loader;
$this->repository = $repository;
$this->store = is_array($store) ? new FileStore($store, true) : $store;
}
/**
* Create a new dotenv instance.
*
* @param string|string[] $paths
* @param string|null $file
* @param \Dotenv\Environment\FactoryInterface|null $envFactory
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param string|string[] $paths
* @param string|string[]|null $names
* @param bool $shortCircuit
*
* @return \Dotenv\Dotenv
*/
public static function create($paths, $file = null, FactoryInterface $envFactory = null)
public static function create(RepositoryInterface $repository, $paths, $names = null, $shortCircuit = true)
{
$loader = new Loader(
self::getFilePaths((array) $paths, $file ?: '.env'),
$envFactory ?: new DotenvFactory(),
true
);
$builder = StoreBuilder::create()->withPaths($paths)->withNames($names);
return new self($loader);
if ($shortCircuit) {
$builder = $builder->shortCircuit();
}
return new self(new Loader(), $repository, $builder->make());
}
/**
* Returns the full paths to the files.
* Create a new mutable dotenv instance with default repository.
*
* @param string[] $paths
* @param string $file
* @param string|string[] $paths
* @param string|string[]|null $names
* @param bool $shortCircuit
*
* @return string[]
* @return \Dotenv\Dotenv
*/
private static function getFilePaths(array $paths, $file)
public static function createMutable($paths, $names = null, $shortCircuit = true)
{
return array_map(function ($path) use ($file) {
return rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file;
}, $paths);
$repository = RepositoryBuilder::create()->make();
return self::create($repository, $paths, $names, $shortCircuit);
}
/**
* Load environment file in given directory.
* Create a new immutable dotenv instance with default repository.
*
* @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidFileException
* @param string|string[] $paths
* @param string|string[]|null $names
* @param bool $shortCircuit
*
* @return array<string|null>
* @return \Dotenv\Dotenv
*/
public function load()
public static function createImmutable($paths, $names = null, $shortCircuit = true)
{
return $this->loadData();
$repository = RepositoryBuilder::create()->immutable()->make();
return self::create($repository, $paths, $names, $shortCircuit);
}
/**
* Load environment file in given directory, silently failing if it doesn't exist.
* Create a new dotenv instance with an array backed repository.
*
* @param string|string[] $paths
* @param string|string[]|null $names
* @param bool $shortCircuit
*
* @return \Dotenv\Dotenv
*/
public static function createArrayBacked($paths, $names = null, $shortCircuit = true)
{
$adapter = new ArrayAdapter();
$repository = RepositoryBuilder::create()->withReaders([$adapter])->withWriters([$adapter])->make();
return self::create($repository, $paths, $names, $shortCircuit);
}
/**
* Parse the given content and resolve nested variables.
*
* This method behaves just like load(), only without mutating your actual
* environment. We do this by using an array backed repository.
*
* @param string $content
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array<string|null>
* @return array<string,string|null>
*/
public static function parse($content)
{
$adapter = new ArrayAdapter();
$repository = RepositoryBuilder::create()->withReaders([$adapter])->withWriters([$adapter])->make();
$phpdotenv = new self(new Loader(), $repository, new StringStore($content));
return $phpdotenv->load();
}
/**
* Read and load environment file(s).
*
* @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidFileException
*
* @return array<string,string|null>
*/
public function load()
{
return $this->loader->load($this->repository, $this->store->read());
}
/**
* Read and load environment file(s), silently failing if no files can be read.
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array<string,string|null>
*/
public function safeLoad()
{
try {
return $this->loadData();
return $this->load();
} catch (InvalidPathException $e) {
// suppressing exception
return [];
}
}
/**
* Load environment file in given directory.
*
* @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidFileException
*
* @return array<string|null>
*/
public function overload()
{
return $this->loadData(true);
}
/**
* Actually load the data.
*
* @param bool $overload
*
* @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidFileException
*
* @return array<string|null>
*/
protected function loadData($overload = false)
{
return $this->loader->setImmutable(!$overload)->load();
}
/**
* Required ensures that the specified variables exist, and returns a new validator object.
*
@@ -132,7 +183,7 @@ class Dotenv
*/
public function required($variables)
{
return new Validator((array) $variables, $this->loader);
return new Validator($this->repository, (array) $variables);
}
/**
@@ -144,16 +195,6 @@ class Dotenv
*/
public function ifPresent($variables)
{
return new Validator((array) $variables, $this->loader, false);
}
/**
* Get the list of environment variables declared inside the 'env' file.
*
* @return string[]
*/
public function getEnvironmentVariableNames()
{
return $this->loader->getEnvironmentVariableNames();
return new Validator($this->repository, (array) $variables, false);
}
}

View File

@@ -1,41 +0,0 @@
<?php
namespace Dotenv\Environment\Adapter;
interface AdapterInterface
{
/**
* Determines if the adapter is supported.
*
* @return bool
*/
public function isSupported();
/**
* Get an environment variable, if it exists.
*
* @param string $name
*
* @return \PhpOption\Option
*/
public function get($name);
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
*
* @return void
*/
public function set($name, $value = null);
/**
* Clear an environment variable.
*
* @param string $name
*
* @return void
*/
public function clear($name);
}

View File

@@ -1,60 +0,0 @@
<?php
namespace Dotenv\Environment\Adapter;
use PhpOption\None;
use PhpOption\Some;
class EnvConstAdapter implements AdapterInterface
{
/**
* Determines if the adapter is supported.
*
* @return bool
*/
public function isSupported()
{
return true;
}
/**
* Get an environment variable, if it exists.
*
* @param string $name
*
* @return \PhpOption\Option
*/
public function get($name)
{
if (array_key_exists($name, $_ENV)) {
return Some::create($_ENV[$name]);
}
return None::create();
}
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
*
* @return void
*/
public function set($name, $value = null)
{
$_ENV[$name] = $value;
}
/**
* Clear an environment variable.
*
* @param string $name
*
* @return void
*/
public function clear($name)
{
unset($_ENV[$name]);
}
}

View File

@@ -1,60 +0,0 @@
<?php
namespace Dotenv\Environment\Adapter;
use PhpOption\None;
use PhpOption\Some;
class ServerConstAdapter implements AdapterInterface
{
/**
* Determines if the adapter is supported.
*
* @return bool
*/
public function isSupported()
{
return true;
}
/**
* Get an environment variable, if it exists.
*
* @param string $name
*
* @return \PhpOption\Option
*/
public function get($name)
{
if (array_key_exists($name, $_SERVER)) {
return Some::create($_SERVER[$name]);
}
return None::create();
}
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
*
* @return void
*/
public function set($name, $value = null)
{
$_SERVER[$name] = $value;
}
/**
* Clear an environment variable.
*
* @param string $name
*
* @return void
*/
public function clear($name)
{
unset($_SERVER[$name]);
}
}

View File

@@ -1,58 +0,0 @@
<?php
namespace Dotenv\Environment;
use Dotenv\Environment\Adapter\AdapterInterface;
use Dotenv\Environment\Adapter\ApacheAdapter;
use Dotenv\Environment\Adapter\EnvConstAdapter;
use Dotenv\Environment\Adapter\PutenvAdapter;
use Dotenv\Environment\Adapter\ServerConstAdapter;
/**
* The default implementation of the environment factory interface.
*/
class DotenvFactory implements FactoryInterface
{
/**
* The set of adapters to use.
*
* @var \Dotenv\Environment\Adapter\AdapterInterface[]
*/
protected $adapters;
/**
* Create a new dotenv environment factory instance.
*
* If no adapters are provided, then the defaults will be used.
*
* @param \Dotenv\Environment\Adapter\AdapterInterface[]|null $adapters
*
* @return void
*/
public function __construct(array $adapters = null)
{
$this->adapters = array_filter($adapters === null ? [new ApacheAdapter(), new EnvConstAdapter(), new ServerConstAdapter(), new PutenvAdapter()] : $adapters, function (AdapterInterface $adapter) {
return $adapter->isSupported();
});
}
/**
* Creates a new mutable environment variables instance.
*
* @return \Dotenv\Environment\VariablesInterface
*/
public function create()
{
return new DotenvVariables($this->adapters, false);
}
/**
* Creates a new immutable environment variables instance.
*
* @return \Dotenv\Environment\VariablesInterface
*/
public function createImmutable()
{
return new DotenvVariables($this->adapters, true);
}
}

View File

@@ -1,78 +0,0 @@
<?php
namespace Dotenv\Environment;
/**
* The default implementation of the environment variables interface.
*/
class DotenvVariables extends AbstractVariables
{
/**
* The set of adapters to use.
*
* @var \Dotenv\Environment\Adapter\AdapterInterface[]
*/
protected $adapters;
/**
* Create a new dotenv environment variables instance.
*
* @param \Dotenv\Environment\Adapter\AdapterInterface[] $adapters
* @param bool $immutable
*
* @return void
*/
public function __construct(array $adapters, $immutable)
{
$this->adapters = $adapters;
parent::__construct($immutable);
}
/**
* Get an environment variable.
*
* We do this by querying our adapters sequentially.
*
* @param string $name
*
* @return string|null
*/
protected function getInternal($name)
{
foreach ($this->adapters as $adapter) {
$result = $adapter->get($name);
if ($result->isDefined()) {
return $result->get();
}
}
}
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
*
* @return void
*/
protected function setInternal($name, $value = null)
{
foreach ($this->adapters as $adapter) {
$adapter->set($name, $value);
}
}
/**
* Clear an environment variable.
*
* @param string $name
*
* @return void
*/
protected function clearInternal($name)
{
foreach ($this->adapters as $adapter) {
$adapter->clear($name);
}
}
}

View File

@@ -1,26 +0,0 @@
<?php
namespace Dotenv\Environment;
/**
* This environment factory interface.
*
* If you need custom implementations of the variables interface, implement
* this interface, and use your implementation in the loader.
*/
interface FactoryInterface
{
/**
* Creates a new mutable environment variables instance.
*
* @return \Dotenv\Environment\VariablesInterface
*/
public function create();
/**
* Creates a new immutable environment variables instance.
*
* @return \Dotenv\Environment\VariablesInterface
*/
public function createImmutable();
}

View File

@@ -2,9 +2,6 @@
namespace Dotenv\Exception;
/**
* This is the exception interface.
*/
interface ExceptionInterface
{
//

View File

@@ -4,9 +4,6 @@ namespace Dotenv\Exception;
use InvalidArgumentException;
/**
* This is the invalid file exception class.
*/
class InvalidFileException extends InvalidArgumentException implements ExceptionInterface
{
//

View File

@@ -4,9 +4,6 @@ namespace Dotenv\Exception;
use InvalidArgumentException;
/**
* This is the invalid path exception class.
*/
class InvalidPathException extends InvalidArgumentException implements ExceptionInterface
{
//

View File

@@ -4,9 +4,6 @@ namespace Dotenv\Exception;
use RuntimeException;
/**
* This is the validation exception class.
*/
class ValidationException extends RuntimeException implements ExceptionInterface
{
//

View File

@@ -1,255 +0,0 @@
<?php
namespace Dotenv;
use Dotenv\Environment\FactoryInterface;
use Dotenv\Exception\InvalidPathException;
use Dotenv\Regex\Regex;
use PhpOption\Option;
/**
* This is the loader class.
*
* It's responsible for loading variables by reading a file from disk and:
* - stripping comments beginning with a `#`,
* - parsing lines that look shell variable setters, e.g `export key = value`, `key="value"`.
* - multiline variable look always start with a " and end with it, e.g: `key="value
* value"`
*/
class Loader
{
/**
* The file paths.
*
* @var string[]
*/
protected $filePaths;
/**
* The environment factory instance.
*
* @var \Dotenv\Environment\FactoryInterface
*/
protected $envFactory;
/**
* The environment variables instance.
*
* @var \Dotenv\Environment\VariablesInterface
*/
protected $envVariables;
/**
* The list of environment variables declared inside the 'env' file.
*
* @var string[]
*/
protected $variableNames = [];
/**
* Create a new loader instance.
*
* @param string[] $filePaths
* @param \Dotenv\Environment\FactoryInterface $envFactory
* @param bool $immutable
*
* @return void
*/
public function __construct(array $filePaths, FactoryInterface $envFactory, $immutable = false)
{
$this->filePaths = $filePaths;
$this->envFactory = $envFactory;
$this->setImmutable($immutable);
}
/**
* Set immutable value.
*
* @param bool $immutable
*
* @return $this
*/
public function setImmutable($immutable = false)
{
$this->envVariables = $immutable
? $this->envFactory->createImmutable()
: $this->envFactory->create();
return $this;
}
/**
* Load the environment file from disk.
*
* @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidFileException
*
* @return array<string|null>
*/
public function load()
{
return $this->loadDirect(
self::findAndRead($this->filePaths)
);
}
/**
* Directly load the given string.
*
* @param string $content
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array<string|null>
*/
public function loadDirect($content)
{
return $this->processEntries(
Lines::process(preg_split("/(\r\n|\n|\r)/", $content))
);
}
/**
* Attempt to read the files in order.
*
* @param string[] $filePaths
*
* @throws \Dotenv\Exception\InvalidPathException
*
* @return string[]
*/
private static function findAndRead(array $filePaths)
{
if ($filePaths === []) {
throw new InvalidPathException('At least one environment file path must be provided.');
}
foreach ($filePaths as $filePath) {
$lines = self::readFromFile($filePath);
if ($lines->isDefined()) {
return $lines->get();
}
}
throw new InvalidPathException(
sprintf('Unable to read any of the environment file(s) at [%s].', implode(', ', $filePaths))
);
}
/**
* Read the given file.
*
* @param string $filePath
*
* @return \PhpOption\Option
*/
private static function readFromFile($filePath)
{
$content = @file_get_contents($filePath);
return Option::fromValue($content, false);
}
/**
* Process the environment variable entries.
*
* We'll fill out any nested variables, and acually set the variable using
* the underlying environment variables instance.
*
* @param string[] $entries
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array<string|null>
*/
private function processEntries(array $entries)
{
$vars = [];
foreach ($entries as $entry) {
list($name, $value) = Parser::parse($entry);
$vars[$name] = $this->resolveNestedVariables($value);
$this->setEnvironmentVariable($name, $vars[$name]);
}
return $vars;
}
/**
* Resolve the nested variables.
*
* Look for ${varname} patterns in the variable value and replace with an
* existing environment variable.
*
* @param string|null $value
*
* @return string|null
*/
private function resolveNestedVariables($value = null)
{
return Option::fromValue($value)
->filter(function ($str) {
return strpos($str, '$') !== false;
})
->flatMap(function ($str) {
return Regex::replaceCallback(
'/\${([a-zA-Z0-9_.]+)}/',
function (array $matches) {
return Option::fromValue($this->getEnvironmentVariable($matches[1]))
->getOrElse($matches[0]);
},
$str
)->success();
})
->getOrElse($value);
}
/**
* Search the different places for environment variables and return first value found.
*
* @param string $name
*
* @return string|null
*/
public function getEnvironmentVariable($name)
{
return $this->envVariables->get($name);
}
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
*
* @return void
*/
public function setEnvironmentVariable($name, $value = null)
{
$this->variableNames[] = $name;
$this->envVariables->set($name, $value);
}
/**
* Clear an environment variable.
*
* This method only expects names in normal form.
*
* @param string $name
*
* @return void
*/
public function clearEnvironmentVariable($name)
{
$this->envVariables->clear($name);
}
/**
* Get the list of environment variables names.
*
* @return string[]
*/
public function getEnvironmentVariableNames()
{
return $this->variableNames;
}
}

View File

@@ -1,6 +1,6 @@
<?php
namespace Dotenv;
namespace Dotenv\Loader;
class Lines
{
@@ -37,19 +37,21 @@ class Lines
* @param string $line
* @param string[] $buffer
*
* @return array
* @return array{bool,string,string[]}
*/
private static function multilineProcess($multiline, $line, array $buffer)
{
$startsOnCurrentLine = $multiline ? false : self::looksLikeMultilineStart($line);
// check if $line can be multiline variable
if ($started = self::looksLikeMultilineStart($line)) {
if ($startsOnCurrentLine) {
$multiline = true;
}
if ($multiline) {
array_push($buffer, $line);
if (self::looksLikeMultilineStop($line, $started)) {
if (self::looksLikeMultilineStop($line, $startsOnCurrentLine)) {
$multiline = false;
$line = implode("\n", $buffer);
$buffer = [];
@@ -105,12 +107,13 @@ class Lines
*
* @param string $line
*
* @return bool
* @return array{array{string,string|null}}
*/
private static function getCharPairs($line)
{
$chars = str_split($line);
/** @var array{array{string,string|null}} */
return array_map(null, $chars, array_slice($chars, 1));
}

View File

@@ -0,0 +1,122 @@
<?php
namespace Dotenv\Loader;
use Dotenv\Regex\Regex;
use Dotenv\Repository\RepositoryInterface;
use PhpOption\Option;
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.
*
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param string $content
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array<string,string|null>
*/
public function load(RepositoryInterface $repository, $content)
{
return $this->processEntries(
$repository,
Lines::process(Regex::split("/(\r\n|\n|\r)/", $content)->getSuccess())
);
}
/**
* Process the environment variable entries.
*
* We'll fill out any nested variables, and acually set the variable using
* the underlying environment variables instance.
*
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param string[] $entries
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array<string,string|null>
*/
private function processEntries(RepositoryInterface $repository, array $entries)
{
$vars = [];
foreach ($entries as $entry) {
list($name, $value) = Parser::parse($entry);
if ($this->whitelist === null || in_array($name, $this->whitelist, true)) {
$vars[$name] = self::resolveNestedVariables($repository, $value);
$repository->set($name, $vars[$name]);
}
}
return $vars;
}
/**
* Resolve the nested variables.
*
* Look for ${varname} patterns in the variable value and replace with an
* existing environment variable.
*
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param \Dotenv\Loader\Value|null $value
*
* @return string|null
*/
private static function resolveNestedVariables(RepositoryInterface $repository, Value $value = null)
{
/** @var Option<Value> */
$option = Option::fromValue($value);
return $option
->map(function (Value $v) use ($repository) {
/** @var string */
return array_reduce($v->getVars(), function ($s, $i) use ($repository) {
return substr($s, 0, $i).self::resolveNestedVariable($repository, substr($s, $i));
}, $v->getChars());
})
->getOrElse(null);
}
/**
* Resolve a single nested variable.
*
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param string $str
*
* @return string
*/
private static function resolveNestedVariable(RepositoryInterface $repository, $str)
{
return Regex::replaceCallback(
'/\A\${([a-zA-Z0-9_.]+)}/',
function (array $matches) use ($repository) {
return Option::fromValue($repository->get($matches[1]))
->getOrElse($matches[0]);
},
$str,
1
)->success()->getOrElse($str);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Dotenv\Loader;
use Dotenv\Repository\RepositoryInterface;
interface LoaderInterface
{
/**
* Load the given environment file content into the repository.
*
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param string $content
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array<string,string|null>
*/
public function load(RepositoryInterface $repository, $content);
}

View File

@@ -0,0 +1,249 @@
<?php
namespace Dotenv\Loader;
use Dotenv\Exception\InvalidFileException;
use Dotenv\Regex\Regex;
use Dotenv\Result\Error;
use Dotenv\Result\Success;
use RuntimeException;
class Parser
{
const INITIAL_STATE = 0;
const UNQUOTED_STATE = 1;
const SINGLE_QUOTED_STATE = 2;
const DOUBLE_QUOTED_STATE = 3;
const ESCAPE_SEQUENCE_STATE = 4;
const WHITESPACE_STATE = 5;
const COMMENT_STATE = 6;
/**
* Parse the given environment variable entry into a name and value.
*
* @param string $entry
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array{string,\Dotenv\Loader\Value|null}
*/
public static function parse($entry)
{
list($name, $value) = self::splitStringIntoParts($entry);
return [self::parseName($name), self::parseValue($value)];
}
/**
* Split the compound string into parts.
*
* @param string $line
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array{string,string|null}
*/
private static function splitStringIntoParts($line)
{
$name = $line;
$value = null;
if (strpos($line, '=') !== false) {
list($name, $value) = array_map('trim', explode('=', $line, 2));
}
if ($name === '') {
throw new InvalidFileException(
self::getErrorMessage('an unexpected equals', $line)
);
}
return [$name, $value];
}
/**
* Strips quotes and the optional leading "export " from the variable name.
*
* @param string $name
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return string
*/
private static function parseName($name)
{
$name = trim(str_replace(['export ', '\'', '"'], '', $name));
if (!self::isValidName($name)) {
throw new InvalidFileException(
self::getErrorMessage('an invalid name', $name)
);
}
return $name;
}
/**
* Is the given variable name valid?
*
* @param string $name
*
* @return bool
*/
private static function isValidName($name)
{
return Regex::match('~\A[a-zA-Z0-9_.]+\z~', $name)->success()->getOrElse(0) === 1;
}
/**
* Strips quotes and comments from the environment variable value.
*
* @param string|null $value
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return \Dotenv\Loader\Value|null
*/
private static function parseValue($value)
{
if ($value === null) {
return null;
}
if (trim($value) === '') {
return Value::blank();
}
$result = array_reduce(str_split($value), function ($data, $char) use ($value) {
return self::processChar($data[1], $char)->mapError(function ($err) use ($value) {
throw new InvalidFileException(
self::getErrorMessage($err, $value)
);
})->mapSuccess(function ($val) use ($data) {
return [$data[0]->append($val[0], $val[1]), $val[2]];
})->getSuccess();
}, [Value::blank(), self::INITIAL_STATE]);
if (in_array($result[1], [self::SINGLE_QUOTED_STATE, self::DOUBLE_QUOTED_STATE, self::ESCAPE_SEQUENCE_STATE], true)) {
throw new InvalidFileException(
self::getErrorMessage('a missing closing quote', $value)
);
}
return $result[0];
}
/**
* Process the given character.
*
* @param int $state
* @param string $char
*
* @return \Dotenv\Result\Result<array{string,bool,int},string>
*/
private static function processChar($state, $char)
{
switch ($state) {
case self::INITIAL_STATE:
if ($char === '\'') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::SINGLE_QUOTED_STATE]);
} elseif ($char === '"') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::DOUBLE_QUOTED_STATE]);
} elseif ($char === '#') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::COMMENT_STATE]);
} elseif ($char === '$') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create([$char, true, self::UNQUOTED_STATE]);
} else {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create([$char, false, self::UNQUOTED_STATE]);
}
case self::UNQUOTED_STATE:
if ($char === '#') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::COMMENT_STATE]);
} elseif (ctype_space($char)) {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::WHITESPACE_STATE]);
} elseif ($char === '$') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create([$char, true, self::UNQUOTED_STATE]);
} else {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create([$char, false, self::UNQUOTED_STATE]);
}
case self::SINGLE_QUOTED_STATE:
if ($char === '\'') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::WHITESPACE_STATE]);
} else {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create([$char, false, self::SINGLE_QUOTED_STATE]);
}
case self::DOUBLE_QUOTED_STATE:
if ($char === '"') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::WHITESPACE_STATE]);
} elseif ($char === '\\') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::ESCAPE_SEQUENCE_STATE]);
} elseif ($char === '$') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create([$char, true, self::DOUBLE_QUOTED_STATE]);
} else {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create([$char, false, self::DOUBLE_QUOTED_STATE]);
}
case self::ESCAPE_SEQUENCE_STATE:
if ($char === '"' || $char === '\\') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create([$char, false, self::DOUBLE_QUOTED_STATE]);
} elseif ($char === '$') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create([$char, false, self::DOUBLE_QUOTED_STATE]);
} elseif (in_array($char, ['f', 'n', 'r', 't', 'v'], true)) {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create([stripcslashes('\\'.$char), false, self::DOUBLE_QUOTED_STATE]);
} else {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Error::create('an unexpected escape sequence');
}
case self::WHITESPACE_STATE:
if ($char === '#') {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::COMMENT_STATE]);
} elseif (!ctype_space($char)) {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Error::create('unexpected whitespace');
} else {
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::WHITESPACE_STATE]);
}
case self::COMMENT_STATE:
/** @var \Dotenv\Result\Result<array{string,bool,int},string> */
return Success::create(['', false, self::COMMENT_STATE]);
default:
throw new RuntimeException('Parser entered invalid state.');
}
}
/**
* Generate a friendly error message.
*
* @param string $cause
* @param string $subject
*
* @return string
*/
private static function getErrorMessage($cause, $subject)
{
return sprintf(
'Failed to parse dotenv file due to %s. Failed at [%s].',
$cause,
strtok($subject, "\n")
);
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace Dotenv\Loader;
class Value
{
/**
* The string representation of the parsed value.
*
* @var string
*/
private $chars;
/**
* The locations of the variables in the value.
*
* @var int[]
*/
private $vars;
/**
* Internal constructor for a value.
*
* @param string $chars
* @param int[] $vars
*
* @return void
*/
private function __construct($chars, array $vars)
{
$this->chars = $chars;
$this->vars = $vars;
}
/**
* Create an empty value instance.
*
* @return \Dotenv\Loader\Value
*/
public static function blank()
{
return new self('', []);
}
/**
* Create a new value instance, appending the character.
*
* @param string $char
* @param bool $var
*
* @return \Dotenv\Loader\Value
*/
public function append($char, $var)
{
return new self(
$this->chars.$char,
$var ? array_merge($this->vars, [strlen($this->chars)]) : $this->vars
);
}
/**
* Get the string representation of the parsed value.
*
* @return string
*/
public function getChars()
{
return $this->chars;
}
/**
* Get the locations of the variables in the value.
*
* @return int[]
*/
public function getVars()
{
$vars = $this->vars;
rsort($vars);
return $vars;
}
}

View File

@@ -1,185 +0,0 @@
<?php
namespace Dotenv;
use Dotenv\Exception\InvalidFileException;
use Dotenv\Regex\Regex;
class Parser
{
const INITIAL_STATE = 0;
const UNQUOTED_STATE = 1;
const QUOTED_STATE = 2;
const ESCAPE_STATE = 3;
const WHITESPACE_STATE = 4;
const COMMENT_STATE = 5;
/**
* Parse the given environment variable entry into a name and value.
*
* @param string $entry
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array
*/
public static function parse($entry)
{
list($name, $value) = self::splitStringIntoParts($entry);
return [self::parseName($name), self::parseValue($value)];
}
/**
* Split the compound string into parts.
*
* @param string $line
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array
*/
private static function splitStringIntoParts($line)
{
$name = $line;
$value = null;
if (strpos($line, '=') !== false) {
list($name, $value) = array_map('trim', explode('=', $line, 2));
}
if ($name === '') {
throw new InvalidFileException(
self::getErrorMessage('an unexpected equals', $line)
);
}
return [$name, $value];
}
/**
* Strips quotes and the optional leading "export " from the variable name.
*
* @param string $name
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return string
*/
private static function parseName($name)
{
$name = trim(str_replace(['export ', '\'', '"'], '', $name));
if (!self::isValidName($name)) {
throw new InvalidFileException(
self::getErrorMessage('an invalid name', $name)
);
}
return $name;
}
/**
* Is the given variable name valid?
*
* @param string $name
*
* @return bool
*/
private static function isValidName($name)
{
return Regex::match('~\A[a-zA-Z0-9_.]+\z~', $name)->success()->getOrElse(0) === 1;
}
/**
* Strips quotes and comments from the environment variable value.
*
* @param string|null $value
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return string|null
*/
private static function parseValue($value)
{
if ($value === null || trim($value) === '') {
return $value;
}
$result = array_reduce(str_split($value), function ($data, $char) use ($value) {
switch ($data[1]) {
case self::INITIAL_STATE:
if ($char === '"' || $char === '\'') {
return [$data[0], self::QUOTED_STATE];
} elseif ($char === '#') {
return [$data[0], self::COMMENT_STATE];
} else {
return [$data[0].$char, self::UNQUOTED_STATE];
}
case self::UNQUOTED_STATE:
if ($char === '#') {
return [$data[0], self::COMMENT_STATE];
} elseif (ctype_space($char)) {
return [$data[0], self::WHITESPACE_STATE];
} else {
return [$data[0].$char, self::UNQUOTED_STATE];
}
case self::QUOTED_STATE:
if ($char === $value[0]) {
return [$data[0], self::WHITESPACE_STATE];
} elseif ($char === '\\') {
return [$data[0], self::ESCAPE_STATE];
} else {
return [$data[0].$char, self::QUOTED_STATE];
}
case self::ESCAPE_STATE:
if ($char === $value[0] || $char === '\\') {
return [$data[0].$char, self::QUOTED_STATE];
} elseif (in_array($char, ['f', 'n', 'r', 't', 'v'], true)) {
return [$data[0].stripcslashes('\\'.$char), self::QUOTED_STATE];
} else {
throw new InvalidFileException(
self::getErrorMessage('an unexpected escape sequence', $value)
);
}
case self::WHITESPACE_STATE:
if ($char === '#') {
return [$data[0], self::COMMENT_STATE];
} elseif (!ctype_space($char)) {
throw new InvalidFileException(
self::getErrorMessage('unexpected whitespace', $value)
);
} else {
return [$data[0], self::WHITESPACE_STATE];
}
case self::COMMENT_STATE:
return [$data[0], self::COMMENT_STATE];
}
}, ['', self::INITIAL_STATE]);
if ($result[1] === self::QUOTED_STATE || $result[1] === self::ESCAPE_STATE) {
throw new InvalidFileException(
self::getErrorMessage('a missing closing quote', $value)
);
}
return $result[0];
}
/**
* Generate a friendly error message.
*
* @param string $cause
* @param string $subject
*
* @return string
*/
private static function getErrorMessage($cause, $subject)
{
return sprintf(
'Failed to parse dotenv file due to %s. Failed at [%s].',
$cause,
strtok($subject, "\n")
);
}
}

View File

@@ -2,6 +2,10 @@
namespace Dotenv\Regex;
use Dotenv\Result\Error;
use Dotenv\Result\Result;
use Dotenv\Result\Success;
class Regex
{
/**
@@ -10,7 +14,7 @@ class Regex
* @param string $pattern
* @param string $subject
*
* @return \Dotenv\Regex\Result
* @return \Dotenv\Result\Result<int,string>
*/
public static function match($pattern, $subject)
{
@@ -22,16 +26,17 @@ class Regex
/**
* Perform a preg replace, wrapping up the result.
*
* @param string $pattern
* @param string $replacement
* @param string $subject
* @param string $pattern
* @param string $replacement
* @param string $subject
* @param int|null $limit
*
* @return \Dotenv\Regex\Result
* @return \Dotenv\Result\Result<string,string>
*/
public static function replace($pattern, $replacement, $subject)
public static function replace($pattern, $replacement, $subject, $limit = null)
{
return self::pregAndWrap(function ($subject) use ($pattern, $replacement) {
return (string) @preg_replace($pattern, $replacement, $subject);
return self::pregAndWrap(function ($subject) use ($pattern, $replacement, $limit) {
return (string) @preg_replace($pattern, $replacement, $subject, $limit === null ? -1 : $limit);
}, $subject);
}
@@ -41,32 +46,53 @@ class Regex
* @param string $pattern
* @param callable $callback
* @param string $subject
* @param int|null $limit
*
* @return \Dotenv\Regex\Result
* @return \Dotenv\Result\Result<string,string>
*/
public static function replaceCallback($pattern, callable $callback, $subject)
public static function replaceCallback($pattern, callable $callback, $subject, $limit = null)
{
return self::pregAndWrap(function ($subject) use ($pattern, $callback) {
return (string) @preg_replace_callback($pattern, $callback, $subject);
return self::pregAndWrap(function ($subject) use ($pattern, $callback, $limit) {
return (string) @preg_replace_callback($pattern, $callback, $subject, $limit === null ? -1 : $limit);
}, $subject);
}
/**
* Perform a preg split, wrapping up the result.
*
* @param string $pattern
* @param string $subject
*
* @return \Dotenv\Result\Result<string[],string>
*/
public static function split($pattern, $subject)
{
return self::pregAndWrap(function ($subject) use ($pattern) {
/** @var string[] */
return (array) @preg_split($pattern, $subject);
}, $subject);
}
/**
* Perform a preg operation, wrapping up the result.
*
* @param callable $operation
* @param string $subject
* @template V
*
* @return \Dotenv\Regex\Result
* @param callable(string):V $operation
* @param string $subject
*
* @return \Dotenv\Result\Result<V,string>
*/
private static function pregAndWrap(callable $operation, $subject)
{
$result = $operation($subject);
if (($e = preg_last_error()) !== PREG_NO_ERROR) {
/** @var Result<V,string> */
return Error::create(self::lookupError($e));
}
/** @var Result<V,string> */
return Success::create($result);
}

View File

@@ -1,17 +1,12 @@
<?php
namespace Dotenv\Environment;
namespace Dotenv\Repository;
use Dotenv\Environment\Adapter\ArrayAdapter;
use Dotenv\Repository\Adapter\ArrayAdapter;
use InvalidArgumentException;
use ReturnTypeWillChange;
/**
* This is the abstract variables implementation.
*
* Extend this as required, implementing "get", "set", and "clear".
*/
abstract class AbstractVariables implements VariablesInterface
abstract class AbstractRepository implements RepositoryInterface
{
/**
* Are we immutable?
@@ -23,12 +18,12 @@ abstract class AbstractVariables implements VariablesInterface
/**
* The record of loaded variables.
*
* @var \Dotenv\Environment\Adapter\ArrayAdapter
* @var \Dotenv\Repository\Adapter\ArrayAdapter
*/
private $loaded;
/**
* Create a new environment variables instance.
* Create a new repository instance.
*
* @param bool $immutable
*
@@ -51,8 +46,8 @@ abstract class AbstractVariables implements VariablesInterface
*/
public function get($name)
{
if (!is_string($name)) {
throw new InvalidArgumentException('Expected name to be a string.');
if (!is_string($name) || '' === $name) {
throw new InvalidArgumentException('Expected name to be a non-empty string.');
}
return $this->getInternal($name);
@@ -61,7 +56,7 @@ abstract class AbstractVariables implements VariablesInterface
/**
* Get an environment variable.
*
* @param string $name
* @param non-empty-string $name
*
* @return string|null
*/
@@ -79,13 +74,13 @@ abstract class AbstractVariables implements VariablesInterface
*/
public function set($name, $value = null)
{
if (!is_string($name)) {
throw new InvalidArgumentException('Expected name to be a string.');
if (!is_string($name) || '' === $name) {
throw new InvalidArgumentException('Expected name to be a non-empty string.');
}
// Don't overwrite existing environment variables if we're immutable
// Ruby's dotenv does this with `ENV[key] ||= value`.
if ($this->isImmutable() && $this->get($name) !== null && $this->loaded->get($name)->isEmpty()) {
if ($this->immutable && $this->get($name) !== null && $this->loaded->get($name)->isEmpty()) {
return;
}
@@ -96,8 +91,8 @@ abstract class AbstractVariables implements VariablesInterface
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
* @param non-empty-string $name
* @param string|null $value
*
* @return void
*/
@@ -114,12 +109,12 @@ abstract class AbstractVariables implements VariablesInterface
*/
public function clear($name)
{
if (!is_string($name)) {
throw new InvalidArgumentException('Expected name to be a string.');
if (!is_string($name) || '' === $name) {
throw new InvalidArgumentException('Expected name to be a non-empty string.');
}
// Don't clear anything if we're immutable.
if ($this->isImmutable()) {
if ($this->immutable) {
return;
}
@@ -129,22 +124,12 @@ abstract class AbstractVariables implements VariablesInterface
/**
* Clear an environment variable.
*
* @param string $name
* @param non-empty-string $name
*
* @return void
*/
abstract protected function clearInternal($name);
/**
* Determine if the environment is immutable.
*
* @return bool
*/
public function isImmutable()
{
return $this->immutable;
}
/**
* Tells whether environment variable has been defined.
*
@@ -154,7 +139,7 @@ abstract class AbstractVariables implements VariablesInterface
*/
public function has($name)
{
return is_string($name) && $this->get($name) !== null;
return is_string($name) && $name !== '' && $this->get($name) !== null;
}
/**

View File

@@ -1,10 +1,10 @@
<?php
namespace Dotenv\Environment\Adapter;
namespace Dotenv\Repository\Adapter;
use PhpOption\None;
class ApacheAdapter implements AdapterInterface
class ApacheAdapter implements AvailabilityInterface, ReaderInterface, WriterInterface
{
/**
* Determines if the adapter is supported.
@@ -24,9 +24,9 @@ class ApacheAdapter implements AdapterInterface
* This is intentionally not implemented, since this adapter exists only as
* a means to overwrite existing apache environment variables.
*
* @param string $name
* @param non-empty-string $name
*
* @return \PhpOption\Option
* @return \PhpOption\Option<string|null>
*/
public function get($name)
{
@@ -38,22 +38,24 @@ class ApacheAdapter implements AdapterInterface
*
* Only if an existing apache variable exists do we overwrite it.
*
* @param string $name
* @param string|null $value
* @param non-empty-string $name
* @param string|null $value
*
* @return void
*/
public function set($name, $value = null)
{
if (apache_getenv($name) !== false) {
apache_setenv($name, (string) $value);
if (apache_getenv($name) === false) {
return;
}
apache_setenv($name, (string) $value);
}
/**
* Clear an environment variable.
*
* @param string $name
* @param non-empty-string $name
*
* @return void
*/

View File

@@ -1,16 +1,16 @@
<?php
namespace Dotenv\Environment\Adapter;
namespace Dotenv\Repository\Adapter;
use PhpOption\None;
use PhpOption\Some;
class ArrayAdapter implements AdapterInterface
class ArrayAdapter implements AvailabilityInterface, ReaderInterface, WriterInterface
{
/**
* The variables and their values.
*
* @return array<string|null>
* @var array<non-empty-string,string|null>
*/
private $variables = [];
@@ -27,24 +27,24 @@ class ArrayAdapter implements AdapterInterface
/**
* Get an environment variable, if it exists.
*
* @param string $name
* @param non-empty-string $name
*
* @return \PhpOption\Option
* @return \PhpOption\Option<string|null>
*/
public function get($name)
{
if (array_key_exists($name, $this->variables)) {
return Some::create($this->variables[$name]);
if (!array_key_exists($name, $this->variables)) {
return None::create();
}
return None::create();
return Some::create($this->variables[$name]);
}
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
* @param non-empty-string $name
* @param string|null $value
*
* @return void
*/
@@ -56,7 +56,7 @@ class ArrayAdapter implements AdapterInterface
/**
* Clear an environment variable.
*
* @param string $name
* @param non-empty-string $name
*
* @return void
*/

View File

@@ -0,0 +1,13 @@
<?php
namespace Dotenv\Repository\Adapter;
interface AvailabilityInterface
{
/**
* Determines if the adapter is supported.
*
* @return bool
*/
public function isSupported();
}

View File

@@ -0,0 +1,72 @@
<?php
namespace Dotenv\Repository\Adapter;
use PhpOption\None;
use PhpOption\Some;
class EnvConstAdapter implements AvailabilityInterface, ReaderInterface, WriterInterface
{
/**
* Determines if the adapter is supported.
*
* @return bool
*/
public function isSupported()
{
return true;
}
/**
* Get an environment variable, if it exists.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string|null>
*/
public function get($name)
{
if (!array_key_exists($name, $_ENV)) {
return None::create();
}
$value = $_ENV[$name];
if (is_scalar($value)) {
/** @var \PhpOption\Option<string|null> */
return Some::create((string) $value);
}
if (null === $value) {
/** @var \PhpOption\Option<string|null> */
return Some::create(null);
}
return None::create();
}
/**
* Set an environment variable.
*
* @param non-empty-string $name
* @param string|null $value
*
* @return void
*/
public function set($name, $value = null)
{
$_ENV[$name] = $value;
}
/**
* Clear an environment variable.
*
* @param non-empty-string $name
*
* @return void
*/
public function clear($name)
{
unset($_ENV[$name]);
}
}

View File

@@ -1,10 +1,10 @@
<?php
namespace Dotenv\Environment\Adapter;
namespace Dotenv\Repository\Adapter;
use PhpOption\Option;
class PutenvAdapter implements AdapterInterface
class PutenvAdapter implements AvailabilityInterface, ReaderInterface, WriterInterface
{
/**
* Determines if the adapter is supported.
@@ -13,26 +13,27 @@ class PutenvAdapter implements AdapterInterface
*/
public function isSupported()
{
return function_exists('putenv');
return function_exists('getenv') && function_exists('putenv');
}
/**
* Get an environment variable, if it exists.
*
* @param string $name
* @param non-empty-string $name
*
* @return \PhpOption\Option
* @return \PhpOption\Option<string|null>
*/
public function get($name)
{
/** @var \PhpOption\Option<string|null> */
return Option::fromValue(getenv($name), false);
}
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
* @param non-empty-string $name
* @param string|null $value
*
* @return void
*/
@@ -44,7 +45,7 @@ class PutenvAdapter implements AdapterInterface
/**
* Clear an environment variable.
*
* @param string $name
* @param non-empty-string $name
*
* @return void
*/

View File

@@ -0,0 +1,15 @@
<?php
namespace Dotenv\Repository\Adapter;
interface ReaderInterface extends AvailabilityInterface
{
/**
* Get an environment variable, if it exists.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string|null>
*/
public function get($name);
}

View File

@@ -0,0 +1,72 @@
<?php
namespace Dotenv\Repository\Adapter;
use PhpOption\None;
use PhpOption\Some;
class ServerConstAdapter implements AvailabilityInterface, ReaderInterface, WriterInterface
{
/**
* Determines if the adapter is supported.
*
* @return bool
*/
public function isSupported()
{
return true;
}
/**
* Get an environment variable, if it exists.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string|null>
*/
public function get($name)
{
if (!array_key_exists($name, $_SERVER)) {
return None::create();
}
$value = $_SERVER[$name];
if (is_scalar($value)) {
/** @var \PhpOption\Option<string|null> */
return Some::create((string) $value);
}
if (null === $value) {
/** @var \PhpOption\Option<string|null> */
return Some::create(null);
}
return None::create();
}
/**
* Set an environment variable.
*
* @param non-empty-string $name
* @param string|null $value
*
* @return void
*/
public function set($name, $value = null)
{
$_SERVER[$name] = $value;
}
/**
* Clear an environment variable.
*
* @param non-empty-string $name
*
* @return void
*/
public function clear($name)
{
unset($_SERVER[$name]);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace Dotenv\Repository\Adapter;
interface WriterInterface extends AvailabilityInterface
{
/**
* Set an environment variable.
*
* @param non-empty-string $name
* @param string|null $value
*
* @return void
*/
public function set($name, $value = null);
/**
* Clear an environment variable.
*
* @param non-empty-string $name
*
* @return void
*/
public function clear($name);
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Dotenv\Repository;
class AdapterRepository extends AbstractRepository
{
/**
* The set of readers to use.
*
* @var \Dotenv\Repository\Adapter\ReaderInterface[]
*/
protected $readers;
/**
* The set of writers to use.
*
* @var \Dotenv\Repository\Adapter\WriterInterface[]
*/
protected $writers;
/**
* Create a new adapter repository instance.
*
* @param \Dotenv\Repository\Adapter\ReaderInterface[] $readers
* @param \Dotenv\Repository\Adapter\WriterInterface[] $writers
* @param bool $immutable
*
* @return void
*/
public function __construct(array $readers, array $writers, $immutable)
{
$this->readers = $readers;
$this->writers = $writers;
parent::__construct($immutable);
}
/**
* Get an environment variable.
*
* We do this by querying our readers sequentially.
*
* @param non-empty-string $name
*
* @return string|null
*/
protected function getInternal($name)
{
foreach ($this->readers as $reader) {
$result = $reader->get($name);
if ($result->isDefined()) {
return $result->get();
}
}
return null;
}
/**
* Set an environment variable.
*
* @param non-empty-string $name
* @param string|null $value
*
* @return void
*/
protected function setInternal($name, $value = null)
{
foreach ($this->writers as $writers) {
$writers->set($name, $value);
}
}
/**
* Clear an environment variable.
*
* @param non-empty-string $name
*
* @return void
*/
protected function clearInternal($name)
{
foreach ($this->writers as $writers) {
$writers->clear($name);
}
}
}

View File

@@ -0,0 +1,144 @@
<?php
namespace Dotenv\Repository;
use Dotenv\Repository\Adapter\ApacheAdapter;
use Dotenv\Repository\Adapter\AvailabilityInterface;
use Dotenv\Repository\Adapter\EnvConstAdapter;
use Dotenv\Repository\Adapter\PutenvAdapter;
use Dotenv\Repository\Adapter\ServerConstAdapter;
class RepositoryBuilder
{
/**
* The set of readers to use.
*
* @var \Dotenv\Repository\Adapter\ReaderInterface[]|null
*/
private $readers;
/**
* The set of writers to use.
*
* @var \Dotenv\Repository\Adapter\WriterInterface[]|null
*/
private $writers;
/**
* Are we immutable?
*
* @var bool
*/
private $immutable;
/**
* Create a new repository builder instance.
*
* @param \Dotenv\Repository\Adapter\ReaderInterface[]|null $readers
* @param \Dotenv\Repository\Adapter\WriterInterface[]|null $writers
* @param bool $immutable
*
* @return void
*/
private function __construct(array $readers = null, array $writers = null, $immutable = false)
{
$this->readers = $readers;
$this->writers = $writers;
$this->immutable = $immutable;
}
/**
* Create a new repository builder instance.
*
* @return \Dotenv\Repository\RepositoryBuilder
*/
public static function create()
{
return new self();
}
/**
* Creates a repository builder with the given readers.
*
* @param \Dotenv\Repository\Adapter\ReaderInterface[]|null $readers
*
* @return \Dotenv\Repository\RepositoryBuilder
*/
public function withReaders(array $readers = null)
{
$readers = $readers === null ? null : self::filterByAvailability($readers);
return new self($readers, $this->writers, $this->immutable);
}
/**
* Creates a repository builder with the given writers.
*
* @param \Dotenv\Repository\Adapter\WriterInterface[]|null $writers
*
* @return \Dotenv\Repository\RepositoryBuilder
*/
public function withWriters(array $writers = null)
{
$writers = $writers === null ? null : self::filterByAvailability($writers);
return new self($this->readers, $writers, $this->immutable);
}
/**
* Creates a repository builder with mutability enabled.
*
* @return \Dotenv\Repository\RepositoryBuilder
*/
public function immutable()
{
return new self($this->readers, $this->writers, true);
}
/**
* Creates a new repository instance.
*
* @return \Dotenv\Repository\RepositoryInterface
*/
public function make()
{
if ($this->readers === null || $this->writers === null) {
$defaults = self::defaultAdapters();
}
return new AdapterRepository(
$this->readers === null ? $defaults : $this->readers,
$this->writers === null ? $defaults : $this->writers,
$this->immutable
);
}
/**
* Return the array of default adapters.
*
* @return \Dotenv\Repository\Adapter\AvailabilityInterface[]
*/
private static function defaultAdapters()
{
return self::filterByAvailability([
new ApacheAdapter(),
new EnvConstAdapter(),
new ServerConstAdapter(),
new PutenvAdapter(),
]);
}
/**
* Filter an array of adapters to only those that are supported.
*
* @param \Dotenv\Repository\Adapter\AvailabilityInterface[] $adapters
*
* @return \Dotenv\Repository\Adapter\AvailabilityInterface[]
*/
private static function filterByAvailability(array $adapters)
{
return array_filter($adapters, function (AvailabilityInterface $adapter) {
return $adapter->isSupported();
});
}
}

View File

@@ -1,21 +1,14 @@
<?php
namespace Dotenv\Environment;
namespace Dotenv\Repository;
use ArrayAccess;
/**
* This environment variables interface.
* @extends \ArrayAccess<string,string|null>
*/
interface VariablesInterface extends ArrayAccess
interface RepositoryInterface extends ArrayAccess
{
/**
* Determine if the environment is immutable.
*
* @return bool
*/
public function isImmutable();
/**
* Tells whether environment variable has been defined.
*

View File

@@ -1,21 +1,26 @@
<?php
namespace Dotenv\Regex;
namespace Dotenv\Result;
use PhpOption\None;
use PhpOption\Some;
/**
* @template T
* @template E
* @extends \Dotenv\Result\Result<T,E>
*/
class Error extends Result
{
/**
* @var string
* @var E
*/
private $value;
/**
* Internal constructor for an error value.
*
* @param string $value
* @param E $value
*
* @return void
*/
@@ -27,9 +32,11 @@ class Error extends Result
/**
* Create a new error value.
*
* @param string $value
* @template F
*
* @return \Dotenv\Regex\Result
* @param F $value
*
* @return \Dotenv\Result\Result<T,F>
*/
public static function create($value)
{
@@ -39,7 +46,7 @@ class Error extends Result
/**
* Get the success option value.
*
* @return \PhpOption\Option
* @return \PhpOption\Option<T>
*/
public function success()
{
@@ -49,19 +56,22 @@ class Error extends Result
/**
* Map over the success value.
*
* @param callable $f
* @template S
*
* @return \Dotenv\Regex\Result
* @param callable(T):S $f
*
* @return \Dotenv\Result\Result<S,E>
*/
public function mapSuccess(callable $f)
{
/** @var \Dotenv\Result\Result<S,E> */
return self::create($this->value);
}
/**
* Get the error option value.
*
* @return \PhpOption\Option
* @return \PhpOption\Option<E>
*/
public function error()
{
@@ -71,9 +81,11 @@ class Error extends Result
/**
* Map over the error value.
*
* @param callable $f
* @template F
*
* @return \Dotenv\Regex\Result
* @param callable(E):F $f
*
* @return \Dotenv\Result\Result<T,F>
*/
public function mapError(callable $f)
{

View File

@@ -1,20 +1,26 @@
<?php
namespace Dotenv\Regex;
namespace Dotenv\Result;
/**
* @template T
* @template E
*/
abstract class Result
{
/**
* Get the success option value.
*
* @return \PhpOption\Option
* @return \PhpOption\Option<T>
*/
abstract public function success();
/**
* Get the error value, if possible.
* Get the success value, if possible.
*
* @return string|int
* @throws \RuntimeException
*
* @return T
*/
public function getSuccess()
{
@@ -24,23 +30,27 @@ abstract class Result
/**
* Map over the success value.
*
* @param callable $f
* @template S
*
* @return \Dotenv\Regex\Result
* @param callable(T):S $f
*
* @return \Dotenv\Result\Result<S,E>
*/
abstract public function mapSuccess(callable $f);
/**
* Get the error option value.
*
* @return \PhpOption\Option
* @return \PhpOption\Option<E>
*/
abstract public function error();
/**
* Get the error value, if possible.
*
* @return string
* @throws \RuntimeException
*
* @return E
*/
public function getError()
{
@@ -50,9 +60,11 @@ abstract class Result
/**
* Map over the error value.
*
* @param callable $f
* @template F
*
* @return \Dotenv\Regex\Result
* @param callable(E):F $f
*
* @return \Dotenv\Result\Result<T,F>
*/
abstract public function mapError(callable $f);
}

View File

@@ -1,21 +1,26 @@
<?php
namespace Dotenv\Regex;
namespace Dotenv\Result;
use PhpOption\None;
use PhpOption\Some;
/**
* @template T
* @template E
* @extends \Dotenv\Result\Result<T,E>
*/
class Success extends Result
{
/**
* @var string|int
* @var T
*/
private $value;
/**
* Internal constructor for a success value.
*
* @param string|int $value
* @param T $value
*
* @return void
*/
@@ -25,11 +30,13 @@ class Success extends Result
}
/**
* Create a new success value.
* Create a new error value.
*
* @param string|int $value
* @template S
*
* @return \Dotenv\Regex\Result
* @param S $value
*
* @return \Dotenv\Result\Result<S,E>
*/
public static function create($value)
{
@@ -39,7 +46,7 @@ class Success extends Result
/**
* Get the success option value.
*
* @return \PhpOption\Option
* @return \PhpOption\Option<T>
*/
public function success()
{
@@ -49,9 +56,11 @@ class Success extends Result
/**
* Map over the success value.
*
* @param callable $f
* @template S
*
* @return \Dotenv\Regex\Result
* @param callable(T):S $f
*
* @return \Dotenv\Result\Result<S,E>
*/
public function mapSuccess(callable $f)
{
@@ -61,7 +70,7 @@ class Success extends Result
/**
* Get the error option value.
*
* @return \PhpOption\Option
* @return \PhpOption\Option<E>
*/
public function error()
{
@@ -71,12 +80,15 @@ class Success extends Result
/**
* Map over the error value.
*
* @param callable $f
* @template F
*
* @return \Dotenv\Regex\Result
* @param callable(E):F $f
*
* @return \Dotenv\Result\Result<T,F>
*/
public function mapError(callable $f)
{
/** @var \Dotenv\Result\Result<T,F> */
return self::create($this->value);
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Dotenv\Store\File;
class Paths
{
/**
* Returns the full paths to the files.
*
* @param string[] $paths
* @param string[] $names
*
* @return string[]
*/
public static function filePaths(array $paths, array $names)
{
$files = [];
foreach ($paths as $path) {
foreach ($names as $name) {
$files[] = rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$name;
}
}
return $files;
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Dotenv\Store\File;
use PhpOption\Option;
class Reader
{
/**
* Read the file(s), and return their raw content.
*
* We provide the file path as the key, and its content as the value. If
* short circuit mode is enabled, then the returned array with have length
* at most one. File paths that couldn't be read are omitted entirely.
*
* @param string[] $filePaths
* @param bool $shortCircuit
*
* @return array<string,string>
*/
public static function read(array $filePaths, $shortCircuit = true)
{
$output = [];
foreach ($filePaths as $filePath) {
$content = self::readFromFile($filePath);
if ($content->isDefined()) {
$output[$filePath] = $content->get();
if ($shortCircuit) {
break;
}
}
}
return $output;
}
/**
* Read the given file.
*
* @param string $filePath
*
* @return \PhpOption\Option<string>
*/
private static function readFromFile($filePath)
{
$content = @file_get_contents($filePath);
/** @var \PhpOption\Option<string> */
return Option::fromValue($content, false);
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace Dotenv\Store;
use Dotenv\Exception\InvalidPathException;
use Dotenv\Store\File\Reader;
class FileStore implements StoreInterface
{
/**
* The file paths.
*
* @var string[]
*/
protected $filePaths;
/**
* Should file loading short circuit?
*
* @var bool
*/
protected $shortCircuit;
/**
* Create a new file store instance.
*
* @param string[] $filePaths
* @param bool $shortCircuit
*
* @return void
*/
public function __construct(array $filePaths, $shortCircuit)
{
$this->filePaths = $filePaths;
$this->shortCircuit = $shortCircuit;
}
/**
* Read the content of the environment file(s).
*
* @throws \Dotenv\Exception\InvalidPathException
*
* @return string
*/
public function read()
{
if ($this->filePaths === []) {
throw new InvalidPathException('At least one environment file path must be provided.');
}
$contents = Reader::read($this->filePaths, $this->shortCircuit);
if (count($contents) > 0) {
return implode("\n", $contents);
}
throw new InvalidPathException(
sprintf('Unable to read any of the environment file(s) at [%s].', implode(', ', $this->filePaths))
);
}
}

View File

@@ -0,0 +1,102 @@
<?php
namespace Dotenv\Store;
use Dotenv\Store\File\Paths;
class StoreBuilder
{
/**
* The paths to search within.
*
* @var string[]
*/
private $paths;
/**
* The file names to search for.
*
* @var string[]|null
*/
private $names;
/**
* Should file loading short circuit?
*
* @var bool
*/
protected $shortCircuit;
/**
* Create a new store builder instance.
*
* @param string[] $paths
* @param string[]|null $names
* @param bool $shortCircuit
*
* @return void
*/
private function __construct(array $paths = [], array $names = null, $shortCircuit = false)
{
$this->paths = $paths;
$this->names = $names;
$this->shortCircuit = $shortCircuit;
}
/**
* Create a new store builder instance.
*
* @return \Dotenv\Store\StoreBuilder
*/
public static function create()
{
return new self();
}
/**
* Creates a store builder with the given paths.
*
* @param string|string[] $paths
*
* @return \Dotenv\Store\StoreBuilder
*/
public function withPaths($paths)
{
return new self((array) $paths, $this->names, $this->shortCircuit);
}
/**
* Creates a store builder with the given names.
*
* @param string|string[]|null $names
*
* @return \Dotenv\Store\StoreBuilder
*/
public function withNames($names = null)
{
return new self($this->paths, $names === null ? null : (array) $names, $this->shortCircuit);
}
/**
* Creates a store builder with short circuit mode enabled.
*
* @return \Dotenv\Store\StoreBuilder
*/
public function shortCircuit()
{
return new self($this->paths, $this->names, true);
}
/**
* Creates a new store instance.
*
* @return \Dotenv\Store\StoreInterface
*/
public function make()
{
return new FileStore(
Paths::filePaths($this->paths, $this->names === null ? ['.env'] : $this->names),
$this->shortCircuit
);
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace Dotenv\Store;
interface StoreInterface
{
/**
* Read the content of the environment file(s).
*
* @throws \Dotenv\Exception\InvalidPathException
*
* @return string
*/
public function read();
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Dotenv\Store;
final class StringStore implements StoreInterface
{
/**
* The file content.
*
* @var string
*/
private $content;
/**
* Create a new string store instance.
*
* @param string $content
*
* @return void
*/
public function __construct($content)
{
$this->content = $content;
}
/**
* Read the content of the environment file(s).
*
* @return string
*/
public function read()
{
return $this->content;
}
}

View File

@@ -4,14 +4,17 @@ namespace Dotenv;
use Dotenv\Exception\ValidationException;
use Dotenv\Regex\Regex;
use Dotenv\Repository\RepositoryInterface;
/**
* This is the validator class.
*
* It's responsible for applying validations against a number of variables.
*/
class Validator
{
/**
* The environment repository instance.
*
* @var \Dotenv\Repository\RepositoryInterface
*/
protected $repository;
/**
* The variables to validate.
*
@@ -19,28 +22,21 @@ class Validator
*/
protected $variables;
/**
* The loader instance.
*
* @var \Dotenv\Loader
*/
protected $loader;
/**
* Create a new validator instance.
*
* @param string[] $variables
* @param \Dotenv\Loader $loader
* @param bool $required
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param string[] $variables
* @param bool $required
*
* @throws \Dotenv\Exception\ValidationException
*
* @return void
*/
public function __construct(array $variables, Loader $loader, $required = true)
public function __construct(RepositoryInterface $repository, array $variables, $required = true)
{
$this->repository = $repository;
$this->variables = $variables;
$this->loader = $loader;
if ($required) {
$this->assertCallback(
@@ -180,7 +176,7 @@ class Validator
$failing = [];
foreach ($this->variables as $variable) {
if ($callback($this->loader->getEnvironmentVariable($variable)) === false) {
if ($callback($this->repository->get($variable)) === false) {
$failing[] = sprintf('%s %s', $variable, $message);
}
}