dependencies-upgrade

This commit is contained in:
RafficMohammed
2023-01-08 02:20:59 +05:30
parent 7870479b18
commit 49021a4497
1711 changed files with 74994 additions and 70803 deletions

View File

@@ -16,15 +16,18 @@
}
],
"require": {
"php": "^5.5.9 || ^7.0 || ^8.0",
"phpoption/phpoption": "^1.7.3",
"symfony/polyfill-ctype": "^1.17"
"php": "^7.1.3 || ^8.0",
"ext-pcre": "*",
"graham-campbell/result-type": "^1.0.2",
"phpoption/phpoption": "^1.8",
"symfony/polyfill-ctype": "^1.23",
"symfony/polyfill-mbstring": "^1.23.1",
"symfony/polyfill-php80": "^1.23.1"
},
"require-dev": {
"ext-filter": "*",
"ext-pcre": "*",
"bamarni/composer-bin-plugin": "^1.4.1",
"phpunit/phpunit": "^4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.30"
"phpunit/phpunit": "^7.5.20 || ^8.5.30 || ^9.5.25"
},
"autoload": {
"psr-4": {
@@ -37,8 +40,7 @@
}
},
"suggest": {
"ext-filter": "Required to use the boolean validator.",
"ext-pcre": "Required to use most of the library."
"ext-filter": "Required to use the boolean validator."
},
"config": {
"allow-plugins": {
@@ -52,7 +54,7 @@
"forward-command": true
},
"branch-alias": {
"dev-master": "4.3-dev"
"dev-master": "5.5-dev"
}
}
}

View File

@@ -1,54 +1,72 @@
<?php
declare(strict_types=1);
namespace Dotenv;
use Dotenv\Exception\InvalidPathException;
use Dotenv\Loader\Loader;
use Dotenv\Loader\LoaderInterface;
use Dotenv\Parser\Parser;
use Dotenv\Parser\ParserInterface;
use Dotenv\Repository\Adapter\ArrayAdapter;
use Dotenv\Repository\Adapter\PutenvAdapter;
use Dotenv\Repository\RepositoryBuilder;
use Dotenv\Repository\RepositoryInterface;
use Dotenv\Store\FileStore;
use Dotenv\Store\StoreBuilder;
use Dotenv\Store\StoreInterface;
use Dotenv\Store\StringStore;
class Dotenv
{
/**
* The store instance.
*
* @var \Dotenv\Store\StoreInterface
*/
private $store;
/**
* The parser instance.
*
* @var \Dotenv\Parser\ParserInterface
*/
private $parser;
/**
* The loader instance.
*
* @var \Dotenv\Loader\LoaderInterface
*/
protected $loader;
private $loader;
/**
* The repository instance.
*
* @var \Dotenv\Repository\RepositoryInterface
*/
protected $repository;
/**
* The store instance.
*
* @var \Dotenv\Store\StoreInterface
*/
protected $store;
private $repository;
/**
* Create a new dotenv instance.
*
* @param \Dotenv\Store\StoreInterface $store
* @param \Dotenv\Parser\ParserInterface $parser
* @param \Dotenv\Loader\LoaderInterface $loader
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param \Dotenv\Store\StoreInterface|string[] $store
*
* @return void
*/
public function __construct(LoaderInterface $loader, RepositoryInterface $repository, $store)
{
public function __construct(
StoreInterface $store,
ParserInterface $parser,
LoaderInterface $loader,
RepositoryInterface $repository
) {
$this->store = $store;
$this->parser = $parser;
$this->loader = $loader;
$this->repository = $repository;
$this->store = is_array($store) ? new FileStore($store, true) : $store;
}
/**
@@ -58,18 +76,27 @@ class Dotenv
* @param string|string[] $paths
* @param string|string[]|null $names
* @param bool $shortCircuit
* @param string|null $fileEncoding
*
* @return \Dotenv\Dotenv
*/
public static function create(RepositoryInterface $repository, $paths, $names = null, $shortCircuit = true)
public static function create(RepositoryInterface $repository, $paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null)
{
$builder = StoreBuilder::create()->withPaths($paths)->withNames($names);
$builder = $names === null ? StoreBuilder::createWithDefaultName() : StoreBuilder::createWithNoNames();
foreach ((array) $paths as $path) {
$builder = $builder->addPath($path);
}
foreach ((array) $names as $name) {
$builder = $builder->addName($name);
}
if ($shortCircuit) {
$builder = $builder->shortCircuit();
}
return new self(new Loader(), $repository, $builder->make());
return new self($builder->fileEncoding($fileEncoding)->make(), new Parser(), new Loader(), $repository);
}
/**
@@ -78,14 +105,34 @@ class Dotenv
* @param string|string[] $paths
* @param string|string[]|null $names
* @param bool $shortCircuit
* @param string|null $fileEncoding
*
* @return \Dotenv\Dotenv
*/
public static function createMutable($paths, $names = null, $shortCircuit = true)
public static function createMutable($paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null)
{
$repository = RepositoryBuilder::create()->make();
$repository = RepositoryBuilder::createWithDefaultAdapters()->make();
return self::create($repository, $paths, $names, $shortCircuit);
return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding);
}
/**
* Create a new mutable dotenv instance with default repository with the putenv adapter.
*
* @param string|string[] $paths
* @param string|string[]|null $names
* @param bool $shortCircuit
* @param string|null $fileEncoding
*
* @return \Dotenv\Dotenv
*/
public static function createUnsafeMutable($paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null)
{
$repository = RepositoryBuilder::createWithDefaultAdapters()
->addAdapter(PutenvAdapter::class)
->make();
return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding);
}
/**
@@ -94,14 +141,35 @@ class Dotenv
* @param string|string[] $paths
* @param string|string[]|null $names
* @param bool $shortCircuit
* @param string|null $fileEncoding
*
* @return \Dotenv\Dotenv
*/
public static function createImmutable($paths, $names = null, $shortCircuit = true)
public static function createImmutable($paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null)
{
$repository = RepositoryBuilder::create()->immutable()->make();
$repository = RepositoryBuilder::createWithDefaultAdapters()->immutable()->make();
return self::create($repository, $paths, $names, $shortCircuit);
return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding);
}
/**
* Create a new immutable dotenv instance with default repository with the putenv adapter.
*
* @param string|string[] $paths
* @param string|string[]|null $names
* @param bool $shortCircuit
* @param string|null $fileEncoding
*
* @return \Dotenv\Dotenv
*/
public static function createUnsafeImmutable($paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null)
{
$repository = RepositoryBuilder::createWithDefaultAdapters()
->addAdapter(PutenvAdapter::class)
->immutable()
->make();
return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding);
}
/**
@@ -110,16 +178,15 @@ class Dotenv
* @param string|string[] $paths
* @param string|string[]|null $names
* @param bool $shortCircuit
* @param string|null $fileEncoding
*
* @return \Dotenv\Dotenv
*/
public static function createArrayBacked($paths, $names = null, $shortCircuit = true)
public static function createArrayBacked($paths, $names = null, bool $shortCircuit = true, string $fileEncoding = null)
{
$adapter = new ArrayAdapter();
$repository = RepositoryBuilder::createWithNoAdapters()->addAdapter(ArrayAdapter::class)->make();
$repository = RepositoryBuilder::create()->withReaders([$adapter])->withWriters([$adapter])->make();
return self::create($repository, $paths, $names, $shortCircuit);
return self::create($repository, $paths, $names, $shortCircuit, $fileEncoding);
}
/**
@@ -134,13 +201,11 @@ class Dotenv
*
* @return array<string,string|null>
*/
public static function parse($content)
public static function parse(string $content)
{
$adapter = new ArrayAdapter();
$repository = RepositoryBuilder::createWithNoAdapters()->addAdapter(ArrayAdapter::class)->make();
$repository = RepositoryBuilder::create()->withReaders([$adapter])->withWriters([$adapter])->make();
$phpdotenv = new self(new Loader(), $repository, new StringStore($content));
$phpdotenv = new self(new StringStore($content), new Parser(), new Loader(), $repository);
return $phpdotenv->load();
}
@@ -148,19 +213,21 @@ class Dotenv
/**
* Read and load environment file(s).
*
* @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidFileException
* @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidFileException
*
* @return array<string,string|null>
*/
public function load()
{
return $this->loader->load($this->repository, $this->store->read());
$entries = $this->parser->parse($this->store->read());
return $this->loader->load($this->repository, $entries);
}
/**
* Read and load environment file(s), silently failing if no files can be read.
*
* @throws \Dotenv\Exception\InvalidFileException
* @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidFileException
*
* @return array<string,string|null>
*/
@@ -183,7 +250,7 @@ class Dotenv
*/
public function required($variables)
{
return new Validator($this->repository, (array) $variables);
return (new Validator($this->repository, (array) $variables))->required();
}
/**
@@ -195,6 +262,6 @@ class Dotenv
*/
public function ifPresent($variables)
{
return new Validator($this->repository, (array) $variables, false);
return new Validator($this->repository, (array) $variables);
}
}

View File

@@ -1,8 +1,12 @@
<?php
declare(strict_types=1);
namespace Dotenv\Exception;
interface ExceptionInterface
use Throwable;
interface ExceptionInterface extends Throwable
{
//
}

View File

@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Dotenv\Exception;
use InvalidArgumentException;
final class InvalidEncodingException extends InvalidArgumentException implements ExceptionInterface
{
//
}

View File

@@ -1,10 +1,12 @@
<?php
declare(strict_types=1);
namespace Dotenv\Exception;
use InvalidArgumentException;
class InvalidFileException extends InvalidArgumentException implements ExceptionInterface
final class InvalidFileException extends InvalidArgumentException implements ExceptionInterface
{
//
}

View File

@@ -1,10 +1,12 @@
<?php
declare(strict_types=1);
namespace Dotenv\Exception;
use InvalidArgumentException;
class InvalidPathException extends InvalidArgumentException implements ExceptionInterface
final class InvalidPathException extends InvalidArgumentException implements ExceptionInterface
{
//
}

View File

@@ -1,10 +1,12 @@
<?php
declare(strict_types=1);
namespace Dotenv\Exception;
use RuntimeException;
class ValidationException extends RuntimeException implements ExceptionInterface
final class ValidationException extends RuntimeException implements ExceptionInterface
{
//
}

