轻量级解析.env文件的类库,轻量到只需要一个类文件,可用于生产环境 浏览次数:21 日期:2021-02-22 22:27:00 ### 背景 Laravel读取.env文件配置时,业务层里面访问一个配置项则Laravel底层会解析一次.env问题,那么Codeigniter4是这样的吗?最近有在读CodeIgniter4的源码,虽然现在还不是特别稳定,但是里面一些优秀的思想以及优秀的库还是值得学习的,比如其中的限流、异常界面实现、Kint调试利器等。今天再Codeigniter贴吧看到一个问答,是关于读取.env文件配置的问题,大致问题是: > Laravel读取.env文件配置时,业务层里面访问一个配置项则Laravel底层会解析一次.env问题,那么Codeigniter4是这样的吗? 处于好奇,并且最近在看CodeIgniter,于是就研究了下CodeIngiter解析.env文件的方式,自己又稍作改动,自动解析bool、null变量。 ### 代码 整个DotEnv.php文件内容如下 ```php path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file; } //-------------------------------------------------------------------- /** * The main entry point, will load the .env file and process it * so that we end up with all settings in the PHP environment vars * (i.e. getenv(), $_ENV, and $_SERVER) * * @return boolean */ public function load(): bool { $vars = $this->parse(); return ($vars === null ? false : true); } //-------------------------------------------------------------------- /** * get .env value by key name * * @return boolean|string|null */ public function getenv($name) { $value = $this->getVariable($name); switch (strtolower($value)) { case 'true': case '(true)': return true; case 'false': case '(false)': return false; case 'empty': case '(empty)': return ''; case 'null': case '(null)': return; } return $value; } //-------------------------------------------------------------------- /** * Parse the .env file into an array of key => value * * @return array|null */ protected function parse(): ?array { // We don't want to enforce the presence of a .env file, they should be optional. if (! is_file($this->path)) { return null; } // Ensure the file is readable if (! is_readable($this->path)) { throw new InvalidArgumentException("The .env file is not readable: {$this->path}"); } $vars = []; $lines = file($this->path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); foreach ($lines as $line) { // Is it a comment? if (strpos(trim($line), '#') === 0) { continue; } // If there is an equal sign, then we know we are assigning a variable. if (strpos($line, '=') !== false) { list($name, $value) = $this->normaliseVariable($line); $vars[$name] = $value; $this->setVariable($name, $value); } } return $vars; } //-------------------------------------------------------------------- /** * Sets the variable into the environment. Will parse the string * first to look for {name}={value} pattern, ensure that nested * variables are handled, and strip it of single and double quotes. * * @param string $name * @param string $value */ protected function setVariable(string $name, string $value = '') { if (! getenv($name, true)) { putenv("$name=$value"); } if (empty($_ENV[$name])) { $_ENV[$name] = $value; } if (empty($_SERVER[$name])) { $_SERVER[$name] = $value; } } //-------------------------------------------------------------------- /** * Parses for assignment, cleans the $name and $value, and ensures * that nested variables are handled. * * @param string $name * @param string $value * * @return array */ protected function normaliseVariable(string $name, string $value = ''): array { // Split our compound string into its parts. if (strpos($name, '=') !== false) { list($name, $value) = explode('=', $name, 2); } $name = trim($name); $value = trim($value); // Sanitize the name $name = str_replace(['export', '\'', '"'], '', $name); // Sanitize the value $value = $this->sanitizeValue($value); $value = $this->resolveNestedVariables($value); return [ $name, $value, ]; } //-------------------------------------------------------------------- /** * Strips quotes from the environment variable value. * * This was borrowed from the excellent phpdotenv with very few changes. * https://github.com/vlucas/phpdotenv * * @param string $value * * @return string * @throws InvalidArgumentException */ protected function sanitizeValue(string $value): string { if (! $value) { return $value; } // Does it begin with a quote? 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 = trim($parts[0]); // Unquoted values cannot contain whitespace if (preg_match('/\s+/', $value) > 0) { throw new InvalidArgumentException('.env values containing spaces must be surrounded by quotes.'); } } return $value; } //-------------------------------------------------------------------- /** * Resolve the nested variables. * * Look for ${varname} patterns in the variable value and replace with an existing * environment variable. * * This was borrowed from the excellent phpdotenv with very few changes. * https://github.com/vlucas/phpdotenv * * @param string $value * * @return string */ protected function resolveNestedVariables(string $value): string { if (strpos($value, '$') !== false) { $value = preg_replace_callback( '/\${([a-zA-Z0-9_]+)}/', function ($matchedPatterns) { $nestedVariable = $this->getVariable($matchedPatterns[1]); if (is_null($nestedVariable)) { return $matchedPatterns[0]; } return $nestedVariable; }, $value ); } return $value; } //-------------------------------------------------------------------- /** * Search the different places for environment variables and return first value found. * * This was borrowed from the excellent phpdotenv with very few changes. * https://github.com/vlucas/phpdotenv * * @param string $name * * @return string|null */ protected function getVariable(string $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); // switch getenv default to null return $value === false ? null : $value; } } //-------------------------------------------------------------------- } ``` .env文件内容如下 ```shell # app配置 APP_DEBUG = False APP_URL=http://localhost APP_NAME = "json 博客" #值有空格等特殊字符,用引号括起来 #数据库配置 DB_HOST=localhost #数据库名,这是注释 DB_PORT=3306 DB_DATABASE=demo DB_USERNAME=root DB_PASSWORD=root DB_DSN = "mysql://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}/${DB_DATABASE}" #redis配置 REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 REDIS_PREFIX= #这是注释 ``` ### 使用方式 ```php require_once './DotEnv.php'; $env = new DotEnv('./');//参数是.env文件所在目录 $env->load(); var_dump($env->getenv("APP_NAME")); var_dump($env->getenv("APP_DEBUG"));//自动解析bool结果true var_dump($env->getenv("DB_DSN"));//支持嵌套变量 var_dump($env->getenv("REDIS_PASSWORD"));//自动解析null字符串为null值 ``` ### 输出结果 ```shell string(11) "json 博客" bool(false) string(32) "mysql://root:root@localhost/demo" NULL ``` ### 注意 - 如果值里面有空格需要用单引号、双引号引用起来 - 支持值嵌套,用${xx}表示变量 - 以#开头的行是注释,不会解析 - 行内支持注释,#后面的不会解析为value - False、false、FALSE解析成false布尔值 - True、true、TRUE解析成true布尔值 - null字符串解析成null类型值 最后更新时间为: 7天前 (2021-02-22 22:27:00)