diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fef3b51..e4456119 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,8 @@ The format is based on Keep a Changelog. - **BREAKING:** `getBool()` and `getInt()`, on `Config` and on `ConfigSection`, require the key when they are called without a default: a missing or `null` key throws `ConfigException::missingKey()` ("The config key `x` is missing."). They returned `false` and `0`. Empty text, such as `KEY=` in `.env`, counts as not set: with a default, the default is used. Before, `getInt()` threw for empty text and `getBool()` returned `false`. Pass the default when the key is optional, such as `config()->getBool('app.debug', false)`; the framework's own optional reads do (#672) - **BREAKING:** The traits of `Quantum\Config\Config` are split by what they do: the new `ReadTrait` has `get()`, `has()`, `all()` and `section()` and is shared with `ConfigSection`; `ValueTrait` is renamed `WriteTrait` and keeps `set()`, `delete()` and `flush()`; `ConfigFileTrait` is removed, and its code (`import()`, `importIfExists()` and the file lookup) is part of `Config` again, since loading files is what `Config` is for and no other class used it. A class of your own that uses `Quantum\Config\Traits\ValueTrait` must use both new traits, and one that uses `ConfigFileTrait` must extend or use `Config`. `Config` itself is unchanged for callers (#672) - **BREAKING:** The cache adapters (`FileAdapter`, `DatabaseAdapter`, `RedisAdapter`, `MemcachedAdapter`), the rate limit adapters (`FileRateLimitAdapter`, `RedisRateLimitAdapter`), the mailer adapters (`SmtpAdapter`, `MailgunAdapter`, `MandrillAdapter`, `ResendAdapter`, `SendgridAdapter`, `SendinblueAdapter`), the captcha adapters (`RecaptchaAdapter`, `HcaptchaAdapter`), the file log adapters (`SingleAdapter`, `DailyAdapter`), the renderer adapters (`HtmlAdapter`, `TwigAdapter`), the session adapters (`NativeSessionAdapter`, `DatabaseSessionAdapter`), the lang adapters (`Quantum\Lang\Adapters\FileAdapter`, `DeepLAdapter`, `GoogleTranslateAdapter`, as their second argument) and the auth adapters (`SessionAuthAdapter`, `JwtAuthAdapter`, as their last argument, with the whole `auth` config) take a `Quantum\Config\ConfigSection` instead of an array, and their factories pass `config()->section(...)`. Code that builds an adapter itself must wrap its array: `new RedisAdapter(new ConfigSection([...]))`. The renderer and session adapters can still be built without an argument; passing `null` is no longer accepted. The auth adapters require their config again: since 3.0.0 it was optional, so an auth adapter built without one ran with two-factor authentication off without an error; now leaving it out fails with an `ArgumentCountError`. A log adapter of your own that uses `LoggerTrait` must declare `initialize(ConfigSection $config)` instead of `initialize(array $params)`. The session `timeout` is read as a whole number, so `'1800'` works and a missing or `null` `timeout` or `table` keeps its default. The remote lang adapters read `cache.enabled` and `use_source_catalog` with the rules of `getBool()`, as before, and `cache.ttl` as a whole number: an unset `ttl` still uses the cache's default, and one that is not a whole number throws a `ConfigException`; it became `0`, so translations were silently not cached. The auth adapters read `two_fa` with the rules of `getBool()`, as before, and `otp_expires` and `session.remember_lifetime` as whole numbers, keeping their defaults (2 minutes and 30 days) when missing. The three settings are read when the adapter is built, so text that is not a whole number throws a `ConfigException` there, even while two-factor authentication is off, and before a sign-in changes anything. Before, an `otp_expires` such as `'abc'` failed with PHP's "Unknown or bad format", and a `remember_lifetime` such as `'abc'` became `0`, a remember cookie that expired at once. The SMTP `port` is read as a whole number like the cache ports: `'587'` works and `'abc'` throws a `ConfigException`; it was handed to PHPMailer as it was. A missing or empty SMTP `port`, such as `MAIL_PORT=` in the `.env` of a project created before 3.1.2, uses 25, PHPMailer's default. The `ttl` and the `port` may be given as text, such as `'600'` from an environment variable; the `ttl` failed with a `TypeError`. A `port` that is not a whole number, such as `'abc'`, throws a `ConfigException`; it became `0`, which Redis and Memcached read as their default port, so a typo connected to the default server without an error. A missing `ttl`, or a missing cache or rate limit `port`, throws a `ConfigException` that names the key (#672) +- **BREAKING:** `Environment` loads the `.env` file itself, reads through `Quantum\Environment\Traits\ReadTrait` (renamed from `ValueTrait`) and writes through the new `WriteTrait` (`updateRow()`). `EnvFileTrait` is removed: its loading methods are private methods of `Environment` now. `Environment`'s public methods and `EnvironmentInterface` are unchanged. A class of your own that uses `ValueTrait` or `EnvFileTrait` must switch to `ReadTrait` and `WriteTrait`, and declare what they use, as `Environment` does: the properties `$loaded`, `$envContent`, `$isMutable` and `$appEnv`, and the methods `getEnvFilePath()` and `getEnvFileName()`, which `WriteTrait` declares abstract (#709) +- **BREAKING:** `env_bool()` and `env_int()` (`Environment::getBool()` and `getInt()`) treat an empty `.env` value (`KEY=`, or a `KEY` line without `=`) as not set and return the default: with `TWO_FA=`, `env_bool('TWO_FA', true)` gives `true` (it gave `false`), and with `REDIS_PORT=`, `env_int('REDIS_PORT', 6379)` gives `6379` (it threw `EnvException`). Without a default they give `false` and `0`, as for a variable that is missing. A value that is not a whole number, such as `abc`, still makes `env_int()` throw, and `env()` still returns the empty string. An empty value that was meant to switch a setting off whose default is on, such as `TWO_FA=` with `env_bool('TWO_FA', true)` in the auth config of the `DemoWeb` and `DemoApi` templates, now leaves it on: write `TWO_FA=false` (#709) ### Fixed - The storage adapters no longer raise PHP warnings where they return `false`: `LocalFileSystemAdapter::listDirectory()` returns `false` for a folder that does not exist without calling `scandir()`, `DropboxFileSystemAdapter::put()` returns `false` when the response has no `size`, and `DropboxFileSystemAdapter::isFile()` and `GoogleDriveFileSystemAdapter::isFile()` return `false` when the metadata lacks `.tag`, `kind` or `mimeType` (#687) @@ -36,6 +38,7 @@ The format is based on Keep a Changelog. - Dropbox refreshes the access token only for a 401 without a body or with an error tagged `invalid_access_token` or `expired_access_token`. It refreshed for every 401 with an error tag, such as `no_account` or a missing permission, and an error body that was plain text raised a `TypeError`. Any other 401 now throws the adapter's `Exception` (#694) - The `Exception` of a failed Dropbox or Google Drive request carries a plain text error body as it is, and the HTTP client's error when the response has no body; a text body was JSON encoded, and an error body that was plain text raised a `TypeError` in the check for an expired access token (#694) - `config()->set()` with a dotted key on an empty config, such as `set('cache.redis', [...])`, nests the value as it does on a config that has values; it stored the literal key `cache.redis`, so `get('cache.redis.port')` returned `null` (#672) +- `Environment::updateRow()` finds the line of the key as the `.env` file has it: a quoted value (`APP_NAME="My App"`, `APP_NAME='My App'`, and a double-quoted value over several lines), an empty one (`APP_NAME=""`) and a `KEY` line without `=` are replaced now; they were left unchanged in the file, and `APP_NAME=""` became `APP_NAME=new""`. A comment after the value stays. The value is written as it is given: a `$` or `\` in it, such as `$1` or `\0`, was read by `preg_replace()` as a reference to the match and changed the written value. A line that cannot be found as it was read, such as `export KEY=value` or a value with `\"` in it, is still left unchanged. When the replacement fails, `updateRow()` throws `EnvException::fileNotFound()`, as it does when the file cannot be read, and keeps the file; it wrote an empty `.env` (#709) ## [3.1.2] - 2026-11-19 diff --git a/rector.php b/rector.php index 209af50d..86fd6a2d 100644 --- a/rector.php +++ b/rector.php @@ -2,7 +2,7 @@ declare(strict_types=1); -use Rector\TypeDeclaration\Rector\StmtsAwareInterface\DeclareStrictTypesRector; +use Rector\TypeDeclaration\Rector\StmtsAwareInterface\SafeDeclareStrictTypesRector; use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector; use Rector\Set\ValueObject\LevelSetList; use Rector\Set\ValueObject\SetList; @@ -17,8 +17,11 @@ SetList::TYPE_DECLARATION, ]) ->withRules([ - DeclareStrictTypesRector::class, + SafeDeclareStrictTypesRector::class, ]) ->withSkip([ ClassPropertyAssignToConstructorPromotionRector::class, + SafeDeclareStrictTypesRector::class => [ + __DIR__ . '/src/*/Helpers/*', + ], ]); diff --git a/src/Environment/Environment.php b/src/Environment/Environment.php index 753caf69..5e99f5ee 100644 --- a/src/Environment/Environment.php +++ b/src/Environment/Environment.php @@ -12,13 +12,15 @@ use Quantum\Environment\Contracts\EnvironmentInterface; use Quantum\Environment\Exceptions\EnvException; -use Quantum\Environment\Traits\EnvFileTrait; -use Dotenv\Exception\InvalidFileException; use Quantum\Environment\Traits\AppEnvTrait; -use Quantum\Environment\Traits\ValueTrait; +use Dotenv\Exception\InvalidFileException; +use Quantum\Environment\Traits\WriteTrait; +use Quantum\Environment\Traits\ReadTrait; use Quantum\App\Exceptions\BaseException; use Quantum\Di\Exceptions\DiException; use Quantum\Environment\Enums\Env; +use Quantum\App\App; +use Dotenv\Dotenv; /** * Class Environment @@ -28,8 +30,8 @@ class Environment implements EnvironmentInterface { use AppEnvTrait; - use ValueTrait; - use EnvFileTrait; + use ReadTrait; + use WriteTrait; private bool $isMutable = false; @@ -66,4 +68,50 @@ public function load(): void $this->envContent = $envContent; $this->loaded = true; } + + /** + * @return array{string, string} + * @throws BaseException + */ + private function resolveEnvironmentFile(): array + { + $baseDir = App::getBaseDir(); + + $filePath = $baseDir . DS . 'shared' . DS . 'config' . DS . 'env.php'; + + if (!file_exists($filePath)) { + throw EnvException::fileNotFound($filePath); + } + + $envConfig = require $filePath; + $appEnv = $envConfig['app_env'] ?? Env::PRODUCTION; + $envFile = $this->getEnvFileName($appEnv); + + if (!file_exists($baseDir . DS . $envFile)) { + throw EnvException::fileNotFound($envFile); + } + + return [$appEnv, $envFile]; + } + + /** + * @return array + * @throws InvalidFileException + */ + private function loadDotenvFile(string $envFile): array + { + $loadedVars = Dotenv::createArrayBacked(App::getBaseDir(), $envFile)->load(); + + return is_array($loadedVars) ? $loadedVars : []; + } + + private function getEnvFilePath(): string + { + return App::getBaseDir() . DS . $this->getEnvFileName($this->appEnv); + } + + private function getEnvFileName(string $appEnv): string + { + return '.env' . ($appEnv !== Env::PRODUCTION ? ".$appEnv" : ''); + } } diff --git a/src/Environment/Traits/EnvFileTrait.php b/src/Environment/Traits/EnvFileTrait.php deleted file mode 100644 index 1093135e..00000000 --- a/src/Environment/Traits/EnvFileTrait.php +++ /dev/null @@ -1,108 +0,0 @@ -isMutable) { - throw EnvException::environmentImmutable(); - } - - if (!$this->loaded) { - throw EnvException::environmentNotLoaded(); - } - - $envFilePath = $this->getEnvFilePath(); - - if (array_key_exists($key, $this->envContent)) { - $envFileContent = fs()->get($envFilePath); - - if (!is_string($envFileContent)) { - throw EnvException::fileNotFound($this->getEnvFileName($this->appEnv)); - } - - $pattern = '/^' . preg_quote($key . '=' . $this->envContent[$key], '/') . '/m'; - $envFileContent = preg_replace($pattern, $key . '=' . $value, $envFileContent); - - fs()->put($envFilePath, (string) $envFileContent); - } else { - fs()->append($envFilePath, PHP_EOL . $key . '=' . $value . PHP_EOL); - } - - $this->envContent[$key] = $value; - } - - /** - * @return array{string, string} - * @throws BaseException - */ - private function resolveEnvironmentFile(): array - { - $baseDir = App::getBaseDir(); - - $filePath = $baseDir . DS . 'shared' . DS . 'config' . DS . 'env.php'; - - if (!file_exists($filePath)) { - throw EnvException::fileNotFound($filePath); - } - - $envConfig = require $filePath; - $appEnv = $envConfig['app_env'] ?? Env::PRODUCTION; - $envFile = $this->getEnvFileName($appEnv); - - if (!file_exists($baseDir . DS . $envFile)) { - throw EnvException::fileNotFound($envFile); - } - - return [$appEnv, $envFile]; - } - - /** - * @return array - * @throws InvalidFileException - */ - private function loadDotenvFile(string $envFile): array - { - $loadedVars = Dotenv::createArrayBacked(App::getBaseDir(), $envFile)->load(); - - return is_array($loadedVars) ? $loadedVars : []; - } - - private function getEnvFilePath(): string - { - return App::getBaseDir() . DS . $this->getEnvFileName($this->appEnv); - } - - private function getEnvFileName(string $appEnv): string - { - return '.env' . ($appEnv !== Env::PRODUCTION ? ".$appEnv" : ''); - } -} diff --git a/src/Environment/Traits/ValueTrait.php b/src/Environment/Traits/ReadTrait.php similarity index 82% rename from src/Environment/Traits/ValueTrait.php rename to src/Environment/Traits/ReadTrait.php index 5fc3b1c0..19ac7540 100644 --- a/src/Environment/Traits/ValueTrait.php +++ b/src/Environment/Traits/ReadTrait.php @@ -13,10 +13,10 @@ use Quantum\Environment\Exceptions\EnvException; /** - * Trait ValueTrait + * Trait ReadTrait * @package Quantum\Environment */ -trait ValueTrait +trait ReadTrait { /** * Gets the environment variable value @@ -36,13 +36,17 @@ public function getValue(string $key, mixed $default = null): mixed } /** - * Gets the environment variable value as a boolean + * Gets the environment variable value as a boolean; an empty or null value gives the default * @throws EnvException */ public function getBool(string $key, bool $default = false): bool { $value = $this->getValue($key, $default); + if ($value === null || $value === '') { + return $default; + } + if (is_bool($value)) { return $value; } @@ -51,13 +55,17 @@ public function getBool(string $key, bool $default = false): bool } /** - * Gets the environment variable value as an integer + * Gets the environment variable value as an integer; an empty or null value gives the default * @throws EnvException */ public function getInt(string $key, int $default = 0): int { $value = $this->getValue($key, $default); + if ($value === null || $value === '') { + return $default; + } + if (is_int($value)) { return $value; } diff --git a/src/Environment/Traits/WriteTrait.php b/src/Environment/Traits/WriteTrait.php new file mode 100644 index 00000000..61a4c879 --- /dev/null +++ b/src/Environment/Traits/WriteTrait.php @@ -0,0 +1,88 @@ +isMutable) { + throw EnvException::environmentImmutable(); + } + + if (!$this->loaded) { + throw EnvException::environmentNotLoaded(); + } + + $envFilePath = $this->getEnvFilePath(); + + if (array_key_exists($key, $this->envContent)) { + $envFileContent = fs()->get($envFilePath); + + if (!is_string($envFileContent)) { + throw EnvException::fileNotFound($this->getEnvFileName($this->appEnv)); + } + + $envFileContent = preg_replace_callback( + $this->rowPattern($key, $this->envContent[$key]), + static fn (): string => $key . '=' . $value, + $envFileContent + ); + + if ($envFileContent === null) { + throw EnvException::fileNotFound($this->getEnvFileName($this->appEnv)); + } + + fs()->put($envFilePath, $envFileContent); + } else { + fs()->append($envFilePath, PHP_EOL . $key . '=' . $value . PHP_EOL); + } + + $this->envContent[$key] = $value; + } + + /** + * Matches the key and its value as they are written in .env: quoted, unquoted or without a value + * (`KEY`, or `KEY=` as updateRow() writes a null value). + * A comment after the value is not part of the match. + */ + private function rowPattern(string $key, mixed $value): string + { + $key = preg_quote($key, '/'); + $endOfValue = '(?=[ \t]*(?:#|\r?$))'; + + if (!is_string($value)) { + return '/^' . $key . '=?' . $endOfValue . '/m'; + } + + $value = preg_quote($value, '/'); + + return '/^(?:' . $key . '="' . $value . '"|' . $key . "='" . $value . "'|" . $key . '=' . $value . $endOfValue . ')/m'; + } +} diff --git a/tests/Unit/Environment/EnvironmentTest.php b/tests/Unit/Environment/EnvironmentTest.php index 2d8afc58..46b3beb8 100644 --- a/tests/Unit/Environment/EnvironmentTest.php +++ b/tests/Unit/Environment/EnvironmentTest.php @@ -5,9 +5,13 @@ use Quantum\Environment\Contracts\EnvironmentInterface; use Quantum\Environment\Exceptions\EnvException; use PHPUnit\Framework\Attributes\DataProvider; +use Quantum\Environment\Traits\AppEnvTrait; +use Quantum\Environment\Traits\WriteTrait; +use Quantum\Environment\Traits\ReadTrait; use Quantum\Environment\Environment; use Quantum\Tests\Unit\AppTestCase; use Quantum\App\AppContext; +use ReflectionClass; use Quantum\App\App; class EnvironmentTest extends AppTestCase @@ -26,6 +30,27 @@ public function testEnvironmentImplementsEnvironmentInterface(): void $this->assertInstanceOf(EnvironmentInterface::class, $this->env); } + public function testEnvironmentKeepsLoadingReadingAndWritingApart(): void + { + $this->assertSame( + [AppEnvTrait::class, ReadTrait::class, WriteTrait::class], + array_values(class_uses(Environment::class)) + ); + + $class = new ReflectionClass(Environment::class); + + foreach (['load', 'resolveEnvironmentFile', 'loadDotenvFile', 'getEnvFilePath', 'getEnvFileName'] as $method) { + $this->assertSame(Environment::class, $class->getMethod($method)->getDeclaringClass()->getName(), $method); + } + + $writeTrait = new ReflectionClass(WriteTrait::class); + + $this->assertTrue($writeTrait->hasMethod('updateRow')); + $this->assertTrue($writeTrait->getMethod('getEnvFilePath')->isAbstract()); + $this->assertTrue($writeTrait->getMethod('getEnvFileName')->isAbstract()); + $this->assertFalse((new ReflectionClass(ReadTrait::class))->hasMethod('updateRow')); + } + public function testEnvironmentGetAppEnv(): void { $this->assertEquals('testing', $this->env->getAppEnv()); @@ -103,7 +128,6 @@ public function testEnvironmentGetBool(): void 'FLAG_YES' => 'yes', 'FLAG_FALSE' => 'false', 'FLAG_ZERO' => '0', - 'FLAG_EMPTY' => '', 'FLAG_OFF' => 'off', 'FLAG_NO' => 'no', 'FLAG_UNKNOWN' => 'maybe', @@ -113,11 +137,19 @@ public function testEnvironmentGetBool(): void $this->assertTrue($this->env->getBool($key), $key); } - foreach (['FLAG_FALSE', 'FLAG_ZERO', 'FLAG_EMPTY', 'FLAG_OFF', 'FLAG_NO', 'FLAG_UNKNOWN'] as $key) { + foreach (['FLAG_FALSE', 'FLAG_ZERO', 'FLAG_OFF', 'FLAG_NO', 'FLAG_UNKNOWN'] as $key) { $this->assertFalse($this->env->getBool($key, true), $key); } } + public function testEnvironmentGetBoolUsesDefaultForEmptyValue(): void + { + $this->setEnvValues(['FLAG_EMPTY' => '']); + + $this->assertTrue($this->env->getBool('FLAG_EMPTY', true)); + $this->assertFalse($this->env->getBool('FLAG_EMPTY')); + } + public function testEnvironmentGetBoolUsesDefaultForMissingKey(): void { $this->assertFalse($this->env->getBool('NON_EXISTING_KEY')); @@ -144,6 +176,49 @@ public function testEnvironmentGetIntUsesDefaultForMissingKey(): void $this->assertSame(25, $this->env->getInt('NON_EXISTING_KEY', 25)); } + public function testEnvironmentGetIntUsesDefaultForEmptyValue(): void + { + $this->setEnvValues(['REDIS_PORT' => '']); + + $this->assertSame(6379, $this->env->getInt('REDIS_PORT', 6379)); + $this->assertSame(0, $this->env->getInt('REDIS_PORT')); + } + + public function testEnvironmentGetBoolAndGetIntUseDefaultForNullValue(): void + { + $this->setEnvValues(['REDIS_PORT' => null, 'TWO_FA' => null]); + + $this->assertSame(6379, $this->env->getInt('REDIS_PORT', 6379)); + $this->assertSame(0, $this->env->getInt('REDIS_PORT')); + $this->assertTrue($this->env->getBool('TWO_FA', true)); + $this->assertFalse($this->env->getBool('TWO_FA')); + } + + public function testEnvironmentGetIntUsesDefaultForKeyWithoutValueInEnvFile(): void + { + $envFilePath = App::getBaseDir() . DS . '.env.testing'; + $originalContent = $this->fs->get($envFilePath); + + try { + $this->fs->append($envFilePath, PHP_EOL . 'REDIS_PORT' . PHP_EOL); + + $this->setPrivateProperty($this->env, 'loaded', false); + $this->env->load(); + + $this->assertNull($this->env->getValue('REDIS_PORT')); + $this->assertSame(6379, $this->env->getInt('REDIS_PORT', 6379)); + } finally { + $this->fs->put($envFilePath, $originalContent); + } + } + + public function testEnvironmentGetValueKeepsTheEmptyValue(): void + { + $this->setEnvValues(['REDIS_PORT' => '']); + + $this->assertSame('', $this->env->getValue('REDIS_PORT', 'default')); + } + #[DataProvider('invalidIntProvider')] public function testEnvironmentGetIntThrowsForInvalidNumber(string $value): void { @@ -163,7 +238,6 @@ public static function invalidIntProvider(): array return [ 'text' => ['abc'], 'decimal' => ['1.5'], - 'empty' => [''], ]; } @@ -270,6 +344,111 @@ public function testEnvironmentUpdateRowThrowsWhenNotLoaded(): void (new Environment())->setMutable(true)->updateRow('SOMETHING', 'Something'); } + /** + * @param array $expectedRows + */ + #[DataProvider('updateRowProvider')] + public function testEnvironmentUpdateRowUpdatesTheRow(string $row, string $key, string $value, array $expectedRows, string $valueAfterReload): void + { + $envFilePath = App::getBaseDir() . DS . '.env.testing'; + $originalContent = $this->fs->get($envFilePath); + + try { + $this->fs->append($envFilePath, PHP_EOL . $row . PHP_EOL . 'OTHER_KEY=other' . PHP_EOL); + + $this->setPrivateProperty($this->env, 'loaded', false); + $this->env->load(); + + $this->env->updateRow($key, $value); + + $this->assertSame($value, $this->env->getValue($key)); + + $lines = preg_split('/\R/', (string) $this->fs->get($envFilePath)); + + foreach ($expectedRows as $expected) { + $this->assertContains($expected, $lines); + } + + $this->assertContains('OTHER_KEY=other', $lines); + $this->assertCount(1, preg_grep('/^' . preg_quote($key, '/') . '\b/', $lines)); + + $this->setPrivateProperty($this->env, 'loaded', false); + $this->env->load(); + + $this->assertSame($valueAfterReload, $this->env->getValue($key)); + $this->assertSame('other', $this->env->getValue('OTHER_KEY')); + } finally { + $this->fs->put($envFilePath, $originalContent); + } + } + + /** + * @return array, string}> + */ + public static function updateRowProvider(): array + { + return [ + 'plain value' => ['MAIL_HOST=localhost', 'MAIL_HOST', 'smtp.test', ['MAIL_HOST=smtp.test'], 'smtp.test'], + 'value with comment' => ['MAIL_HOST=localhost # local only', 'MAIL_HOST', 'smtp.test', ['MAIL_HOST=smtp.test # local only'], 'smtp.test'], + 'value with hash' => ['MAIL_HOST=localhost#local', 'MAIL_HOST', 'smtp.test', ['MAIL_HOST=smtp.test#local'], 'smtp.test'], + 'empty value' => ['APP_NAME=', 'APP_NAME', 'Quantum', ['APP_NAME=Quantum'], 'Quantum'], + 'quoted value' => ['APP_NAME="My App"', 'APP_NAME', 'Quantum', ['APP_NAME=Quantum'], 'Quantum'], + 'single quoted value' => ["APP_NAME='My App'", 'APP_NAME', 'Quantum', ['APP_NAME=Quantum'], 'Quantum'], + 'empty quoted value' => ['APP_NAME=""', 'APP_NAME', 'Quantum', ['APP_NAME=Quantum'], 'Quantum'], + 'key without value' => ['FEATURE_X', 'FEATURE_X', 'on', ['FEATURE_X=on'], 'on'], + 'multi-line value' => ["PRIVATE_KEY=\"-----BEGIN\nabc\n-----END\"", 'PRIVATE_KEY', 'x', ['PRIVATE_KEY=x'], 'x'], 'value with dollar and backslash' => ['BASIC_AUTH_PWD=old', 'BASIC_AUTH_PWD', 'pa$1ss\0', ['BASIC_AUTH_PWD=pa$1ss\0'], 'pa$1ss\0'], + 'escaped quote is left as it is' => ['APP_NAME="Say \"hi\""', 'APP_NAME', 'Quantum', ['APP_NAME="Say \"hi\""'], 'Say "hi"'], + ]; + } + + public function testEnvironmentUpdateRowUpdatesARowItWroteWithoutAValue(): void + { + $envFilePath = App::getBaseDir() . DS . '.env.testing'; + $originalContent = $this->fs->get($envFilePath); + + try { + $this->env->updateRow('FEATURE_X', null); + $this->env->updateRow('FEATURE_X', 'on'); + + $lines = preg_split('/\R/', (string) $this->fs->get($envFilePath)); + + $this->assertContains('FEATURE_X=on', $lines); + $this->assertCount(1, preg_grep('/^FEATURE_X\b/', $lines)); + + $this->setPrivateProperty($this->env, 'loaded', false); + $this->env->load(); + + $this->assertSame('on', $this->env->getValue('FEATURE_X')); + } finally { + $this->fs->put($envFilePath, $originalContent); + } + } + + public function testEnvironmentUpdateRowKeepsTheFileWhenTheRowCannotBeReplaced(): void + { + $envFilePath = App::getBaseDir() . DS . '.env.testing'; + $originalContent = $this->fs->get($envFilePath); + $jit = ini_get('pcre.jit'); + $backtrackLimit = ini_get('pcre.backtrack_limit'); + + try { + ini_set('pcre.jit', '0'); + ini_set('pcre.backtrack_limit', '1'); + + $this->expectException(EnvException::class); + + $this->env->updateRow('APP_KEY', 'Something'); + } finally { + ini_set('pcre.jit', (string) $jit); + ini_set('pcre.backtrack_limit', (string) $backtrackLimit); + + $contentAfter = $this->fs->get($envFilePath); + $this->fs->put($envFilePath, $originalContent); + + $this->assertSame($originalContent, $contentAfter); + } + } + public function testEnvironmentUpdateRowThrowsWhenEnvFileCannotBeRead(): void { $this->setPrivateProperty($this->env, 'appEnv', 'missing'); @@ -288,7 +467,7 @@ public function testEnvironmentUpdateRowThrowsWhenEnvFileCannotBeRead(): void } /** - * @param array $values + * @param array $values */ private function setEnvValues(array $values): void { diff --git a/tests/Unit/Environment/Helpers/EnvHelperTest.php b/tests/Unit/Environment/Helpers/EnvHelperTest.php index e78a9eca..5e6a1e04 100644 --- a/tests/Unit/Environment/Helpers/EnvHelperTest.php +++ b/tests/Unit/Environment/Helpers/EnvHelperTest.php @@ -35,13 +35,20 @@ public function testGetEnvValueWithDefault(): void public function testEnvBoolConvertsTextToBoolean(): void { - $this->setEnvValues(['FLAG_FALSE' => 'false', 'FLAG_ZERO' => '0', 'FLAG_EMPTY' => '', 'FLAG_TRUE' => 'true']); + $this->setEnvValues(['FLAG_FALSE' => 'false', 'FLAG_ZERO' => '0', 'FLAG_TRUE' => 'true']); $this->assertTrue(env_bool('DEBUG')); $this->assertTrue(env_bool('FLAG_TRUE')); $this->assertFalse(env_bool('FLAG_FALSE', true)); $this->assertFalse(env_bool('FLAG_ZERO', true)); - $this->assertFalse(env_bool('FLAG_EMPTY', true)); + } + + public function testEnvBoolAndEnvIntUseTheDefaultForAnEmptyValue(): void + { + $this->setEnvValues(['TWO_FA' => '', 'REDIS_PORT' => '']); + + $this->assertTrue(env_bool('TWO_FA', true)); + $this->assertSame(6379, env_int('REDIS_PORT', 6379)); } public function testEnvBoolUsesDefaultForMissingKey(): void