View File

@@ -1,122 +1,47 @@
<?php
declare(strict_types=1);
namespace Dotenv\Loader;
use Dotenv\Regex\Regex;
use Dotenv\Parser\Entry;
use Dotenv\Parser\Value;
use Dotenv\Repository\RepositoryInterface;
use PhpOption\Option;
class Loader implements LoaderInterface
final class Loader implements LoaderInterface
{
/**
* The variable name whitelist.
* Load the given entries into the repository.
*
* @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.
* We'll substitute any nested variables, and send each variable to the
* repository, with the effect of actually mutating the environment.
*
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param string $content
*
* @throws \Dotenv\Exception\InvalidFileException
* @param \Dotenv\Parser\Entry[] $entries
*
* @return array<string,string|null>
*/
public function load(RepositoryInterface $repository, $content)
public function load(RepositoryInterface $repository, array $entries)
{
return $this->processEntries(
$repository,
Lines::process(Regex::split("/(\r\n|\n|\r)/", $content)->getSuccess())
);
}
return \array_reduce($entries, static function (array $vars, Entry $entry) use ($repository) {
$name = $entry->getName();
/**
* 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 = [];
$value = $entry->getValue()->map(static function (Value $value) use ($repository) {
return Resolver::resolve($repository, $value);
});
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]);
if ($value->isDefined()) {
$inner = $value->get();
if ($repository->set($name, $inner)) {
return \array_merge($vars, [$name => $inner]);
}
} else {
if ($repository->clear($name)) {
return \array_merge($vars, [$name => null]);
}
}
}
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);
return $vars;
}, []);
}
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace Dotenv\Loader;
use Dotenv\Repository\RepositoryInterface;
@@ -7,14 +9,12 @@ use Dotenv\Repository\RepositoryInterface;
interface LoaderInterface
{
/**
* Load the given environment file content into the repository.
* Load the given entries into the repository.
*
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param string $content
*
* @throws \Dotenv\Exception\InvalidFileException
* @param \Dotenv\Parser\Entry[] $entries
*
* @return array<string,string|null>
*/
public function load(RepositoryInterface $repository, $content);
public function load(RepositoryInterface $repository, array $entries);
}

View File

@@ -1,249 +0,0 @@
<?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,65 @@
<?php
declare(strict_types=1);
namespace Dotenv\Loader;
use Dotenv\Parser\Value;
use Dotenv\Repository\RepositoryInterface;
use Dotenv\Util\Regex;
use Dotenv\Util\Str;
use PhpOption\Option;
final class Resolver
{
/**
* This class is a singleton.
*
* @codeCoverageIgnore
*
* @return void
*/
private function __construct()
{
//
}
/**
* Resolve the nested variables in the given value.
*
* Replaces ${varname} patterns in the allowed positions in the variable
* value by an existing environment variable.
*
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param \Dotenv\Parser\Value $value
*
* @return string
*/
public static function resolve(RepositoryInterface $repository, Value $value)
{
return \array_reduce($value->getVars(), static function (string $s, int $i) use ($repository) {
return Str::substr($s, 0, $i).self::resolveVariable($repository, Str::substr($s, $i));
}, $value->getChars());
}
/**
* Resolve a single nested variable.
*
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param string $str
*
* @return string
*/
private static function resolveVariable(RepositoryInterface $repository, string $str)
{
return Regex::replaceCallback(
'/\A\${([a-zA-Z0-9_.]+)}/',
static 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,59 @@
<?php
declare(strict_types=1);
namespace Dotenv\Parser;
use PhpOption\Option;
final class Entry
{
/**
* The entry name.
*
* @var string
*/
private $name;
/**
* The entry value.
*
* @var \Dotenv\Parser\Value|null
*/
private $value;
/**
* Create a new entry instance.
*
* @param string $name
* @param \Dotenv\Parser\Value|null $value
*
* @return void
*/
public function __construct(string $name, Value $value = null)
{
$this->name = $name;
$this->value = $value;
}
/**
* Get the entry name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get the entry value.
*
* @return \PhpOption\Option<\Dotenv\Parser\Value>
*/
public function getValue()
{
/** @var \PhpOption\Option<\Dotenv\Parser\Value> */
return Option::fromValue($this->value);
}
}

View File

@@ -0,0 +1,300 @@
<?php
declare(strict_types=1);
namespace Dotenv\Parser;
use Dotenv\Util\Regex;
use Dotenv\Util\Str;
use GrahamCampbell\ResultType\Error;
use GrahamCampbell\ResultType\Result;
use GrahamCampbell\ResultType\Success;
final class EntryParser
{
private const INITIAL_STATE = 0;
private const UNQUOTED_STATE = 1;
private const SINGLE_QUOTED_STATE = 2;
private const DOUBLE_QUOTED_STATE = 3;
private const ESCAPE_SEQUENCE_STATE = 4;
private const WHITESPACE_STATE = 5;
private const COMMENT_STATE = 6;
private const REJECT_STATES = [self::SINGLE_QUOTED_STATE, self::DOUBLE_QUOTED_STATE, self::ESCAPE_SEQUENCE_STATE];
/**
* This class is a singleton.
*
* @codeCoverageIgnore
*
* @return void
*/
private function __construct()
{
//
}
/**
* Parse a raw entry into a proper entry.
*
* That is, turn a raw environment variable entry into a name and possibly
* a value. We wrap the answer in a result type.
*
* @param string $entry
*
* @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry,string>
*/
public static function parse(string $entry)
{
return self::splitStringIntoParts($entry)->flatMap(static function (array $parts) {
[$name, $value] = $parts;
return self::parseName($name)->flatMap(static function (string $name) use ($value) {
/** @var Result<Value|null,string> */
$parsedValue = $value === null ? Success::create(null) : self::parseValue($value);
return $parsedValue->map(static function (?Value $value) use ($name) {
return new Entry($name, $value);
});
});
});
}
/**
* Split the compound string into parts.
*
* @param string $line
*
* @return \GrahamCampbell\ResultType\Result<array{string,string|null},string>
*/
private static function splitStringIntoParts(string $line)
{
/** @var array{string,string|null} */
$result = Str::pos($line, '=')->map(static function () use ($line) {
return \array_map('trim', \explode('=', $line, 2));
})->getOrElse([$line, null]);
if ($result[0] === '') {
/** @var \GrahamCampbell\ResultType\Result<array{string,string|null},string> */
return Error::create(self::getErrorMessage('an unexpected equals', $line));
}
/** @var \GrahamCampbell\ResultType\Result<array{string,string|null},string> */
return Success::create($result);
}
/**
* Parse the given variable name.
*
* That is, strip the optional quotes and leading "export" from the
* variable name. We wrap the answer in a result type.
*
* @param string $name
*
* @return \GrahamCampbell\ResultType\Result<string,string>
*/
private static function parseName(string $name)
{
if (Str::len($name) > 8 && Str::substr($name, 0, 6) === 'export' && \ctype_space(Str::substr($name, 6, 1))) {
$name = \ltrim(Str::substr($name, 6));
}
if (self::isQuotedName($name)) {
$name = Str::substr($name, 1, -1);
}
if (!self::isValidName($name)) {
/** @var \GrahamCampbell\ResultType\Result<string,string> */
return Error::create(self::getErrorMessage('an invalid name', $name));
}
/** @var \GrahamCampbell\ResultType\Result<string,string> */
return Success::create($name);
}
/**
* Is the given variable name quoted?
*
* @param string $name
*
* @return bool
*/
private static function isQuotedName(string $name)
{
if (Str::len($name) < 3) {
return false;
}
$first = Str::substr($name, 0, 1);
$last = Str::substr($name, -1, 1);
return ($first === '"' && $last === '"') || ($first === '\'' && $last === '\'');
}
/**
* Is the given variable name valid?
*
* @param string $name
*
* @return bool
*/
private static function isValidName(string $name)
{
return Regex::matches('~(*UTF8)\A[\p{Ll}\p{Lu}\p{M}\p{N}_.]+\z~', $name)->success()->getOrElse(false);
}
/**
* Parse the given variable value.
*
* This has the effect of stripping quotes and comments, dealing with
* special characters, and locating nested variables, but not resolving
* them. Formally, we run a finite state automaton with an output tape: a
* transducer. We wrap the answer in a result type.
*
* @param string $value
*
* @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value,string>
*/
private static function parseValue(string $value)
{
if (\trim($value) === '') {
/** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value,string> */
return Success::create(Value::blank());
}
return \array_reduce(\iterator_to_array(Lexer::lex($value)), static function (Result $data, string $token) {
return $data->flatMap(static function (array $data) use ($token) {
return self::processToken($data[1], $token)->map(static function (array $val) use ($data) {
return [$data[0]->append($val[0], $val[1]), $val[2]];
});
});
}, Success::create([Value::blank(), self::INITIAL_STATE]))->flatMap(static function (array $result) {
/** @psalm-suppress DocblockTypeContradiction */
if (in_array($result[1], self::REJECT_STATES, true)) {
/** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value,string> */
return Error::create('a missing closing quote');
}
/** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Value,string> */
return Success::create($result[0]);
})->mapError(static function (string $err) use ($value) {
return self::getErrorMessage($err, $value);
});
}
/**
* Process the given token.
*
* @param int $state
* @param string $token
*
* @return \GrahamCampbell\ResultType\Result<array{string,bool,int},string>
*/
private static function processToken(int $state, string $token)
{
switch ($state) {
case self::INITIAL_STATE:
if ($token === '\'') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::SINGLE_QUOTED_STATE]);
} elseif ($token === '"') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::DOUBLE_QUOTED_STATE]);
} elseif ($token === '#') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::COMMENT_STATE]);
} elseif ($token === '$') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create([$token, true, self::UNQUOTED_STATE]);
} else {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create([$token, false, self::UNQUOTED_STATE]);
}
case self::UNQUOTED_STATE:
if ($token === '#') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::COMMENT_STATE]);
} elseif (\ctype_space($token)) {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::WHITESPACE_STATE]);
} elseif ($token === '$') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create([$token, true, self::UNQUOTED_STATE]);
} else {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create([$token, false, self::UNQUOTED_STATE]);
}
case self::SINGLE_QUOTED_STATE:
if ($token === '\'') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::WHITESPACE_STATE]);
} else {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create([$token, false, self::SINGLE_QUOTED_STATE]);
}
case self::DOUBLE_QUOTED_STATE:
if ($token === '"') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::WHITESPACE_STATE]);
} elseif ($token === '\\') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::ESCAPE_SEQUENCE_STATE]);
} elseif ($token === '$') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create([$token, true, self::DOUBLE_QUOTED_STATE]);
} else {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]);
}
case self::ESCAPE_SEQUENCE_STATE:
if ($token === '"' || $token === '\\') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]);
} elseif ($token === '$') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create([$token, false, self::DOUBLE_QUOTED_STATE]);
} else {
$first = Str::substr($token, 0, 1);
if (\in_array($first, ['f', 'n', 'r', 't', 'v'], true)) {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create([\stripcslashes('\\'.$first).Str::substr($token, 1), false, self::DOUBLE_QUOTED_STATE]);
} else {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Error::create('an unexpected escape sequence');
}
}
case self::WHITESPACE_STATE:
if ($token === '#') {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::COMMENT_STATE]);
} elseif (!\ctype_space($token)) {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Error::create('unexpected whitespace');
} else {
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::WHITESPACE_STATE]);
}
case self::COMMENT_STATE:
/** @var \GrahamCampbell\ResultType\Result<array{string,bool,int},string> */
return Success::create(['', false, self::COMMENT_STATE]);
default:
throw new \Error('Parser entered invalid state.');
}
}
/**
* Generate a friendly error message.
*
* @param string $cause
* @param string $subject
*
* @return string
*/
private static function getErrorMessage(string $cause, string $subject)
{
return \sprintf(
'Encountered %s at [%s].',
$cause,
\strtok($subject, "\n")
);
}
}

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Dotenv\Parser;
final class Lexer
{
/**
* The regex for each type of token.
*/
private const PATTERNS = [
'[\r\n]{1,1000}', '[^\S\r\n]{1,1000}', '\\\\', '\'', '"', '\\#', '\\$', '([^(\s\\\\\'"\\#\\$)]|\\(|\\)){1,1000}',
];
/**
* This class is a singleton.
*
* @codeCoverageIgnore
*
* @return void
*/
private function __construct()
{
//
}
/**
* Convert content into a token stream.
*
* Multibyte string processing is not needed here, and nether is error
* handling, for performance reasons.
*
* @param string $content
*
* @return \Generator<string>
*/
public static function lex(string $content)
{
static $regex;
if ($regex === null) {
$regex = '(('.\implode(')|(', self::PATTERNS).'))A';
}
$offset = 0;
while (isset($content[$offset])) {
if (!\preg_match($regex, $content, $matches, 0, $offset)) {
throw new \Error(\sprintf('Lexer encountered unexpected character [%s].', $content[$offset]));
}
$offset += \strlen($matches[0]);
yield $matches[0];
}
}
}

