From 468d49996720a0c84c05fb56379c63522eda3418 Mon Sep 17 00:00:00 2001 From: Arman <407448+armanist@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:52:16 +0400 Subject: [PATCH 1/6] [#709] Treat an empty .env value as not set in env_int() and env_bool() Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + src/Environment/Traits/ValueTrait.php | 12 +++++++-- tests/Unit/Environment/EnvironmentTest.php | 27 ++++++++++++++++--- .../Environment/Helpers/EnvHelperTest.php | 11 ++++++-- 4 files changed, 44 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fef3b51..be9a9d7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,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) +- `env_bool()` and `env_int()` (`Environment::getBool()` and `getInt()`) treat an empty `.env` value 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 (#709) ## [3.1.2] - 2026-11-19 diff --git a/src/Environment/Traits/ValueTrait.php b/src/Environment/Traits/ValueTrait.php index 5fc3b1c0..e7abe238 100644 --- a/src/Environment/Traits/ValueTrait.php +++ b/src/Environment/Traits/ValueTrait.php @@ -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 value gives the default * @throws EnvException */ public function getBool(string $key, bool $default = false): bool { $value = $this->getValue($key, $default); + if ($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 value gives the default * @throws EnvException */ public function getInt(string $key, int $default = 0): int { $value = $this->getValue($key, $default); + if ($value === '') { + return $default; + } + if (is_int($value)) { return $value; } diff --git a/tests/Unit/Environment/EnvironmentTest.php b/tests/Unit/Environment/EnvironmentTest.php index 2d8afc58..e3283024 100644 --- a/tests/Unit/Environment/EnvironmentTest.php +++ b/tests/Unit/Environment/EnvironmentTest.php @@ -103,7 +103,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 +112,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 +151,21 @@ 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 testEnvironmentGetValueKeepsTheEmptyValue(): void + { + $this->setEnvValues(['REDIS_PORT' => '']); + + $this->assertSame('', $this->env->getValue('REDIS_PORT', 'default')); + } + #[DataProvider('invalidIntProvider')] public function testEnvironmentGetIntThrowsForInvalidNumber(string $value): void { @@ -163,7 +185,6 @@ public static function invalidIntProvider(): array return [ 'text' => ['abc'], 'decimal' => ['1.5'], - 'empty' => [''], ]; } 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 From 62e0475df4f137317d2d6bba109a82b45068bd65 Mon Sep 17 00:00:00 2001 From: Arman <407448+armanist@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:58:21 +0400 Subject: [PATCH 2/6] [#709] Split Environment into loading, ReadTrait and WriteTrait Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + src/Environment/Environment.php | 58 +++++++++++++++++-- .../Traits/{ValueTrait.php => ReadTrait.php} | 4 +- .../{EnvFileTrait.php => WriteTrait.php} | 54 +---------------- tests/Unit/Environment/EnvironmentTest.php | 21 +++++++ 5 files changed, 79 insertions(+), 59 deletions(-) rename src/Environment/Traits/{ValueTrait.php => ReadTrait.php} (98%) rename src/Environment/Traits/{EnvFileTrait.php => WriteTrait.php} (52%) diff --git a/CHANGELOG.md b/CHANGELOG.md index be9a9d7d..a9764343 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ 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 `getEnvFilePath()` and `getEnvFileName()`, which `WriteTrait` calls, as `Environment` does (#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) 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/ValueTrait.php b/src/Environment/Traits/ReadTrait.php similarity index 98% rename from src/Environment/Traits/ValueTrait.php rename to src/Environment/Traits/ReadTrait.php index e7abe238..8fa61994 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 diff --git a/src/Environment/Traits/EnvFileTrait.php b/src/Environment/Traits/WriteTrait.php similarity index 52% rename from src/Environment/Traits/EnvFileTrait.php rename to src/Environment/Traits/WriteTrait.php index 1093135e..4fb4b732 100644 --- a/src/Environment/Traits/EnvFileTrait.php +++ b/src/Environment/Traits/WriteTrait.php @@ -12,19 +12,15 @@ use Quantum\Environment\Exceptions\EnvException; use Quantum\Config\Exceptions\ConfigException; -use Dotenv\Exception\InvalidFileException; use Quantum\App\Exceptions\BaseException; use Quantum\Di\Exceptions\DiException; -use Quantum\Environment\Enums\Env; use ReflectionException; -use Quantum\App\App; -use Dotenv\Dotenv; /** - * Trait EnvFileTrait + * Trait WriteTrait * @package Quantum\Environment */ -trait EnvFileTrait +trait WriteTrait { /** * Creates or updates the row in .env @@ -59,50 +55,4 @@ public function updateRow(string $key, ?string $value): void $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/tests/Unit/Environment/EnvironmentTest.php b/tests/Unit/Environment/EnvironmentTest.php index e3283024..e5b0d6ac 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,23 @@ 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); + } + + $this->assertTrue((new ReflectionClass(WriteTrait::class))->hasMethod('updateRow')); + $this->assertFalse((new ReflectionClass(ReadTrait::class))->hasMethod('updateRow')); + } + public function testEnvironmentGetAppEnv(): void { $this->assertEquals('testing', $this->env->getAppEnv()); From bd05b8c95de65ccd7f83bc6e48f3e6a9a996ec1f Mon Sep 17 00:00:00 2001 From: Arman <407448+armanist@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:04:57 +0400 Subject: [PATCH 3/6] [#709] Treat a null .env value as not set and declare what WriteTrait needs Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +-- src/Environment/Traits/ReadTrait.php | 8 ++--- src/Environment/Traits/WriteTrait.php | 4 +++ tests/Unit/Environment/EnvironmentTest.php | 36 ++++++++++++++++++++-- 4 files changed, 44 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a9764343..59330915 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,7 +26,7 @@ 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 `getEnvFilePath()` and `getEnvFileName()`, which `WriteTrait` calls, as `Environment` does (#709) +- **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) ### 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) @@ -37,7 +37,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) -- `env_bool()` and `env_int()` (`Environment::getBool()` and `getInt()`) treat an empty `.env` value 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 (#709) +- `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 (#709) ## [3.1.2] - 2026-11-19 diff --git a/src/Environment/Traits/ReadTrait.php b/src/Environment/Traits/ReadTrait.php index 8fa61994..19ac7540 100644 --- a/src/Environment/Traits/ReadTrait.php +++ b/src/Environment/Traits/ReadTrait.php @@ -36,14 +36,14 @@ public function getValue(string $key, mixed $default = null): mixed } /** - * Gets the environment variable value as a boolean; an empty value gives the default + * 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 === '') { + if ($value === null || $value === '') { return $default; } @@ -55,14 +55,14 @@ public function getBool(string $key, bool $default = false): bool } /** - * Gets the environment variable value as an integer; an empty value gives the default + * 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 === '') { + if ($value === null || $value === '') { return $default; } diff --git a/src/Environment/Traits/WriteTrait.php b/src/Environment/Traits/WriteTrait.php index 4fb4b732..be4e1073 100644 --- a/src/Environment/Traits/WriteTrait.php +++ b/src/Environment/Traits/WriteTrait.php @@ -22,6 +22,10 @@ */ trait WriteTrait { + abstract private function getEnvFilePath(): string; + + abstract private function getEnvFileName(string $appEnv): string; + /** * Creates or updates the row in .env * @throws EnvException|ConfigException|DiException|BaseException|ReflectionException diff --git a/tests/Unit/Environment/EnvironmentTest.php b/tests/Unit/Environment/EnvironmentTest.php index e5b0d6ac..a33a2f94 100644 --- a/tests/Unit/Environment/EnvironmentTest.php +++ b/tests/Unit/Environment/EnvironmentTest.php @@ -43,7 +43,11 @@ public function testEnvironmentKeepsLoadingReadingAndWritingApart(): void $this->assertSame(Environment::class, $class->getMethod($method)->getDeclaringClass()->getName(), $method); } - $this->assertTrue((new ReflectionClass(WriteTrait::class))->hasMethod('updateRow')); + $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')); } @@ -180,6 +184,34 @@ public function testEnvironmentGetIntUsesDefaultForEmptyValue(): void $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' => '']); @@ -330,7 +362,7 @@ public function testEnvironmentUpdateRowThrowsWhenEnvFileCannotBeRead(): void } /** - * @param array $values + * @param array $values */ private function setEnvValues(array $values): void { From a2b0d631d3630bc1ec2a700952533fc28cc82c83 Mon Sep 17 00:00:00 2001 From: Arman <407448+armanist@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:40:32 +0400 Subject: [PATCH 4/6] [#709] Find the .env row as it is written in updateRow() and write the value as given Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- src/Environment/Traits/WriteTrait.php | 31 +++++++- tests/Unit/Environment/EnvironmentTest.php | 82 ++++++++++++++++++++++ 3 files changed, 112 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59330915..e4456119 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ The format is based on Keep a Changelog. - **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) @@ -37,7 +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) -- `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 (#709) +- `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/src/Environment/Traits/WriteTrait.php b/src/Environment/Traits/WriteTrait.php index be4e1073..a15df874 100644 --- a/src/Environment/Traits/WriteTrait.php +++ b/src/Environment/Traits/WriteTrait.php @@ -49,14 +49,39 @@ public function updateRow(string $key, ?string $value): void throw EnvException::fileNotFound($this->getEnvFileName($this->appEnv)); } - $pattern = '/^' . preg_quote($key . '=' . $this->envContent[$key], '/') . '/m'; - $envFileContent = preg_replace($pattern, $key . '=' . $value, $envFileContent); + $envFileContent = preg_replace_callback( + $this->rowPattern($key, $this->envContent[$key]), + static fn (): string => $key . '=' . $value, + $envFileContent + ); - fs()->put($envFilePath, (string) $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. + * 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 a33a2f94..b04bfb08 100644 --- a/tests/Unit/Environment/EnvironmentTest.php +++ b/tests/Unit/Environment/EnvironmentTest.php @@ -344,6 +344,88 @@ 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 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'); From 5fe6a364b50030a52b168fa2d3f442a269d97426 Mon Sep 17 00:00:00 2001 From: Arman <407448+armanist@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:52:47 +0400 Subject: [PATCH 5/6] Replace DeclareStrictTypesRector, removed in Rector 2.9, with SafeDeclareStrictTypesRector Co-Authored-By: Claude Opus 5.5 --- rector.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) 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/*', + ], ]); From 3fdd5735d555d7925d8bb494cd9681d4310115f7 Mon Sep 17 00:00:00 2001 From: Arman <407448+armanist@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:04:43 +0400 Subject: [PATCH 6/6] [#709] Find a row that updateRow() wrote with a null value Co-Authored-By: Claude Opus 5.5 --- src/Environment/Traits/WriteTrait.php | 5 +++-- tests/Unit/Environment/EnvironmentTest.php | 23 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/Environment/Traits/WriteTrait.php b/src/Environment/Traits/WriteTrait.php index a15df874..61a4c879 100644 --- a/src/Environment/Traits/WriteTrait.php +++ b/src/Environment/Traits/WriteTrait.php @@ -68,7 +68,8 @@ public function updateRow(string $key, ?string $value): void } /** - * Matches the key and its value as they are written in .env: quoted, unquoted or without a 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 @@ -77,7 +78,7 @@ private function rowPattern(string $key, mixed $value): string $endOfValue = '(?=[ \t]*(?:#|\r?$))'; if (!is_string($value)) { - return '/^' . $key . $endOfValue . '/m'; + return '/^' . $key . '=?' . $endOfValue . '/m'; } $value = preg_quote($value, '/'); diff --git a/tests/Unit/Environment/EnvironmentTest.php b/tests/Unit/Environment/EnvironmentTest.php index b04bfb08..46b3beb8 100644 --- a/tests/Unit/Environment/EnvironmentTest.php +++ b/tests/Unit/Environment/EnvironmentTest.php @@ -401,6 +401,29 @@ public static function updateRowProvider(): array ]; } + 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';