Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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

Expand Down
7 changes: 5 additions & 2 deletions rector.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -17,8 +17,11 @@
SetList::TYPE_DECLARATION,
])
->withRules([
DeclareStrictTypesRector::class,
SafeDeclareStrictTypesRector::class,
])
->withSkip([
ClassPropertyAssignToConstructorPromotionRector::class,
SafeDeclareStrictTypesRector::class => [
__DIR__ . '/src/*/Helpers/*',
],
]);
58 changes: 53 additions & 5 deletions src/Environment/Environment.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -28,8 +30,8 @@
class Environment implements EnvironmentInterface
{
use AppEnvTrait;
use ValueTrait;
use EnvFileTrait;
use ReadTrait;
use WriteTrait;

private bool $isMutable = false;

Expand Down Expand Up @@ -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<string, mixed>
* @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" : '');
}
}
108 changes: 0 additions & 108 deletions src/Environment/Traits/EnvFileTrait.php

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
}
Expand All @@ -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;
}
Expand Down
88 changes: 88 additions & 0 deletions src/Environment/Traits/WriteTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

declare(strict_types=1);

/**
* Quantum PHP Framework
* An open-source software development framework for PHP
* @link https://quantumphp.io
*/

namespace Quantum\Environment\Traits;

use Quantum\Environment\Exceptions\EnvException;
use Quantum\Config\Exceptions\ConfigException;
use Quantum\App\Exceptions\BaseException;
use Quantum\Di\Exceptions\DiException;
use ReflectionException;

/**
* Trait WriteTrait
* @package Quantum\Environment
*/
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
*/
public function updateRow(string $key, ?string $value): void
{
if (!$this->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';
}
}
Loading
Loading