View File

@@ -1,13 +1,30 @@
<?php
namespace Dotenv\Loader;
declare(strict_types=1);
class Lines
namespace Dotenv\Parser;
use Dotenv\Util\Regex;
use Dotenv\Util\Str;
final class Lines
{
/**
* This class is a singleton.
*
* @codeCoverageIgnore
*
* @return void
*/
private function __construct()
{
//
}
/**
* Process the array of lines of environment variables.
*
* This will produce an array of entries, one per variable.
* This will produce an array of raw entries, one per variable.
*
* @param string[] $lines
*
@@ -20,7 +37,7 @@ class Lines
$multilineBuffer = [];
foreach ($lines as $line) {
list($multiline, $line, $multilineBuffer) = self::multilineProcess($multiline, $line, $multilineBuffer);
[$multiline, $line, $multilineBuffer] = self::multilineProcess($multiline, $line, $multilineBuffer);
if (!$multiline && !self::isCommentOrWhitespace($line)) {
$output[] = $line;
@@ -39,7 +56,7 @@ class Lines
*
* @return array{bool,string,string[]}
*/
private static function multilineProcess($multiline, $line, array $buffer)
private static function multilineProcess(bool $multiline, string $line, array $buffer)
{
$startsOnCurrentLine = $multiline ? false : self::looksLikeMultilineStart($line);
@@ -49,11 +66,11 @@ class Lines
}
if ($multiline) {
array_push($buffer, $line);
\array_push($buffer, $line);
if (self::looksLikeMultilineStop($line, $startsOnCurrentLine)) {
$multiline = false;
$line = implode("\n", $buffer);
$line = \implode("\n", $buffer);
$buffer = [];
}
}
@@ -68,13 +85,11 @@ class Lines
*
* @return bool
*/
private static function looksLikeMultilineStart($line)
private static function looksLikeMultilineStart(string $line)
{
if (strpos($line, '="') === false) {
return false;
}
return self::looksLikeMultilineStop($line, true) === false;
return Str::pos($line, '="')->map(static function () use ($line) {
return self::looksLikeMultilineStop($line, true) === false;
})->getOrElse(false);
}
/**
@@ -85,36 +100,15 @@ class Lines
*
* @return bool
*/
private static function looksLikeMultilineStop($line, $started)
private static function looksLikeMultilineStop(string $line, bool $started)
{
if ($line === '"') {
return true;
}
$seen = $started ? 0 : 1;
foreach (self::getCharPairs(str_replace('\\\\', '', $line)) as $pair) {
if ($pair[0] !== '\\' && $pair[1] === '"') {
$seen++;
}
}
return $seen > 1;
}
/**
* Get all pairs of adjacent characters within the line.
*
* @param string $line
*
* @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));
return Regex::occurrences('/(?=([^\\\\]"))/', \str_replace('\\\\', '', $line))->map(static function (int $count) use ($started) {
return $started ? $count > 1 : $count >= 1;
})->success()->getOrElse(false);
}
/**
@@ -124,14 +118,10 @@ class Lines
*
* @return bool
*/
private static function isCommentOrWhitespace($line)
private static function isCommentOrWhitespace(string $line)
{
if (trim($line) === '') {
return true;
}
$line = \trim($line);
$line = ltrim($line);
return isset($line[0]) && $line[0] === '#';
return $line === '' || (isset($line[0]) && $line[0] === '#');
}
}

View File

@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Dotenv\Parser;
use Dotenv\Exception\InvalidFileException;
use Dotenv\Util\Regex;
use GrahamCampbell\ResultType\Result;
use GrahamCampbell\ResultType\Success;
final class Parser implements ParserInterface
{
/**
* Parse content into an entry array.
*
* @param string $content
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return \Dotenv\Parser\Entry[]
*/
public function parse(string $content)
{
return Regex::split("/(\r\n|\n|\r)/", $content)->mapError(static function () {
return 'Could not split into separate lines.';
})->flatMap(static function (array $lines) {
return self::process(Lines::process($lines));
})->mapError(static function (string $error) {
throw new InvalidFileException(\sprintf('Failed to parse dotenv file. %s', $error));
})->success()->get();
}
/**
* Convert the raw entries into proper entries.
*
* @param string[] $entries
*
* @return \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry[],string>
*/
private static function process(array $entries)
{
/** @var \GrahamCampbell\ResultType\Result<\Dotenv\Parser\Entry[],string> */
return \array_reduce($entries, static function (Result $result, string $raw) {
return $result->flatMap(static function (array $entries) use ($raw) {
return EntryParser::parse($raw)->map(static function (Entry $entry) use ($entries) {
/** @var \Dotenv\Parser\Entry[] */
return \array_merge($entries, [$entry]);
});
});
}, Success::create([]));
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Dotenv\Parser;
interface ParserInterface
{
/**
* Parse content into an entry array.
*
* @param string $content
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return \Dotenv\Parser\Entry[]
*/
public function parse(string $content);
}

View File

@@ -1,8 +1,12 @@
<?php
namespace Dotenv\Loader;
declare(strict_types=1);
class Value
namespace Dotenv\Parser;
use Dotenv\Util\Str;
final class Value
{
/**
* The string representation of the parsed value.
@@ -26,7 +30,7 @@ class Value
*
* @return void
*/
private function __construct($chars, array $vars)
private function __construct(string $chars, array $vars)
{
$this->chars = $chars;
$this->vars = $vars;
@@ -35,7 +39,7 @@ class Value
/**
* Create an empty value instance.
*
* @return \Dotenv\Loader\Value
* @return \Dotenv\Parser\Value
*/
public static function blank()
{
@@ -43,18 +47,18 @@ class Value
}
/**
* Create a new value instance, appending the character.
* Create a new value instance, appending the characters.
*
* @param string $char
* @param string $chars
* @param bool $var
*
* @return \Dotenv\Loader\Value
* @return \Dotenv\Parser\Value
*/
public function append($char, $var)
public function append(string $chars, bool $var)
{
return new self(
$this->chars.$char,
$var ? array_merge($this->vars, [strlen($this->chars)]) : $this->vars
$this->chars.$chars,
$var ? \array_merge($this->vars, [Str::len($this->chars)]) : $this->vars
);
}
@@ -76,7 +80,8 @@ class Value
public function getVars()
{
$vars = $this->vars;
rsort($vars);
\rsort($vars);
return $vars;
}

View File

@@ -1,127 +0,0 @@
<?php
namespace Dotenv\Regex;
use Dotenv\Result\Error;
use Dotenv\Result\Result;
use Dotenv\Result\Success;
class Regex
{
/**
* Perform a preg match, wrapping up the result.
*
* @param string $pattern
* @param string $subject
*
* @return \Dotenv\Result\Result<int,string>
*/
public static function match($pattern, $subject)
{
return self::pregAndWrap(function ($subject) use ($pattern) {
return (int) @preg_match($pattern, $subject);
}, $subject);
}
/**
* Perform a preg replace, wrapping up the result.
*
* @param string $pattern
* @param string $replacement
* @param string $subject
* @param int|null $limit
*
* @return \Dotenv\Result\Result<string,string>
*/
public static function replace($pattern, $replacement, $subject, $limit = null)
{
return self::pregAndWrap(function ($subject) use ($pattern, $replacement, $limit) {
return (string) @preg_replace($pattern, $replacement, $subject, $limit === null ? -1 : $limit);
}, $subject);
}
/**
* Perform a preg replace callback, wrapping up the result.
*
* @param string $pattern
* @param callable $callback
* @param string $subject
* @param int|null $limit
*
* @return \Dotenv\Result\Result<string,string>
*/
public static function replaceCallback($pattern, callable $callback, $subject, $limit = null)
{
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.
*
* @template V
*
* @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);
}
/**
* Lookup the preg error code.
*
* @param int $code
*
* @return string
*/
private static function lookupError($code)
{
if (defined('PREG_JIT_STACKLIMIT_ERROR') && $code === PREG_JIT_STACKLIMIT_ERROR) {
return 'JIT stack limit exhausted';
}
switch ($code) {
case PREG_INTERNAL_ERROR:
return 'Internal error';
case PREG_BAD_UTF8_ERROR:
return 'Malformed UTF-8 characters, possibly incorrectly encoded';
case PREG_BAD_UTF8_OFFSET_ERROR:
return 'The offset did not correspond to the beginning of a valid UTF-8 code point';
case PREG_BACKTRACK_LIMIT_ERROR:
return 'Backtrack limit exhausted';
case PREG_RECURSION_LIMIT_ERROR:
return 'Recursion limit exhausted';
default:
return 'Unknown error';
}
}
}

View File

@@ -1,180 +0,0 @@
<?php
namespace Dotenv\Repository;
use Dotenv\Repository\Adapter\ArrayAdapter;
use InvalidArgumentException;
use ReturnTypeWillChange;
abstract class AbstractRepository implements RepositoryInterface
{
/**
* Are we immutable?
*
* @var bool
*/
private $immutable;
/**
* The record of loaded variables.
*
* @var \Dotenv\Repository\Adapter\ArrayAdapter
*/
private $loaded;
/**
* Create a new repository instance.
*
* @param bool $immutable
*
* @return void
*/
public function __construct($immutable)
{
$this->immutable = $immutable;
$this->loaded = new ArrayAdapter();
}
/**
* Get an environment variable.
*
* @param string $name
*
* @throws \InvalidArgumentException
*
* @return string|null
*/
public function get($name)
{
if (!is_string($name) || '' === $name) {
throw new InvalidArgumentException('Expected name to be a non-empty string.');
}
return $this->getInternal($name);
}
/**
* Get an environment variable.
*
* @param non-empty-string $name
*
* @return string|null
*/
abstract protected function getInternal($name);
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function set($name, $value = null)
{
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->immutable && $this->get($name) !== null && $this->loaded->get($name)->isEmpty()) {
return;
}
$this->setInternal($name, $value);
$this->loaded->set($name, '');
}
/**
* Set an environment variable.
*
* @param non-empty-string $name
* @param string|null $value
*
* @return void
*/
abstract protected function setInternal($name, $value = null);
/**
* Clear an environment variable.
*
* @param string $name
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function clear($name)
{
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->immutable) {
return;
}
$this->clearInternal($name);
}
/**
* Clear an environment variable.
*
* @param non-empty-string $name
*
* @return void
*/
abstract protected function clearInternal($name);
/**
* Tells whether environment variable has been defined.
*
* @param string $name
*
* @return bool
*/
public function has($name)
{
return is_string($name) && $name !== '' && $this->get($name) !== null;
}
/**
* {@inheritdoc}
*/
#[ReturnTypeWillChange]
public function offsetExists($offset)
{
return $this->has($offset);
}
/**
* {@inheritdoc}
*/
#[ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->get($offset);
}
/**
* {@inheritdoc}
*/
#[ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
$this->set($offset, $value);
}
/**
* {@inheritdoc}
*/
#[ReturnTypeWillChange]
public function offsetUnset($offset)
{
$this->clear($offset);
}
}

