update v 1.0.7.5

This commit is contained in:
Sujit Prasad
2016-06-13 20:41:55 +05:30
parent aa9786d829
commit 283d97e3ea
5078 changed files with 339851 additions and 175995 deletions

View File

@@ -1,199 +0,0 @@
PHP dotenv
==========
Loads environment variables from `.env` to `getenv()`, `$_ENV` and
`$_SERVER` automagically.
This is a PHP version of the original [Ruby
dotenv](https://github.com/bkeepers/dotenv).
[![Build
Status](https://secure.travis-ci.org/vlucas/phpdotenv.png)](http://travis-ci.org/vlucas/phpdotenv)
Why .env?
---------
**You should never store sensitive credentials in your code**. Storing
[configuration in the environment](http://www.12factor.net/config) is one of
the tenets of a [twelve-factor app](http://www.12factor.net/). Anything that is
likely to change between deployment environments such as database credentials
or credentials for 3rd party services should be extracted from the
code into environment variables.
Basically, a `.env` file is an easy way to load custom configuration
variables that your application needs without having to modify .htaccess
files or Apache/nginx virtual hosts. This means you won't have to edit
any files outside the project, and all the environment variables are
always set no matter how you run your project - Apache, Nginx, CLI, and
even PHP 5.4's built-in webserver. It's WAY easier than all the other
ways you know of to set environment variables, and you're going to love
it.
* NO editing virtual hosts in Apache or Nginx
* NO adding `php_value` flags to .htaccess files
* EASY portability and sharing of required ENV values
* COMPATIBLE with PHP's built-in web server and CLI runner
Installation with Composer
--------------------------
```shell
curl -s http://getcomposer.org/installer | php
php composer.phar require vlucas/phpdotenv
```
Usage
-----
The `.env` file is generally kept out of version control since it can contain
sensitive API keys and passwords. A separate `.env.example` file is created
with all the required environment variables defined except for the sensitive
ones, which are either user-supplied for their own development environments or
are communicated elsewhere to project collaborators. The project collaborators
then independently copy the `.env.example` file to a local `.env` and ensure
all the settings are correct for their local environment, filling in the secret
keys or providing their own values when necessary. In this usage, the `.env`
file should be added to the project's `.gitignore` file so that it will never
be committed by collaborators. This usage ensures that no sensitive passwords
or API keys will ever be in the version control history so there is less risk
of a security breach, and production values will never have to be shared with
all project collaborators.
Add your application configuration to a `.env` file in the root of your
project. **Make sure the `.env` file is added to your `.gitignore` so it is not
checked-in the code**
```shell
S3_BUCKET=dotenv
SECRET_KEY=souper_seekret_key
```
Now create a file named `.env.example` and check this into the project. This
should have the ENV variables you need to have set, but the values should
either be blank or filled with dummy data. The idea is to let people know what
variables are required, but not give them the sensitive production values.
```shell
S3_BUCKET=devbucket
SECRET_KEY=abc123
```
You can then load `.env` in your application with a single line:
```php
Dotenv::load(__DIR__);
```
All of the defined variables are now accessible with the `getenv`
method, and are available in the `$_ENV` and `$_SERVER` super-globals.
```php
$s3_bucket = getenv('S3_BUCKET');
$s3_bucket = $_ENV['S3_BUCKET'];
$s3_bucket = $_SERVER['S3_BUCKET'];
```
You should also be able to access them using your framework's Request
class (if you are using a framework).
```php
$s3_bucket = $request->env('S3_BUCKET');
$s3_bucket = $request->getEnv('S3_BUCKET');
$s3_bucket = $request->server->get('S3_BUCKET');
```
### Nesting Variables
It's possible to nest an environment variable within another, useful to cut down on repetition.
This is done by wrapping an existing environment variable in `{$…}` e.g.
```shell
BASE_DIR=/var/webroot/project-root
CACHE_DIR={$BASE_DIR}/cache
TMP_DIR={$BASE_DIR}/tmp
```
### Immutability
By default, Dotenv treats environment variables as immutable, that is… once set they cannot be changed.
You can make Dotenv mutable using
```php
Dotenv::makeMutable();
```
… and you can make Dotenv immutable again using
```php
Dotenv::makeImmutable();
```
Requiring Variables to be Set
-----------------------------
Using Dotenv, you can require specific ENV vars to be defined, and throw
an Exception if they are not. This is particularly useful to let people know
any explicit required variables that your app will not work without.
You can use a single string:
```php
Dotenv::required('DATABASE_DSN');
```
Or an array of strings:
```php
Dotenv::required(array('DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS'));
```
If any ENV vars are missing, Dotenv will throw a `RuntimeException` like this:
```
Required environment variable missing or value not allowed: 'DB_USER', 'DB_PASS'
```
### Allowed values
As you may have noticed from the Exception message above, it's also possible to define a set of values that your
environment variable should adhere to.
```php
Dotenv::required('SESSION_STORE', array('Filesystem', 'Memcached'));
```
Again, if the environment variable wasn't in this list, you'd get a similar Exception:
```
Required environment variable missing or value not allowed: 'SESSION_STORE'
```
### Comments
You can comment your `.env` file using the `#` character. E.g.
```shell
# this is a comment
VAR="value" # comment
VAR=value # comment
```
Usage Notes
-----------
When a new developer clones your codebase, they will have an additional
**one-time step** to manually copy the `.env.example` file to `.env` and fill-in
their own values (or get any sensitive values from a project co-worker).
phpdotenv is made for development environments, and generally should not be
used in production. In production, the actual environment variables should be
set so that there is no overhead of loading the `.env` file on each request.
This can be achieved via an automated deployment process with tools like
Vagrant, chef, or Puppet, or can be set manually with cloud hosts like
Pagodabox and Heroku.
Contributing
------------
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Make your changes
4. Run the tests, adding new ones for your own code if necessary (`phpunit`)
5. Commit your changes (`git commit -am 'Added some feature'`)
6. Push to the branch (`git push origin my-new-feature`)
7. Create new Pull Request

View File

@@ -1,10 +1,8 @@
{
"name": "vlucas/phpdotenv",
"type": "library",
"description": "Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.",
"keywords": ["env", "dotenv", "environment"],
"homepage": "http://github.com/vlucas/phpdotenv",
"license" : "BSD",
"license" : "BSD-3-Clause-Attribution",
"authors" : [
{
"name": "Vance Lucas",
@@ -13,14 +11,19 @@
}
],
"require": {
"php": ">=5.3.2"
"php": ">=5.3.9"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
"phpunit/phpunit": "^4.8 || ^5.0"
},
"autoload": {
"psr-0": {
"Dotenv": "src/"
"psr-4": {
"Dotenv\\": "src/"
}
},
"extra": {
"branch-alias": {
"dev-master": "2.2-dev"
}
}
}

View File

@@ -1,307 +1,95 @@
<?php
namespace Dotenv;
/**
* Dotenv.
* This is the dotenv class.
*
* Loads a `.env` file in the given directory and sets the environment vars.
* It's responsible for loading a `.env` file in the given directory and
* setting the environment vars.
*/
class Dotenv
{
/**
* If true, then environment variables will not be overwritten.
* The file path.
*
* @var bool
* @var string
*/
protected static $immutable = true;
protected $filePath;
/**
* Load `.env` file in given directory.
* The loader instance.
*
* @var \Dotenv\Loader|null
*/
protected $loader;
/**
* Create a new dotenv instance.
*
* @param string $path
* @param string $file
*
* @return void
*/
public static function load($path, $file = '.env')
public function __construct($path, $file = '.env')
{
$this->filePath = $this->getFilePath($path, $file);
$this->loader = new Loader($this->filePath, true);
}
/**
* Load `.env` file in given directory.
*
* @return array
*/
public function load()
{
$this->loader = new Loader($this->filePath, true);
return $this->loader->load();
}
/**
* Load `.env` file in given directory.
*
* @return array
*/
public function overload()
{
$this->loader = new Loader($this->filePath, false);
return $this->loader->load();
}
/**
* Returns the full path to the file.
*
* @param string $path
* @param string $file
*
* @return string
*/
protected function getFilePath($path, $file)
{
if (!is_string($file)) {
$file = '.env';
}
$filePath = rtrim($path, '/').'/'.$file;
if (!is_readable($filePath) || !is_file($filePath)) {
throw new \InvalidArgumentException(
sprintf(
'Dotenv: Environment file %s not found or not readable. '.
'Create file with your environment settings at %s',
$file,
$filePath
)
);
}
$filePath = rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file;
// Read file into an array of lines with auto-detected line endings
$autodetect = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', '1');
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
ini_set('auto_detect_line_endings', $autodetect);
foreach ($lines as $line) {
// Disregard comments
if (strpos(trim($line), '#') === 0) {
continue;
}
// Only use non-empty lines that look like setters
if (strpos($line, '=') !== false) {
static::setEnvironmentVariable($line);
}
}
return $filePath;
}
/**
* Set a variable.
* Required ensures that the specified variables exist, and returns a new Validator object.
*
* Variable set using:
* - putenv
* - $_ENV
* - $_SERVER.
* @param string|string[] $variable
*
* The environment variable value is stripped of single and double quotes.
*
* @param string $name
* @param string|null $value
*
* @return void
* @return \Dotenv\Validator
*/
public static function setEnvironmentVariable($name, $value = null)
public function required($variable)
{
list($name, $value) = static::normaliseEnvironmentVariable($name, $value);
// Don't overwrite existing environment variables if we're immutable
// Ruby's dotenv does this with `ENV[key] ||= value`.
if (static::$immutable === true && !is_null(static::findEnvironmentVariable($name))) {
return;
}
putenv("$name=$value");
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
/**
* Require specified ENV vars to be present, or throw an exception.
*
* You can also pass through an set of allowed values for the environment variable.
*
* @param mixed $environmentVariables
* @param string[] $allowedValues
*
* @throws \RuntimeException
*
* @return true
*/
public static function required($environmentVariables, array $allowedValues = array())
{
$environmentVariables = (array) $environmentVariables;
$missingEnvironmentVariables = array();
foreach ($environmentVariables as $environmentVariable) {
$value = static::findEnvironmentVariable($environmentVariable);
if (is_null($value)) {
$missingEnvironmentVariables[] = $environmentVariable;
} elseif ($allowedValues) {
if (!in_array($value, $allowedValues)) {
// may differentiate in the future, but for now this does the job
$missingEnvironmentVariables[] = $environmentVariable;
}
}
}
if ($missingEnvironmentVariables) {
throw new \RuntimeException(
sprintf(
"Required environment variable missing, or value not allowed: '%s'",
implode("', '", $missingEnvironmentVariables)
)
);
}
return true;
}
/**
* Takes value as passed in by developer.
*
* We're also:
* - ensuring we're dealing with a separate name and value, breaking apart the name string if needed
* - cleaning the value of quotes
* - cleaning the name of quotes
* - resolving nested variables
*
* @param string $name
* @param string $value
*
* @return array
*/
protected static function normaliseEnvironmentVariable($name, $value)
{
list($name, $value) = static::splitCompoundStringIntoParts($name, $value);
$name = static::sanitiseVariableName($name);
$value = static::sanitiseVariableValue($value);
$value = static::resolveNestedVariables($value);
return array($name, $value);
}
/**
* If the $name contains an = sign, then we split it into 2 parts, a name & value.
*
* @param string $name
* @param string $value
*
* @return array
*/
protected static function splitCompoundStringIntoParts($name, $value)
{
if (strpos($name, '=') !== false) {
list($name, $value) = array_map('trim', explode('=', $name, 2));
}
return array($name, $value);
}
/**
* Strips quotes from the environment variable value.
*
* @param string $value
*
* @return string
*/
protected static function sanitiseVariableValue($value)
{
$value = trim($value);
if (!$value) {
return '';
}
if (strpbrk($value[0], '"\'') !== false) { // value starts with a quote
$quote = $value[0];
$regexPattern = sprintf('/^
%1$s # match a quote at the start of the value
( # capturing sub-pattern used
(?: # we do not need to capture this
[^%1$s\\\\] # any character other than a quote or backslash
|\\\\\\\\ # or two backslashes together
|\\\\%1$s # or an escaped quote e.g \"
)* # as many characters that match the previous rules
) # end of the capturing sub-pattern
%1$s # and the closing quote
.*$ # and discard any string after the closing quote
/mx', $quote);
$value = preg_replace($regexPattern, '$1', $value);
$value = str_replace("\\$quote", $quote, $value);
$value = str_replace('\\\\', '\\', $value);
} else {
$parts = explode(' #', $value, 2);
$value = $parts[0];
}
return trim($value);
}
/**
* Strips quotes and the optional leading "export " from the environment variable name.
*
* @param string $name
*
* @return string
*/
protected static function sanitiseVariableName($name)
{
return trim(str_replace(array('export ', '\'', '"'), '', $name));
}
/**
* Look for {$varname} patterns in the variable value.
*
* Replace with an existing environment variable.
*
* @param string $value
*
* @return mixed
*/
protected static function resolveNestedVariables($value)
{
if (strpos($value, '$') !== false) {
$value = preg_replace_callback(
'/{\$([a-zA-Z0-9_]+)}/',
function ($matchedPatterns) {
$nestedVariable = Dotenv::findEnvironmentVariable($matchedPatterns[1]);
if (is_null($nestedVariable)) {
return $matchedPatterns[0];
} else {
return $nestedVariable;
}
},
$value
);
}
return $value;
}
/**
* Search the different places for environment variables and return first value found.
*
* @param string $name
*
* @return string
*/
public static function findEnvironmentVariable($name)
{
switch (true) {
case array_key_exists($name, $_ENV):
return $_ENV[$name];
case array_key_exists($name, $_SERVER):
return $_SERVER[$name];
default:
$value = getenv($name);
return $value === false ? null : $value; // switch getenv default to null
}
}
/**
* Check Dotenv immutable status.
*
* Returns true if immutable, false if mutable.
*
* @return bool
*/
public static function isImmutable()
{
return static::$immutable;
}
/**
* Make Dotenv immutable.
*
* This means that once set, an environment variable cannot be overridden.
*
* @return void
*/
public static function makeImmutable()
{
static::$immutable = true;
}
/**
* Make Dotenv mutable.
*
* Environment variables will act as, well, variables.
*
* @return void
*/
public static function makeMutable()
{
static::$immutable = false;
return new Validator((array) $variable, $this->loader);
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace Dotenv\Exception;
/**
* This is the exception interface.
*/
interface ExceptionInterface
{
//
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Dotenv\Exception;
use InvalidArgumentException;
/**
* This is the invalid callback exception class.
*/
class InvalidCallbackException extends InvalidArgumentException implements ExceptionInterface
{
//
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Dotenv\Exception;
use InvalidArgumentException;
/**
* This is the invalid file exception class.
*/
class InvalidFileException extends InvalidArgumentException implements ExceptionInterface
{
//
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Dotenv\Exception;
use InvalidArgumentException;
/**
* This is the invalid path exception class.
*/
class InvalidPathException extends InvalidArgumentException implements ExceptionInterface
{
//
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Dotenv\Exception;
use RuntimeException;
/**
* This is the validation exception class.
*/
class ValidationException extends RuntimeException implements ExceptionInterface
{
//
}

371
vendor/vlucas/phpdotenv/src/Loader.php vendored Normal file
View File

@@ -0,0 +1,371 @@
<?php
namespace Dotenv;
use Dotenv\Exception\InvalidFileException;
use Dotenv\Exception\InvalidPathException;
/**
* This is the loaded class.
*
* It's responsible for loading variables by reading a file from disk and:
* - stripping comments beginning with a `#`,
* - parsing lines that look shell variable setters, e.g `export key = value`, `key="value"`.
*/
class Loader
{
/**
* The file path.
*
* @var string
*/
protected $filePath;
/**
* Are we immutable?
*
* @var bool
*/
protected $immutable;
/**
* Create a new loader instance.
*
* @param string $filePath
* @param bool $immutable
*
* @return void
*/
public function __construct($filePath, $immutable = false)
{
$this->filePath = $filePath;
$this->immutable = $immutable;
}
/**
* Load `.env` file in given directory.
*
* @return array
*/
public function load()
{
$this->ensureFileIsReadable();
$filePath = $this->filePath;
$lines = $this->readLinesFromFile($filePath);
foreach ($lines as $line) {
if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
$this->setEnvironmentVariable($line);
}
}
return $lines;
}
/**
* Ensures the given filePath is readable.
*
* @throws \Dotenv\Exception\InvalidPathException
*
* @return void
*/
protected function ensureFileIsReadable()
{
if (!is_readable($this->filePath) || !is_file($this->filePath)) {
throw new InvalidPathException(sprintf('Unable to read the environment file at %s.', $this->filePath));
}
}
/**
* Normalise the given environment variable.
*
* Takes value as passed in by developer and:
* - ensures we're dealing with a separate name and value, breaking apart the name string if needed,
* - cleaning the value of quotes,
* - cleaning the name of quotes,
* - resolving nested variables.
*
* @param string $name
* @param string $value
*
* @return array
*/
protected function normaliseEnvironmentVariable($name, $value)
{
list($name, $value) = $this->splitCompoundStringIntoParts($name, $value);
list($name, $value) = $this->sanitiseVariableName($name, $value);
list($name, $value) = $this->sanitiseVariableValue($name, $value);
$value = $this->resolveNestedVariables($value);
return array($name, $value);
}
/**
* Process the runtime filters.
*
* Called from the `VariableFactory`, passed as a callback in `$this->loadFromFile()`.
*
* @param string $name
* @param string $value
*
* @return array
*/
public function processFilters($name, $value)
{
list($name, $value) = $this->splitCompoundStringIntoParts($name, $value);
list($name, $value) = $this->sanitiseVariableName($name, $value);
list($name, $value) = $this->sanitiseVariableValue($name, $value);
return array($name, $value);
}
/**
* Read lines from the file, auto detecting line endings.
*
* @param string $filePath
*
* @return array
*/
protected function readLinesFromFile($filePath)
{
// Read file into an array of lines with auto-detected line endings
$autodetect = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', '1');
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
ini_set('auto_detect_line_endings', $autodetect);
return $lines;
}
/**
* Determine if the line in the file is a comment, e.g. begins with a #.
*
* @param string $line
*
* @return bool
*/
protected function isComment($line)
{
return strpos(trim($line), '#') === 0;
}
/**
* Determine if the given line looks like it's setting a variable.
*
* @param string $line
*
* @return bool
*/
protected function looksLikeSetter($line)
{
return strpos($line, '=') !== false;
}
/**
* Split the compound string into parts.
*
* If the `$name` contains an `=` sign, then we split it into 2 parts, a `name` & `value`
* disregarding the `$value` passed in.
*
* @param string $name
* @param string $value
*
* @return array
*/
protected function splitCompoundStringIntoParts($name, $value)
{
if (strpos($name, '=') !== false) {
list($name, $value) = array_map('trim', explode('=', $name, 2));
}
return array($name, $value);
}
/**
* Strips quotes from the environment variable value.
*
* @param string $name
* @param string $value
*
* @throws \Dotenv\Exception\InvalidFileException
*
* @return array
*/
protected function sanitiseVariableValue($name, $value)
{
$value = trim($value);
if (!$value) {
return array($name, $value);
}
if ($this->beginsWithAQuote($value)) { // value starts with a quote
$quote = $value[0];
$regexPattern = sprintf(
'/^
%1$s # match a quote at the start of the value
( # capturing sub-pattern used
(?: # we do not need to capture this
[^%1$s\\\\] # any character other than a quote or backslash
|\\\\\\\\ # or two backslashes together
|\\\\%1$s # or an escaped quote e.g \"
)* # as many characters that match the previous rules
) # end of the capturing sub-pattern
%1$s # and the closing quote
.*$ # and discard any string after the closing quote
/mx',
$quote
);
$value = preg_replace($regexPattern, '$1', $value);
$value = str_replace("\\$quote", $quote, $value);
$value = str_replace('\\\\', '\\', $value);
} else {
$parts = explode(' #', $value, 2);
$value = trim($parts[0]);
// Unquoted values cannot contain whitespace
if (preg_match('/\s+/', $value) > 0) {
throw new InvalidFileException('Dotenv values containing spaces must be surrounded by quotes.');
}
}
return array($name, trim($value));
}
/**
* Resolve the nested variables.
*
* Look for {$varname} patterns in the variable value and replace with an existing
* environment variable.
*
* @param string $value
*
* @return mixed
*/
protected function resolveNestedVariables($value)
{
if (strpos($value, '$') !== false) {
$loader = $this;
$value = preg_replace_callback(
'/\${([a-zA-Z0-9_]+)}/',
function ($matchedPatterns) use ($loader) {
$nestedVariable = $loader->getEnvironmentVariable($matchedPatterns[1]);
if ($nestedVariable === null) {
return $matchedPatterns[0];
} else {
return $nestedVariable;
}
},
$value
);
}
return $value;
}
/**
* Strips quotes and the optional leading "export " from the environment variable name.
*
* @param string $name
* @param string $value
*
* @return array
*/
protected function sanitiseVariableName($name, $value)
{
$name = trim(str_replace(array('export ', '\'', '"'), '', $name));
return array($name, $value);
}
/**
* Determine if the given string begins with a quote.
*
* @param string $value
*
* @return bool
*/
protected function beginsWithAQuote($value)
{
return strpbrk($value[0], '"\'') !== false;
}
/**
* Search the different places for environment variables and return first value found.
*
* @param string $name
*
* @return string
*/
public function getEnvironmentVariable($name)
{
switch (true) {
case array_key_exists($name, $_ENV):
return $_ENV[$name];
case array_key_exists($name, $_SERVER):
return $_SERVER[$name];
default:
$value = getenv($name);
return $value === false ? null : $value; // switch getenv default to null
}
}
/**
* Set an environment variable.
*
* This is done using:
* - putenv,
* - $_ENV,
* - $_SERVER.
*
* The environment variable value is stripped of single and double quotes.
*
* @param string $name
* @param string|null $value
*
* @return void
*/
public function setEnvironmentVariable($name, $value = null)
{
list($name, $value) = $this->normaliseEnvironmentVariable($name, $value);
// Don't overwrite existing environment variables if we're immutable
// Ruby's dotenv does this with `ENV[key] ||= value`.
if ($this->immutable && $this->getEnvironmentVariable($name) !== null) {
return;
}
putenv("$name=$value");
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
/**
* Clear an environment variable.
*
* This is not (currently) used by Dotenv but is provided as a utility
* method for 3rd party code.
*
* This is done using:
* - putenv,
* - unset($_ENV, $_SERVER).
*
* @param string $name
*
* @see setEnvironmentVariable()
*
* @return void
*/
public function clearEnvironmentVariable($name)
{
// Don't clear anything if we're immutable.
if ($this->immutable) {
return;
}
putenv($name);
unset($_ENV[$name], $_SERVER[$name]);
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace Dotenv;
use Dotenv\Exception\InvalidCallbackException;
use Dotenv\Exception\ValidationException;
/**
* This is the validator class.
*
* It's responsible for applying validations against a number of variables.
*/
class Validator
{
/**
* The variables to validate.
*
* @var array
*/
protected $variables;
/**
* The loader instance.
*
* @var \Dotenv\Loader
*/
protected $loader;
/**
* Create a new validator instance.
*
* @param array $variables
* @param \Dotenv\Loader $loader
*
* @return void
*/
public function __construct(array $variables, Loader $loader)
{
$this->variables = $variables;
$this->loader = $loader;
$this->assertCallback(
function ($value) {
return $value !== null;
},
'is missing'
);
}
/**
* Assert that each variable is not empty.
*
* @return \Dotenv\Validator
*/
public function notEmpty()
{
return $this->assertCallback(
function ($value) {
return strlen(trim($value)) > 0;
},
'is empty'
);
}
/**
* Assert that each specified variable is an integer.
*
* @return \Dotenv\Validator
*/
public function isInteger()
{
return $this->assertCallback(
function ($value) {
return ctype_digit($value);
},
'is not an integer'
);
}
/**
* Assert that each variable is amongst the given choices.
*
* @param string[] $choices
*
* @return \Dotenv\Validator
*/
public function allowedValues(array $choices)
{
return $this->assertCallback(
function ($value) use ($choices) {
return in_array($value, $choices);
},
'is not an allowed value'
);
}
/**
* Assert that the callback returns true for each variable.
*
* @param callable $callback
* @param string $message
*
* @throws \Dotenv\Exception\InvalidCallbackException|\Dotenv\Exception\ValidationException
*
* @return \Dotenv\Validator
*/
protected function assertCallback($callback, $message = 'failed callback assertion')
{
if (!is_callable($callback)) {
throw new InvalidCallbackException('The provided callback must be callable.');
}
$variablesFailingAssertion = array();
foreach ($this->variables as $variableName) {
$variableValue = $this->loader->getEnvironmentVariable($variableName);
if (call_user_func($callback, $variableValue) === false) {
$variablesFailingAssertion[] = $variableName." $message";
}
}
if (count($variablesFailingAssertion) > 0) {
throw new ValidationException(sprintf(
'One or more environment variables failed assertions: %s.',
implode(', ', $variablesFailingAssertion)
));
}
return $this;
}
}