View File

@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
interface AdapterInterface extends ReaderInterface, WriterInterface
{
/**
* Create a new instance of the adapter, if it is available.
*
* @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface>
*/
public static function create();
}

View File

@@ -1,11 +1,40 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
use PhpOption\None;
use PhpOption\Option;
use PhpOption\Some;
class ApacheAdapter implements AvailabilityInterface, ReaderInterface, WriterInterface
final class ApacheAdapter implements AdapterInterface
{
/**
* Create a new apache adapter instance.
*
* @return void
*/
private function __construct()
{
//
}
/**
* Create a new instance of the adapter, if it is available.
*
* @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface>
*/
public static function create()
{
if (self::isSupported()) {
/** @var \PhpOption\Option<AdapterInterface> */
return Some::create(new self());
}
return None::create();
}
/**
* Determines if the adapter is supported.
*
@@ -13,54 +42,48 @@ class ApacheAdapter implements AvailabilityInterface, ReaderInterface, WriterInt
*
* @return bool
*/
public function isSupported()
private static function isSupported()
{
return function_exists('apache_getenv') && function_exists('apache_setenv');
return \function_exists('apache_getenv') && \function_exists('apache_setenv');
}
/**
* Get an environment variable, if it exists.
*
* This is intentionally not implemented, since this adapter exists only as
* a means to overwrite existing apache environment variables.
* Read an environment variable, if it exists.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string|null>
* @return \PhpOption\Option<string>
*/
public function get($name)
public function read(string $name)
{
return None::create();
/** @var \PhpOption\Option<string> */
return Option::fromValue(apache_getenv($name))->filter(static function ($value) {
return \is_string($value) && $value !== '';
});
}
/**
* Set an environment variable.
*
* Only if an existing apache variable exists do we overwrite it.
* Write to an environment variable, if possible.
*
* @param non-empty-string $name
* @param string|null $value
* @param string $value
*
* @return void
* @return bool
*/
public function set($name, $value = null)
public function write(string $name, string $value)
{
if (apache_getenv($name) === false) {
return;
}
apache_setenv($name, (string) $value);
return apache_setenv($name, $value);
}
/**
* Clear an environment variable.
* Delete an environment variable, if possible.
*
* @param non-empty-string $name
*
* @return void
* @return bool
*/
public function clear($name)
public function delete(string $name)
{
// Nothing to do here.
return apache_setenv($name, '');
}
}

View File

@@ -1,67 +1,80 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
use PhpOption\None;
use PhpOption\Option;
use PhpOption\Some;
class ArrayAdapter implements AvailabilityInterface, ReaderInterface, WriterInterface
final class ArrayAdapter implements AdapterInterface
{
/**
* The variables and their values.
*
* @var array<non-empty-string,string|null>
* @var array<string,string>
*/
private $variables = [];
private $variables;
/**
* Determines if the adapter is supported.
* Create a new array adapter instance.
*
* @return void
*/
private function __construct()
{
$this->variables = [];
}
/**
* Create a new instance of the adapter, if it is available.
*
* @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface>
*/
public static function create()
{
/** @var \PhpOption\Option<AdapterInterface> */
return Some::create(new self());
}
/**
* Read an environment variable, if it exists.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string>
*/
public function read(string $name)
{
return Option::fromArraysValue($this->variables, $name);
}
/**
* Write to an environment variable, if possible.
*
* @param non-empty-string $name
* @param string $value
*
* @return bool
*/
public function isSupported()
public function write(string $name, string $value)
{
$this->variables[$name] = $value;
return true;
}
/**
* Get an environment variable, if it exists.
* Delete an environment variable, if possible.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string|null>
* @return bool
*/
public function get($name)
{
if (!array_key_exists($name, $this->variables)) {
return None::create();
}
return Some::create($this->variables[$name]);
}
/**
* Set an environment variable.
*
* @param non-empty-string $name
* @param string|null $value
*
* @return void
*/
public function set($name, $value = null)
{
$this->variables[$name] = $value;
}
/**
* Clear an environment variable.
*
* @param non-empty-string $name
*
* @return void
*/
public function clear($name)
public function delete(string $name)
{
unset($this->variables[$name]);
return true;
}
}

View File

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

View File

@@ -1,72 +1,89 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
use PhpOption\None;
use PhpOption\Option;
use PhpOption\Some;
class EnvConstAdapter implements AvailabilityInterface, ReaderInterface, WriterInterface
final class EnvConstAdapter implements AdapterInterface
{
/**
* Determines if the adapter is supported.
* Create a new env const adapter instance.
*
* @return void
*/
private function __construct()
{
//
}
/**
* Create a new instance of the adapter, if it is available.
*
* @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface>
*/
public static function create()
{
/** @var \PhpOption\Option<AdapterInterface> */
return Some::create(new self());
}
/**
* Read an environment variable, if it exists.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string>
*/
public function read(string $name)
{
/** @var \PhpOption\Option<string> */
return Option::fromArraysValue($_ENV, $name)
->filter(static function ($value) {
return \is_scalar($value);
})
->map(static function ($value) {
if ($value === false) {
return 'false';
}
if ($value === true) {
return 'true';
}
/** @psalm-suppress PossiblyInvalidCast */
return (string) $value;
});
}
/**
* Write to an environment variable, if possible.
*
* @param non-empty-string $name
* @param string $value
*
* @return bool
*/
public function isSupported()
public function write(string $name, string $value)
{
$_ENV[$name] = $value;
return true;
}
/**
* Get an environment variable, if it exists.
* Delete an environment variable, if possible.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string|null>
* @return bool
*/
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)
public function delete(string $name)
{
unset($_ENV[$name]);
return true;
}
}

View File

@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
final class GuardedWriter implements WriterInterface
{
/**
* The inner writer to use.
*
* @var \Dotenv\Repository\Adapter\WriterInterface
*/
private $writer;
/**
* The variable name allow list.
*
* @var string[]
*/
private $allowList;
/**
* Create a new guarded writer instance.
*
* @param \Dotenv\Repository\Adapter\WriterInterface $writer
* @param string[] $allowList
*
* @return void
*/
public function __construct(WriterInterface $writer, array $allowList)
{
$this->writer = $writer;
$this->allowList = $allowList;
}
/**
* Write to an environment variable, if possible.
*
* @param non-empty-string $name
* @param string $value
*
* @return bool
*/
public function write(string $name, string $value)
{
// Don't set non-allowed variables
if (!$this->isAllowed($name)) {
return false;
}
// Set the value on the inner writer
return $this->writer->write($name, $value);
}
/**
* Delete an environment variable, if possible.
*
* @param non-empty-string $name
*
* @return bool
*/
public function delete(string $name)
{
// Don't clear non-allowed variables
if (!$this->isAllowed($name)) {
return false;
}
// Set the value on the inner writer
return $this->writer->delete($name);
}
/**
* Determine if the given variable is allowed.
*
* @param non-empty-string $name
*
* @return bool
*/
private function isAllowed(string $name)
{
return \in_array($name, $this->allowList, true);
}
}

View File

@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
final class ImmutableWriter implements WriterInterface
{
/**
* The inner writer to use.
*
* @var \Dotenv\Repository\Adapter\WriterInterface
*/
private $writer;
/**
* The inner reader to use.
*
* @var \Dotenv\Repository\Adapter\ReaderInterface
*/
private $reader;
/**
* The record of loaded variables.
*
* @var array<string,string>
*/
private $loaded;
/**
* Create a new immutable writer instance.
*
* @param \Dotenv\Repository\Adapter\WriterInterface $writer
* @param \Dotenv\Repository\Adapter\ReaderInterface $reader
*
* @return void
*/
public function __construct(WriterInterface $writer, ReaderInterface $reader)
{
$this->writer = $writer;
$this->reader = $reader;
$this->loaded = [];
}
/**
* Write to an environment variable, if possible.
*
* @param non-empty-string $name
* @param string $value
*
* @return bool
*/
public function write(string $name, string $value)
{
// Don't overwrite existing environment variables
// Ruby's dotenv does this with `ENV[key] ||= value`
if ($this->isExternallyDefined($name)) {
return false;
}
// Set the value on the inner writer
if (!$this->writer->write($name, $value)) {
return false;
}
// Record that we have loaded the variable
$this->loaded[$name] = '';
return true;
}
/**
* Delete an environment variable, if possible.
*
* @param non-empty-string $name
*
* @return bool
*/
public function delete(string $name)
{
// Don't clear existing environment variables
if ($this->isExternallyDefined($name)) {
return false;
}
// Clear the value on the inner writer
if (!$this->writer->delete($name)) {
return false;
}
// Leave the variable as fair game
unset($this->loaded[$name]);
return true;
}
/**
* Determine if the given variable is externally defined.
*
* That is, is it an "existing" variable.
*
* @param non-empty-string $name
*
* @return bool
*/
private function isExternallyDefined(string $name)
{
return $this->reader->read($name)->isDefined() && !isset($this->loaded[$name]);
}
}

View File

@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
use PhpOption\None;
final class MultiReader implements ReaderInterface
{
/**
* The set of readers to use.
*
* @var \Dotenv\Repository\Adapter\ReaderInterface[]
*/
private $readers;
/**
* Create a new multi-reader instance.
*
* @param \Dotenv\Repository\Adapter\ReaderInterface[] $readers
*
* @return void
*/
public function __construct(array $readers)
{
$this->readers = $readers;
}
/**
* Read an environment variable, if it exists.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string>
*/
public function read(string $name)
{
foreach ($this->readers as $reader) {
$result = $reader->read($name);
if ($result->isDefined()) {
return $result;
}
}
return None::create();
}
}

View File

@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
final class MultiWriter implements WriterInterface
{
/**
* The set of writers to use.
*
* @var \Dotenv\Repository\Adapter\WriterInterface[]
*/
private $writers;
/**
* Create a new multi-writer instance.
*
* @param \Dotenv\Repository\Adapter\WriterInterface[] $writers
*
* @return void
*/
public function __construct(array $writers)
{
$this->writers = $writers;
}
/**
* Write to an environment variable, if possible.
*
* @param non-empty-string $name
* @param string $value
*
* @return bool
*/
public function write(string $name, string $value)
{
foreach ($this->writers as $writers) {
if (!$writers->write($name, $value)) {
return false;
}
}
return true;
}
/**
* Delete an environment variable, if possible.
*
* @param non-empty-string $name
*
* @return bool
*/
public function delete(string $name)
{
foreach ($this->writers as $writers) {
if (!$writers->delete($name)) {
return false;
}
}
return true;
}
}

View File

@@ -1,56 +1,91 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
use PhpOption\None;
use PhpOption\Option;
use PhpOption\Some;
class PutenvAdapter implements AvailabilityInterface, ReaderInterface, WriterInterface
final class PutenvAdapter implements AdapterInterface
{
/**
* Create a new putenv adapter instance.
*
* @return void
*/
private function __construct()
{
//
}
/**
* Create a new instance of the adapter, if it is available.
*
* @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface>
*/
public static function create()
{
if (self::isSupported()) {
/** @var \PhpOption\Option<AdapterInterface> */
return Some::create(new self());
}
return None::create();
}
/**
* Determines if the adapter is supported.
*
* @return bool
*/
public function isSupported()
private static function isSupported()
{
return function_exists('getenv') && function_exists('putenv');
return \function_exists('getenv') && \function_exists('putenv');
}
/**
* Get an environment variable, if it exists.
* Read an environment variable, if it exists.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string|null>
* @return \PhpOption\Option<string>
*/
public function get($name)
public function read(string $name)
{
/** @var \PhpOption\Option<string|null> */
return Option::fromValue(getenv($name), false);
/** @var \PhpOption\Option<string> */
return Option::fromValue(\getenv($name), false)->filter(static function ($value) {
return \is_string($value);
});
}
/**
* Set an environment variable.
* Write to an environment variable, if possible.
*
* @param non-empty-string $name
* @param string|null $value
* @param string $value
*
* @return void
* @return bool
*/
public function set($name, $value = null)
public function write(string $name, string $value)
{
putenv("$name=$value");
\putenv("$name=$value");
return true;
}
/**
* Clear an environment variable.
* Delete an environment variable, if possible.
*
* @param non-empty-string $name
*
* @return void
* @return bool
*/
public function clear($name)
public function delete(string $name)
{
putenv($name);
\putenv($name);
return true;
}
}

View File

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

View File

@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
final class ReplacingWriter implements WriterInterface
{
/**
* The inner writer to use.
*
* @var \Dotenv\Repository\Adapter\WriterInterface
*/
private $writer;
/**
* The inner reader to use.
*
* @var \Dotenv\Repository\Adapter\ReaderInterface
*/
private $reader;
/**
* The record of seen variables.
*
* @var array<string,string>
*/
private $seen;
/**
* Create a new replacement writer instance.
*
* @param \Dotenv\Repository\Adapter\WriterInterface $writer
* @param \Dotenv\Repository\Adapter\ReaderInterface $reader
*
* @return void
*/
public function __construct(WriterInterface $writer, ReaderInterface $reader)
{
$this->writer = $writer;
$this->reader = $reader;
$this->seen = [];
}
/**
* Write to an environment variable, if possible.
*
* @param non-empty-string $name
* @param string $value
*
* @return bool
*/
public function write(string $name, string $value)
{
if ($this->exists($name)) {
return $this->writer->write($name, $value);
}
// succeed if nothing to do
return true;
}
/**
* Delete an environment variable, if possible.
*
* @param non-empty-string $name
*
* @return bool
*/
public function delete(string $name)
{
if ($this->exists($name)) {
return $this->writer->delete($name);
}
// succeed if nothing to do
return true;
}
/**
* Does the given environment variable exist.
*
* Returns true if it currently exists, or existed at any point in the past
* that we are aware of.
*
* @param non-empty-string $name
*
* @return bool
*/
private function exists(string $name)
{
if (isset($this->seen[$name])) {
return true;
}
if ($this->reader->read($name)->isDefined()) {
$this->seen[$name] = '';
return true;
}
return false;
}
}

View File

@@ -1,72 +1,89 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
use PhpOption\None;
use PhpOption\Option;
use PhpOption\Some;
class ServerConstAdapter implements AvailabilityInterface, ReaderInterface, WriterInterface
final class ServerConstAdapter implements AdapterInterface
{
/**
* Determines if the adapter is supported.
* Create a new server const adapter instance.
*
* @return void
*/
private function __construct()
{
//
}
/**
* Create a new instance of the adapter, if it is available.
*
* @return \PhpOption\Option<\Dotenv\Repository\Adapter\AdapterInterface>
*/
public static function create()
{
/** @var \PhpOption\Option<AdapterInterface> */
return Some::create(new self());
}
/**
* Read an environment variable, if it exists.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string>
*/
public function read(string $name)
{
/** @var \PhpOption\Option<string> */
return Option::fromArraysValue($_SERVER, $name)
->filter(static function ($value) {
return \is_scalar($value);
})
->map(static function ($value) {
if ($value === false) {
return 'false';
}
if ($value === true) {
return 'true';
}
/** @psalm-suppress PossiblyInvalidCast */
return (string) $value;
});
}
/**
* Write to an environment variable, if possible.
*
* @param non-empty-string $name
* @param string $value
*
* @return bool
*/
public function isSupported()
public function write(string $name, string $value)
{
$_SERVER[$name] = $value;
return true;
}
/**
* Get an environment variable, if it exists.
* Delete an environment variable, if possible.
*
* @param non-empty-string $name
*
* @return \PhpOption\Option<string|null>
* @return bool
*/
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)
public function delete(string $name)
{
unset($_SERVER[$name]);
return true;
}
}

View File

@@ -1,25 +1,27 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository\Adapter;
interface WriterInterface extends AvailabilityInterface
interface WriterInterface
{
/**
* Set an environment variable.
* Write to an environment variable, if possible.
*
* @param non-empty-string $name
* @param string|null $value
* @param string $value
*
* @return void
* @return bool
*/
public function set($name, $value = null);
public function write(string $name, string $value);
/**
* Clear an environment variable.
* Delete an environment variable, if possible.
*
* @param non-empty-string $name
*
* @return void
* @return bool
*/
public function clear($name);
public function delete(string $name);
}

View File

@@ -1,86 +1,107 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository;
class AdapterRepository extends AbstractRepository
use Dotenv\Repository\Adapter\ReaderInterface;
use Dotenv\Repository\Adapter\WriterInterface;
use InvalidArgumentException;
final class AdapterRepository implements RepositoryInterface
{
/**
* The set of readers to use.
* The reader to use.
*
* @var \Dotenv\Repository\Adapter\ReaderInterface[]
* @var \Dotenv\Repository\Adapter\ReaderInterface
*/
protected $readers;
private $reader;
/**
* The set of writers to use.
* The writer to use.
*
* @var \Dotenv\Repository\Adapter\WriterInterface[]
* @var \Dotenv\Repository\Adapter\WriterInterface
*/
protected $writers;
private $writer;
/**
* Create a new adapter repository instance.
*
* @param \Dotenv\Repository\Adapter\ReaderInterface[] $readers
* @param \Dotenv\Repository\Adapter\WriterInterface[] $writers
* @param bool $immutable
* @param \Dotenv\Repository\Adapter\ReaderInterface $reader
* @param \Dotenv\Repository\Adapter\WriterInterface $writer
*
* @return void
*/
public function __construct(array $readers, array $writers, $immutable)
public function __construct(ReaderInterface $reader, WriterInterface $writer)
{
$this->readers = $readers;
$this->writers = $writers;
parent::__construct($immutable);
$this->reader = $reader;
$this->writer = $writer;
}
/**
* Determine if the given environment variable is defined.
*
* @param string $name
*
* @return bool
*/
public function has(string $name)
{
return '' !== $name && $this->reader->read($name)->isDefined();
}
/**
* Get an environment variable.
*
* We do this by querying our readers sequentially.
* @param string $name
*
* @param non-empty-string $name
* @throws \InvalidArgumentException
*
* @return string|null
*/
protected function getInternal($name)
public function get(string $name)
{
foreach ($this->readers as $reader) {
$result = $reader->get($name);
if ($result->isDefined()) {
return $result->get();
}
if ('' === $name) {
throw new InvalidArgumentException('Expected name to be a non-empty string.');
}
return null;
return $this->reader->read($name)->getOrElse(null);
}
/**
* Set an environment variable.
*
* @param non-empty-string $name
* @param string|null $value
* @param string $name
* @param string $value
*
* @return void
* @throws \InvalidArgumentException
*
* @return bool
*/
protected function setInternal($name, $value = null)
public function set(string $name, string $value)
{
foreach ($this->writers as $writers) {
$writers->set($name, $value);
if ('' === $name) {
throw new InvalidArgumentException('Expected name to be a non-empty string.');
}
return $this->writer->write($name, $value);
}
/**
* Clear an environment variable.
*
* @param non-empty-string $name
* @param string $name
*
* @return void
* @throws \InvalidArgumentException
*
* @return bool
*/
protected function clearInternal($name)
public function clear(string $name)
{
foreach ($this->writers as $writers) {
$writers->clear($name);
if ('' === $name) {
throw new InvalidArgumentException('Expected name to be a non-empty string.');
}
return $this->writer->delete($name);
}
}

View File

@@ -1,26 +1,43 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository;
use Dotenv\Repository\Adapter\ApacheAdapter;
use Dotenv\Repository\Adapter\AvailabilityInterface;
use Dotenv\Repository\Adapter\AdapterInterface;
use Dotenv\Repository\Adapter\EnvConstAdapter;
use Dotenv\Repository\Adapter\PutenvAdapter;
use Dotenv\Repository\Adapter\GuardedWriter;
use Dotenv\Repository\Adapter\ImmutableWriter;
use Dotenv\Repository\Adapter\MultiReader;
use Dotenv\Repository\Adapter\MultiWriter;
use Dotenv\Repository\Adapter\ReaderInterface;
use Dotenv\Repository\Adapter\ServerConstAdapter;
use Dotenv\Repository\Adapter\WriterInterface;
use InvalidArgumentException;
use PhpOption\Some;
use ReflectionClass;
class RepositoryBuilder
final class RepositoryBuilder
{
/**
* The set of default adapters.
*/
private const DEFAULT_ADAPTERS = [
ServerConstAdapter::class,
EnvConstAdapter::class,
];
/**
* The set of readers to use.
*
* @var \Dotenv\Repository\Adapter\ReaderInterface[]|null
* @var \Dotenv\Repository\Adapter\ReaderInterface[]
*/
private $readers;
/**
* The set of writers to use.
*
* @var \Dotenv\Repository\Adapter\WriterInterface[]|null
* @var \Dotenv\Repository\Adapter\WriterInterface[]
*/
private $writers;
@@ -32,57 +49,182 @@ class RepositoryBuilder
private $immutable;
/**
* Create a new repository builder instance.
* The variable name allow list.
*
* @param \Dotenv\Repository\Adapter\ReaderInterface[]|null $readers
* @param \Dotenv\Repository\Adapter\WriterInterface[]|null $writers
* @param bool $immutable
*
* @return void
* @var string[]|null
*/
private function __construct(array $readers = null, array $writers = null, $immutable = false)
{
$this->readers = $readers;
$this->writers = $writers;
$this->immutable = $immutable;
}
private $allowList;
/**
* Create a new repository builder instance.
*
* @param \Dotenv\Repository\Adapter\ReaderInterface[] $readers
* @param \Dotenv\Repository\Adapter\WriterInterface[] $writers
* @param bool $immutable
* @param string[]|null $allowList
*
* @return void
*/
private function __construct(array $readers = [], array $writers = [], bool $immutable = false, array $allowList = null)
{
$this->readers = $readers;
$this->writers = $writers;
$this->immutable = $immutable;
$this->allowList = $allowList;
}
/**
* Create a new repository builder instance with no adapters added.
*
* @return \Dotenv\Repository\RepositoryBuilder
*/
public static function create()
public static function createWithNoAdapters()
{
return new self();
}
/**
* Creates a repository builder with the given readers.
*
* @param \Dotenv\Repository\Adapter\ReaderInterface[]|null $readers
* Create a new repository builder instance with the default adapters added.
*
* @return \Dotenv\Repository\RepositoryBuilder
*/
public function withReaders(array $readers = null)
public static function createWithDefaultAdapters()
{
$readers = $readers === null ? null : self::filterByAvailability($readers);
$adapters = \iterator_to_array(self::defaultAdapters());
return new self($readers, $this->writers, $this->immutable);
return new self($adapters, $adapters);
}
/**
* Creates a repository builder with the given writers.
* Return the array of default adapters.
*
* @param \Dotenv\Repository\Adapter\WriterInterface[]|null $writers
* @return \Generator<\Dotenv\Repository\Adapter\AdapterInterface>
*/
private static function defaultAdapters()
{
foreach (self::DEFAULT_ADAPTERS as $adapter) {
$instance = $adapter::create();
if ($instance->isDefined()) {
yield $instance->get();
}
}
}
/**
* Determine if the given name if of an adapterclass.
*
* @param string $name
*
* @return bool
*/
private static function isAnAdapterClass(string $name)
{
if (!\class_exists($name)) {
return false;
}
return (new ReflectionClass($name))->implementsInterface(AdapterInterface::class);
}
/**
* Creates a repository builder with the given reader added.
*
* Accepts either a reader instance, or a class-string for an adapter. If
* the adapter is not supported, then we silently skip adding it.
*
* @param \Dotenv\Repository\Adapter\ReaderInterface|string $reader
*
* @throws \InvalidArgumentException
*
* @return \Dotenv\Repository\RepositoryBuilder
*/
public function withWriters(array $writers = null)
public function addReader($reader)
{
$writers = $writers === null ? null : self::filterByAvailability($writers);
if (!(\is_string($reader) && self::isAnAdapterClass($reader)) && !($reader instanceof ReaderInterface)) {
throw new InvalidArgumentException(
\sprintf(
'Expected either an instance of %s or a class-string implementing %s',
ReaderInterface::class,
AdapterInterface::class
)
);
}
return new self($this->readers, $writers, $this->immutable);
$optional = Some::create($reader)->flatMap(static function ($reader) {
return \is_string($reader) ? $reader::create() : Some::create($reader);
});
$readers = \array_merge($this->readers, \iterator_to_array($optional));
return new self($readers, $this->writers, $this->immutable, $this->allowList);
}
/**
* Creates a repository builder with the given writer added.
*
* Accepts either a writer instance, or a class-string for an adapter. If
* the adapter is not supported, then we silently skip adding it.
*
* @param \Dotenv\Repository\Adapter\WriterInterface|string $writer
*
* @throws \InvalidArgumentException
*
* @return \Dotenv\Repository\RepositoryBuilder
*/
public function addWriter($writer)
{
if (!(\is_string($writer) && self::isAnAdapterClass($writer)) && !($writer instanceof WriterInterface)) {
throw new InvalidArgumentException(
\sprintf(
'Expected either an instance of %s or a class-string implementing %s',
WriterInterface::class,
AdapterInterface::class
)
);
}
$optional = Some::create($writer)->flatMap(static function ($writer) {
return \is_string($writer) ? $writer::create() : Some::create($writer);
});
$writers = \array_merge($this->writers, \iterator_to_array($optional));
return new self($this->readers, $writers, $this->immutable, $this->allowList);
}
/**
* Creates a repository builder with the given adapter added.
*
* Accepts either an adapter instance, or a class-string for an adapter. If
* the adapter is not supported, then we silently skip adding it. We will
* add the adapter as both a reader and a writer.
*
* @param \Dotenv\Repository\Adapter\WriterInterface|string $adapter
*
* @throws \InvalidArgumentException
*
* @return \Dotenv\Repository\RepositoryBuilder
*/
public function addAdapter($adapter)
{
if (!(\is_string($adapter) && self::isAnAdapterClass($adapter)) && !($adapter instanceof AdapterInterface)) {
throw new InvalidArgumentException(
\sprintf(
'Expected either an instance of %s or a class-string implementing %s',
WriterInterface::class,
AdapterInterface::class
)
);
}
$optional = Some::create($adapter)->flatMap(static function ($adapter) {
return \is_string($adapter) ? $adapter::create() : Some::create($adapter);
});
$readers = \array_merge($this->readers, \iterator_to_array($optional));
$writers = \array_merge($this->writers, \iterator_to_array($optional));
return new self($readers, $writers, $this->immutable, $this->allowList);
}
/**
@@ -92,7 +234,19 @@ class RepositoryBuilder
*/
public function immutable()
{
return new self($this->readers, $this->writers, true);
return new self($this->readers, $this->writers, true, $this->allowList);
}
/**
* Creates a repository builder with the given allow list.
*
* @param string[]|null $allowList
*
* @return \Dotenv\Repository\RepositoryBuilder
*/
public function allowList(array $allowList = null)
{
return new self($this->readers, $this->writers, $this->immutable, $allowList);
}
/**
@@ -102,43 +256,17 @@ class RepositoryBuilder
*/
public function make()
{
if ($this->readers === null || $this->writers === null) {
$defaults = self::defaultAdapters();
$reader = new MultiReader($this->readers);
$writer = new MultiWriter($this->writers);
if ($this->immutable) {
$writer = new ImmutableWriter($writer, $reader);
}
return new AdapterRepository(
$this->readers === null ? $defaults : $this->readers,
$this->writers === null ? $defaults : $this->writers,
$this->immutable
);
}
if ($this->allowList !== null) {
$writer = new GuardedWriter($writer, $this->allowList);
}
/**
* 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();
});
return new AdapterRepository($reader, $writer);
}
}

View File

@@ -1,22 +1,19 @@
<?php
declare(strict_types=1);
namespace Dotenv\Repository;
use ArrayAccess;
/**
* @extends \ArrayAccess<string,string|null>
*/
interface RepositoryInterface extends ArrayAccess
interface RepositoryInterface
{
/**
* Tells whether environment variable has been defined.
* Determine if the given environment variable is defined.
*
* @param string $name
*
* @return bool
*/
public function has($name);
public function has(string $name);
/**
* Get an environment variable.
@@ -27,19 +24,19 @@ interface RepositoryInterface extends ArrayAccess
*
* @return string|null
*/
public function get($name);
public function get(string $name);
/**
* Set an environment variable.
*
* @param string $name
* @param string|null $value
* @param string $name
* @param string $value
*
* @throws \InvalidArgumentException
*
* @return void
* @return bool
*/
public function set($name, $value = null);
public function set(string $name, string $value);
/**
* Clear an environment variable.
@@ -48,7 +45,7 @@ interface RepositoryInterface extends ArrayAccess
*
* @throws \InvalidArgumentException
*
* @return void
* @return bool
*/
public function clear($name);
public function clear(string $name);
}

View File

@@ -1,94 +0,0 @@
<?php
namespace Dotenv\Result;
use PhpOption\None;
use PhpOption\Some;
/**
* @template T
* @template E
* @extends \Dotenv\Result\Result<T,E>
*/
class Error extends Result
{
/**
* @var E
*/
private $value;
/**
* Internal constructor for an error value.
*
* @param E $value
*
* @return void
*/
private function __construct($value)
{
$this->value = $value;
}
/**
* Create a new error value.
*
* @template F
*
* @param F $value
*
* @return \Dotenv\Result\Result<T,F>
*/
public static function create($value)
{
return new self($value);
}
/**
* Get the success option value.
*
* @return \PhpOption\Option<T>
*/
public function success()
{
return None::create();
}
/**
* Map over the success value.
*
* @template S
*
* @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<E>
*/
public function error()
{
return Some::create($this->value);
}
/**
* Map over the error value.
*
* @template F
*
* @param callable(E):F $f
*
* @return \Dotenv\Result\Result<T,F>
*/
public function mapError(callable $f)
{
return self::create($f($this->value));
}
}

View File

@@ -1,70 +0,0 @@
<?php
namespace Dotenv\Result;
/**
* @template T
* @template E
*/
abstract class Result
{
/**
* Get the success option value.
*
* @return \PhpOption\Option<T>
*/
abstract public function success();
/**
* Get the success value, if possible.
*
* @throws \RuntimeException
*
* @return T
*/
public function getSuccess()
{
return $this->success()->get();
}
/**
* Map over the success value.
*
* @template S
*
* @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<E>
*/
abstract public function error();
/**
* Get the error value, if possible.
*
* @throws \RuntimeException
*
* @return E
*/
public function getError()
{
return $this->error()->get();
}
/**
* Map over the error value.
*
* @template F
*
* @param callable(E):F $f
*
* @return \Dotenv\Result\Result<T,F>
*/
abstract public function mapError(callable $f);
}

View File

@@ -1,94 +0,0 @@
<?php
namespace Dotenv\Result;
use PhpOption\None;
use PhpOption\Some;
/**
* @template T
* @template E
* @extends \Dotenv\Result\Result<T,E>
*/
class Success extends Result
{
/**
* @var T
*/
private $value;
/**
* Internal constructor for a success value.
*
* @param T $value
*
* @return void
*/
private function __construct($value)
{
$this->value = $value;
}
/**
* Create a new error value.
*
* @template S
*
* @param S $value
*
* @return \Dotenv\Result\Result<S,E>
*/
public static function create($value)
{
return new self($value);
}
/**
* Get the success option value.
*
* @return \PhpOption\Option<T>
*/
public function success()
{
return Some::create($this->value);
}
/**
* Map over the success value.
*
* @template S
*
* @param callable(T):S $f
*
* @return \Dotenv\Result\Result<S,E>
*/
public function mapSuccess(callable $f)
{
return self::create($f($this->value));
}
/**
* Get the error option value.
*
* @return \PhpOption\Option<E>
*/
public function error()
{
return None::create();
}
/**
* Map over the error value.
*
* @template F
*
* @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

@@ -1,9 +1,26 @@
<?php
declare(strict_types=1);
namespace Dotenv\Store\File;
class Paths
/**
* @internal
*/
final class Paths
{
/**
* This class is a singleton.
*
* @codeCoverageIgnore
*
* @return void
*/
private function __construct()
{
//
}
/**
* Returns the full paths to the files.
*
@@ -18,7 +35,7 @@ class Paths
foreach ($paths as $path) {
foreach ($names as $name) {
$files[] = rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$name;
$files[] = \rtrim($path, \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR.$name;
}
}

View File

@@ -1,11 +1,30 @@
<?php
declare(strict_types=1);
namespace Dotenv\Store\File;
use Dotenv\Exception\InvalidEncodingException;
use Dotenv\Util\Str;
use PhpOption\Option;
class Reader
/**
* @internal
*/
final class Reader
{
/**
* This class is a singleton.
*
* @codeCoverageIgnore
*
* @return void
*/
private function __construct()
{
//
}
/**
* Read the file(s), and return their raw content.
*
@@ -13,17 +32,20 @@ class Reader
* 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
* @param string[] $filePaths
* @param bool $shortCircuit
* @param string|null $fileEncoding
*
* @throws \Dotenv\Exception\InvalidEncodingException
*
* @return array<string,string>
*/
public static function read(array $filePaths, $shortCircuit = true)
public static function read(array $filePaths, bool $shortCircuit = true, string $fileEncoding = null)
{
$output = [];
foreach ($filePaths as $filePath) {
$content = self::readFromFile($filePath);
$content = self::readFromFile($filePath, $fileEncoding);
if ($content->isDefined()) {
$output[$filePath] = $content->get();
if ($shortCircuit) {
@@ -38,15 +60,22 @@ class Reader
/**
* Read the given file.
*
* @param string $filePath
* @param string $path
* @param string|null $encoding
*
* @throws \Dotenv\Exception\InvalidEncodingException
*
* @return \PhpOption\Option<string>
*/
private static function readFromFile($filePath)
private static function readFromFile(string $path, string $encoding = null)
{
$content = @file_get_contents($filePath);
/** @var Option<string> */
$content = Option::fromValue(@\file_get_contents($path), false);
/** @var \PhpOption\Option<string> */
return Option::fromValue($content, false);
return $content->flatMap(static function (string $content) use ($encoding) {
return Str::utf8($content, $encoding)->mapError(static function (string $error) {
throw new InvalidEncodingException($error);
})->success();
});
}
}

View File

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

View File

@@ -1,11 +1,18 @@
<?php
declare(strict_types=1);
namespace Dotenv\Store;
use Dotenv\Store\File\Paths;
class StoreBuilder
final class StoreBuilder
{
/**
* The of default name.
*/
private const DEFAULT_NAME = '.env';
/**
* The paths to search within.
*
@@ -16,7 +23,7 @@ class StoreBuilder
/**
* The file names to search for.
*
* @var string[]|null
* @var string[]
*/
private $names;
@@ -25,56 +32,75 @@ class StoreBuilder
*
* @var bool
*/
protected $shortCircuit;
private $shortCircuit;
/**
* The file encoding.
*
* @var string|null
*/
private $fileEncoding;
/**
* Create a new store builder instance.
*
* @param string[] $paths
* @param string[]|null $names
* @param bool $shortCircuit
* @param string[] $paths
* @param string[] $names
* @param bool $shortCircuit
* @param string|null $fileEncoding
*
* @return void
*/
private function __construct(array $paths = [], array $names = null, $shortCircuit = false)
private function __construct(array $paths = [], array $names = [], bool $shortCircuit = false, string $fileEncoding = null)
{
$this->paths = $paths;
$this->names = $names;
$this->shortCircuit = $shortCircuit;
$this->fileEncoding = $fileEncoding;
}
/**
* Create a new store builder instance.
* Create a new store builder instance with no names.
*
* @return \Dotenv\Store\StoreBuilder
*/
public static function create()
public static function createWithNoNames()
{
return new self();
}
/**
* Creates a store builder with the given paths.
*
* @param string|string[] $paths
* Create a new store builder instance with the default name.
*
* @return \Dotenv\Store\StoreBuilder
*/
public function withPaths($paths)
public static function createWithDefaultName()
{
return new self((array) $paths, $this->names, $this->shortCircuit);
return new self([], [self::DEFAULT_NAME]);
}
/**
* Creates a store builder with the given names.
* Creates a store builder with the given path added.
*
* @param string|string[]|null $names
* @param string $path
*
* @return \Dotenv\Store\StoreBuilder
*/
public function withNames($names = null)
public function addPath(string $path)
{
return new self($this->paths, $names === null ? null : (array) $names, $this->shortCircuit);
return new self(\array_merge($this->paths, [$path]), $this->names, $this->shortCircuit, $this->fileEncoding);
}
/**
* Creates a store builder with the given name added.
*
* @param string $name
*
* @return \Dotenv\Store\StoreBuilder
*/
public function addName(string $name)
{
return new self($this->paths, \array_merge($this->names, [$name]), $this->shortCircuit, $this->fileEncoding);
}
/**
@@ -84,7 +110,19 @@ class StoreBuilder
*/
public function shortCircuit()
{
return new self($this->paths, $this->names, true);
return new self($this->paths, $this->names, true, $this->fileEncoding);
}
/**
* Creates a store builder with the specified file encoding.
*
* @param string|null $fileEncoding
*
* @return \Dotenv\Store\StoreBuilder
*/
public function fileEncoding(string $fileEncoding = null)
{
return new self($this->paths, $this->names, $this->shortCircuit, $fileEncoding);
}
/**
@@ -95,8 +133,9 @@ class StoreBuilder
public function make()
{
return new FileStore(
Paths::filePaths($this->paths, $this->names === null ? ['.env'] : $this->names),
$this->shortCircuit
Paths::filePaths($this->paths, $this->names),
$this->shortCircuit,
$this->fileEncoding
);
}
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace Dotenv\Store;
interface StoreInterface
@@ -7,7 +9,7 @@ interface StoreInterface
/**
* Read the content of the environment file(s).
*
* @throws \Dotenv\Exception\InvalidPathException
* @throws \Dotenv\Exception\InvalidEncodingException|\Dotenv\Exception\InvalidPathException
*
* @return string
*/

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace Dotenv\Store;
final class StringStore implements StoreInterface
@@ -18,7 +20,7 @@ final class StringStore implements StoreInterface
*
* @return void
*/
public function __construct($content)
public function __construct(string $content)
{
$this->content = $content;
}

View File

@@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
namespace Dotenv\Util;
use GrahamCampbell\ResultType\Error;
use GrahamCampbell\ResultType\Success;
/**
* @internal
*/
final class Regex
{
/**
* This class is a singleton.
*
* @codeCoverageIgnore
*
* @return void
*/
private function __construct()
{
//
}
/**
* Perform a preg match, wrapping up the result.
*
* @param string $pattern
* @param string $subject
*
* @return \GrahamCampbell\ResultType\Result<bool,string>
*/
public static function matches(string $pattern, string $subject)
{
return self::pregAndWrap(static function (string $subject) use ($pattern) {
return @\preg_match($pattern, $subject) === 1;
}, $subject);
}
/**
* Perform a preg match all, wrapping up the result.
*
* @param string $pattern
* @param string $subject
*
* @return \GrahamCampbell\ResultType\Result<int,string>
*/
public static function occurrences(string $pattern, string $subject)
{
return self::pregAndWrap(static function (string $subject) use ($pattern) {
return (int) @\preg_match_all($pattern, $subject);
}, $subject);
}
/**
* Perform a preg replace callback, wrapping up the result.
*
* @param string $pattern
* @param callable $callback
* @param string $subject
* @param int|null $limit
*
* @return \GrahamCampbell\ResultType\Result<string,string>
*/
public static function replaceCallback(string $pattern, callable $callback, string $subject, int $limit = null)
{
return self::pregAndWrap(static function (string $subject) use ($pattern, $callback, $limit) {
return (string) @\preg_replace_callback($pattern, $callback, $subject, $limit ?? -1);
}, $subject);
}
/**
* Perform a preg split, wrapping up the result.
*
* @param string $pattern
* @param string $subject
*
* @return \GrahamCampbell\ResultType\Result<string[],string>
*/
public static function split(string $pattern, string $subject)
{
return self::pregAndWrap(static function (string $subject) use ($pattern) {
/** @var string[] */
return (array) @\preg_split($pattern, $subject);
}, $subject);
}
/**
* Perform a preg operation, wrapping up the result.
*
* @template V
*
* @param callable(string):V $operation
* @param string $subject
*
* @return \GrahamCampbell\ResultType\Result<V,string>
*/
private static function pregAndWrap(callable $operation, string $subject)
{
$result = $operation($subject);
if (\preg_last_error() !== \PREG_NO_ERROR) {
/** @var \GrahamCampbell\ResultType\Result<V,string> */
return Error::create(\preg_last_error_msg());
}
/** @var \GrahamCampbell\ResultType\Result<V,string> */
return Success::create($result);
}
}

View File

@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace Dotenv\Util;
use GrahamCampbell\ResultType\Error;
use GrahamCampbell\ResultType\Success;
use PhpOption\Option;
/**
* @internal
*/
final class Str
{
/**
* This class is a singleton.
*
* @codeCoverageIgnore
*
* @return void
*/
private function __construct()
{
//
}
/**
* Convert a string to UTF-8 from the given encoding.
*
* @param string $input
* @param string|null $encoding
*
* @return \GrahamCampbell\ResultType\Result<string,string>
*/
public static function utf8(string $input, string $encoding = null)
{
if ($encoding !== null && !\in_array($encoding, \mb_list_encodings(), true)) {
/** @var \GrahamCampbell\ResultType\Result<string,string> */
return Error::create(
\sprintf('Illegal character encoding [%s] specified.', $encoding)
);
}
$converted = $encoding === null ?
@\mb_convert_encoding($input, 'UTF-8') :
@\mb_convert_encoding($input, 'UTF-8', $encoding);
/**
* this is for support UTF-8 with BOM encoding
* @see https://en.wikipedia.org/wiki/Byte_order_mark
* @see https://github.com/vlucas/phpdotenv/issues/500
*/
if (\substr($converted, 0, 3) == "\xEF\xBB\xBF") {
$converted = \substr($converted, 3);
}
/** @var \GrahamCampbell\ResultType\Result<string,string> */
return Success::create($converted);
}
/**
* Search for a given substring of the input.
*
* @param string $haystack
* @param string $needle
*
* @return \PhpOption\Option<int>
*/
public static function pos(string $haystack, string $needle)
{
/** @var \PhpOption\Option<int> */
return Option::fromValue(\mb_strpos($haystack, $needle, 0, 'UTF-8'), false);
}
/**
* Grab the specified substring of the input.
*
* @param string $input
* @param int $start
* @param int|null $length
*
* @return string
*/
public static function substr(string $input, int $start, int $length = null)
{
return \mb_substr($input, $start, $length, 'UTF-8');
}
/**
* Compute the length of the given string.
*
* @param string $input
*
* @return int
*/
public static function len(string $input)
{
return \mb_strlen($input, 'UTF-8');
}
}

View File

@@ -1,10 +1,13 @@
<?php
declare(strict_types=1);
namespace Dotenv;
use Dotenv\Exception\ValidationException;
use Dotenv\Regex\Regex;
use Dotenv\Repository\RepositoryInterface;
use Dotenv\Util\Regex;
use Dotenv\Util\Str;
class Validator
{
@@ -13,39 +16,46 @@ class Validator
*
* @var \Dotenv\Repository\RepositoryInterface
*/
protected $repository;
private $repository;
/**
* The variables to validate.
*
* @var string[]
*/
protected $variables;
private $variables;
/**
* Create a new validator instance.
*
* @param \Dotenv\Repository\RepositoryInterface $repository
* @param string[] $variables
* @param bool $required
*
* @throws \Dotenv\Exception\ValidationException
*
* @return void
*/
public function __construct(RepositoryInterface $repository, array $variables, $required = true)
public function __construct(RepositoryInterface $repository, array $variables)
{
$this->repository = $repository;
$this->variables = $variables;
}
if ($required) {
$this->assertCallback(
function ($value) {
return $value !== null;
},
'is missing'
);
}
/**
* Assert that each variable is present.
*
* @throws \Dotenv\Exception\ValidationException
*
* @return \Dotenv\Validator
*/
public function required()
{
return $this->assert(
static function (?string $value) {
return $value !== null;
},
'is missing'
);
}
/**
@@ -57,13 +67,9 @@ class Validator
*/
public function notEmpty()
{
return $this->assertCallback(
function ($value) {
if ($value === null) {
return true;
}
return strlen(trim($value)) > 0;
return $this->assertNullable(
static function (string $value) {
return Str::len(\trim($value)) > 0;
},
'is empty'
);
@@ -78,13 +84,9 @@ class Validator
*/
public function isInteger()
{
return $this->assertCallback(
function ($value) {
if ($value === null) {
return true;
}
return ctype_digit($value);
return $this->assertNullable(
static function (string $value) {
return \ctype_digit($value);
},
'is not an integer'
);
@@ -99,17 +101,13 @@ class Validator
*/
public function isBoolean()
{
return $this->assertCallback(
function ($value) {
if ($value === null) {
return true;
}
return $this->assertNullable(
static function (string $value) {
if ($value === '') {
return false;
}
return filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) !== null;
return \filter_var($value, \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE) !== null;
},
'is not a boolean'
);
@@ -126,15 +124,11 @@ class Validator
*/
public function allowedValues(array $choices)
{
return $this->assertCallback(
function ($value) use ($choices) {
if ($value === null) {
return true;
}
return in_array($value, $choices, true);
return $this->assertNullable(
static function (string $value) use ($choices) {
return \in_array($value, $choices, true);
},
sprintf('is not one of [%s]', implode(', ', $choices))
\sprintf('is not one of [%s]', \implode(', ', $choices))
);
}
@@ -147,47 +141,69 @@ class Validator
*
* @return \Dotenv\Validator
*/
public function allowedRegexValues($regex)
public function allowedRegexValues(string $regex)
{
return $this->assertCallback(
function ($value) use ($regex) {
if ($value === null) {
return true;
}
return Regex::match($regex, $value)->success()->getOrElse(0) === 1;
return $this->assertNullable(
static function (string $value) use ($regex) {
return Regex::matches($regex, $value)->success()->getOrElse(false);
},
sprintf('does not match "%s"', $regex)
\sprintf('does not match "%s"', $regex)
);
}
/**
* Assert that the callback returns true for each variable.
*
* @param callable $callback
* @param string $message
* @param callable(?string):bool $callback
* @param string $message
*
* @throws \Dotenv\Exception\ValidationException
*
* @return \Dotenv\Validator
*/
protected function assertCallback(callable $callback, $message = 'failed callback assertion')
public function assert(callable $callback, string $message)
{
$failing = [];
foreach ($this->variables as $variable) {
if ($callback($this->repository->get($variable)) === false) {
$failing[] = sprintf('%s %s', $variable, $message);
$failing[] = \sprintf('%s %s', $variable, $message);
}
}
if (count($failing) > 0) {
throw new ValidationException(sprintf(
if (\count($failing) > 0) {
throw new ValidationException(\sprintf(
'One or more environment variables failed assertions: %s.',
implode(', ', $failing)
\implode(', ', $failing)
));
}
return $this;
}
/**
* Assert that the callback returns true for each variable.
*
* Skip checking null variable values.
*
* @param callable(string):bool $callback
* @param string $message
*
* @throws \Dotenv\Exception\ValidationException
*
* @return \Dotenv\Validator
*/
public function assertNullable(callable $callback, string $message)
{
return $this->assert(
static function (?string $value) use ($callback) {
if ($value === null) {
return true;
}
return $callback($value);
},
$message
);
}
}