Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ The format is based on Keep a Changelog.

## [Unreleased]

### Added
- `Quantum\Config\ConfigSection`, a read-only slice of the config, and `Config::section($key)`, which returns it: `config()->section('cache.redis')`. A section has `get()`, `has()`, `getBool()`, `getInt()`, `all()` and `section()`, and nothing that loads or changes values. It keeps the values it was created with; a key that is missing or not an array gives an empty section. `Config` and `ConfigSection` read with the same code, the new `ReadTrait` and `TypedValuesTrait`, so `Config` can cut out a section as well. `ConfigInterface` declares `section()`, so a class of your own that implements it must add the method (#672)

### Changed
- **BREAKING:** PHP 8.2 or newer is required: `composer.json` requires `php` `^8.2`, and CI tests PHP 8.2, 8.3 and 8.4. Applications on PHP 8.1 stay on 3.1.x. `Pipeline`, `MatchedRoute` and `RouteFinder` are `readonly` classes now; they are `final`, so nothing changes for applications (#687)
- **BREAKING:** `composer.json` requires `psr/log` `^3.0` (it allowed `^2.0`), `firebase/php-jwt` `^7.0` (it allowed `^6.0`) and, for development, `mockery/mockery` `^1.6`. An application whose own `composer.json` pins `psr/log` 2 or `firebase/php-jwt` 6 must allow the newer major. `firebase/php-jwt` 7 rejects an HMAC key shorter than its algorithm needs (32 bytes for HS256) with `Provided key is too short`; the JWT authentication signs with `APP_KEY`, so an application with a shorter key must generate a new one with `php qt core:key` (#687)
Expand All @@ -18,6 +21,11 @@ The format is based on Keep a Changelog.
- The test suite runs on PHPUnit `^11.5` (a development dependency). Its tests use attributes such as `#[DataProvider]` instead of doc-comment markers, which PHPUnit 12 no longer reads (#687)
- **BREAKING:** The `single` and `daily` log adapters write the context of a log call after the message, as one line of JSON, for example `[2026-11-23 14:02:11] Info: Order paid {"order":1042}`; they ignored it, so a failed cron task lost its `exception`, `file` and `line`. A `trace` that is text stays on its own lines, an exception in the context is written as its class, message, file and line, and a context value that cannot be converted never makes the log call fail. A line without a context is unchanged. A tool that parses log lines must allow the JSON at the end, and passwords or tokens passed in the context now reach the log file. The message stays `string|Stringable`, as PSR-3 defines: `logger()->info([...])` throws a `TypeError`, so put structured data in the context, and a custom adapter that uses `LoggerTrait` must pass `formatMessage()` a string (#613)
- **BREAKING:** The hierarchy flag of `Quantum\Config\Setup`, deprecated in 3.1.2, is removed: the `$hierarchical` constructor argument, `setHierarchy()` and `getHierarchy()`. A module's config file that does not exist always falls back to `shared/config`. The constructor takes `($pathPrefix, $fileName, $module, $exceptionMessage)`, so the module and the exception message move up one position: `new Setup('config', 'app', true, 'Admin')` must become `new Setup('config', 'app', module: 'Admin')`. In a file that declares `strict_types`, the old call fails with a `TypeError`. Without it, PHP turns `true` into the module `1` and `false` into no module, which means the current request's module, and the module name becomes the exception message, so the config is read from `shared` or from the wrong module without an error. Calls that pass only the first two arguments, or the module as a named argument, are unaffected (#619)
- **BREAKING:** `Config::all()` returns the values as an array, and `[]` when the config is empty; it returned the internal `Dflydev\DotAccessData\Data` object, or `null`, through which the config could be changed without `set()`. Code that reads the result, such as `foreach (config()->all() as ...)` or `empty(config()->all())`, keeps working. Code that calls methods on it, such as `config()->all()->get('app.name')`, must use `config()->get('app.name')`, and a check for `null` must check for `[]` (#672)
- **BREAKING:** `ConfigInterface` declares `section(string $key): ConfigSection` and types `all(): array`. A class of your own that implements it must add `section()` and return an array from `all()` (#672)
- **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)

### 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 @@ -27,6 +35,7 @@ The format is based on Keep a Changelog.
- The Dropbox and Google Drive storage adapters refresh an expired access token at most once per request. The request after the refresh called the same method again without a limit, so a 401 that came back after the refresh, or a 401 from the token request itself, repeated the requests without end. When the retried request or the token request fails, the adapter throws its `Exception`. The retried request keeps its HTTP method; it was always sent as `POST` (#694)
- 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)

## [3.1.2] - 2026-11-19

Expand Down
2 changes: 1 addition & 1 deletion src/App/Helpers/misc.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ function slugify(string $text): string
*/
function is_debug_mode(): bool
{
return config()->getBool('app.debug');
return config()->getBool('app.debug', false);
}

/**
Expand Down
19 changes: 15 additions & 4 deletions src/Auth/Adapters/JwtAuthAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@

use Quantum\Auth\Contracts\AuthenticatableInterface;
use Quantum\Auth\Contracts\AuthServiceInterface;
use Quantum\Config\Exceptions\ConfigException;
use Quantum\Auth\Exceptions\AuthException;
use Quantum\Jwt\Exceptions\JwtException;
use Quantum\Di\Exceptions\DiException;
use Quantum\Auth\Traits\AuthTrait;
use Quantum\Config\ConfigSection;
use Quantum\Auth\Enums\AuthKeys;
use Quantum\Mailer\Mailer;
use Quantum\Hasher\Hasher;
Expand All @@ -35,20 +37,29 @@ class JwtAuthAdapter implements AuthenticatableInterface
protected JwtToken $jwt;

/**
* @param array<string, mixed> $config
* @throws AuthException
* @throws AuthException|ConfigException
*/
public function __construct(AuthServiceInterface $authService, Mailer $mailer, Hasher $hasher, JwtToken $jwt, array $config = [])
public function __construct(AuthServiceInterface $authService, Mailer $mailer, Hasher $hasher, JwtToken $jwt, ConfigSection $config)
{
$this->authService = $authService;
$this->mailer = $mailer;
$this->hasher = $hasher;
$this->jwt = $jwt;
$this->config = $config;
$this->readConfig($config);

$this->verifySchema($this->authService->userSchema());
}

/**
* Reads the auth settings once, so an invalid value fails when the adapter is built
* @throws ConfigException
*/
protected function readConfig(ConfigSection $config): void
{
$this->twoFactorEnabled = $config->getBool('two_fa', false);
$this->otpExpires = $config->getInt('otp_expires', 2);
}

/**
* @inheritDoc
* @return string|array<string, string>
Expand Down
25 changes: 18 additions & 7 deletions src/Auth/Adapters/SessionAuthAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Quantum\App\Exceptions\BaseException;
use Quantum\Di\Exceptions\DiException;
use Quantum\Auth\Traits\AuthTrait;
use Quantum\Config\ConfigSection;
use Quantum\Auth\Enums\AuthKeys;
use Quantum\Hasher\Hasher;
use Quantum\Mailer\Mailer;
Expand All @@ -36,20 +37,32 @@ class SessionAuthAdapter implements AuthenticatableInterface

private const DEFAULT_REMEMBER_LIFETIME = 2592000;

private int $rememberLifetime;

/**
* @param array<string, mixed> $config
* @throws AuthException
* @throws AuthException|ConfigException
*/
public function __construct(AuthServiceInterface $authService, Mailer $mailer, Hasher $hasher, array $config = [])
public function __construct(AuthServiceInterface $authService, Mailer $mailer, Hasher $hasher, ConfigSection $config)
{
$this->authService = $authService;
$this->mailer = $mailer;
$this->hasher = $hasher;
$this->config = $config;
$this->readConfig($config);

$this->verifySchema($this->authService->userSchema());
}

/**
* Reads the auth settings once, so an invalid value fails when the adapter is built
* @throws ConfigException
*/
protected function readConfig(ConfigSection $config): void
{
$this->twoFactorEnabled = $config->getBool('two_fa', false);
$this->otpExpires = $config->getInt('otp_expires', 2);
$this->rememberLifetime = $config->getInt('session.remember_lifetime', self::DEFAULT_REMEMBER_LIFETIME);
}

/**
* @inheritDoc
* @throws AuthException
Expand Down Expand Up @@ -200,12 +213,10 @@ private function setRememberToken(User $user): void
[$this->keyFields[AuthKeys::REMEMBER_TOKEN->value] => $rememberToken]
);

$rememberLifetime = (int) ($this->config['session']['remember_lifetime'] ?? self::DEFAULT_REMEMBER_LIFETIME);

cookie()->set(
$this->keyFields[AuthKeys::REMEMBER_TOKEN->value],
$rememberToken,
$rememberLifetime,
$this->rememberLifetime,
'/',
'',
true,
Expand Down
2 changes: 1 addition & 1 deletion src/Auth/Factories/AuthFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public function resolve(?string $adapter = null): Auth
private function createInstance(string $adapterClass, string $adapter): Auth
{
$authService = $this->createAuthService($adapter);
$authConfig = (array) config()->get('auth');
$authConfig = config()->section('auth');

$adapterInstance = $adapter === AuthType::JWT
? new $adapterClass($authService, mailer(), new Hasher(), $this->createJwtInstance(), $authConfig)
Expand Down
18 changes: 12 additions & 6 deletions src/Auth/Traits/AuthTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Quantum\App\Exceptions\BaseException;
use Quantum\Jwt\Exceptions\JwtException;
use Quantum\Di\Exceptions\DiException;
use Quantum\Config\ConfigSection;
use Quantum\Auth\Enums\AuthKeys;
use Quantum\Mailer\Mailer;
use Quantum\Hasher\Hasher;
Expand All @@ -39,10 +40,9 @@ trait AuthTrait

protected int $otpLength = 6;

/**
* @var array<string, mixed>
*/
protected array $config = [];
protected bool $twoFactorEnabled = false;

protected int $otpExpires = 2;

/**
* @var array<string, string>
Expand Down Expand Up @@ -217,7 +217,7 @@ protected function twoStepVerification(User $user): string

$time = new DateTime();

$time->add(new DateInterval('PT' . ($this->config['otp_expires'] ?? 2) . 'M'));
$time->add(new DateInterval('PT' . $this->otpExpires . 'M'));

$this->authService->update(
$this->keyFields[AuthKeys::USERNAME->value],
Expand Down Expand Up @@ -326,6 +326,12 @@ protected function sendMail(User $user, array $body): void
->send();
}

/**
* Reads the adapter's settings once, so an invalid value fails when the adapter is built
* @throws ConfigException
*/
abstract protected function readConfig(ConfigSection $config): void;

/**
* Verify user schema
* @param array<string, mixed> $schema
Expand All @@ -350,6 +356,6 @@ protected function verifySchema(array $schema): void

protected function isTwoFactorEnabled(): bool
{
return filter_var($this->config['two_fa'] ?? false, FILTER_VALIDATE_BOOLEAN);
return $this->twoFactorEnabled;
}
}
12 changes: 7 additions & 5 deletions src/Cache/Adapters/DatabaseAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
namespace Quantum\Cache\Adapters;

use Quantum\Cache\Exceptions\InvalidCacheKeyException;
use Quantum\Config\Exceptions\ConfigException;
use Quantum\Model\Exceptions\ModelException;
use Quantum\App\Exceptions\BaseException;
use Quantum\Model\Factories\ModelFactory;
use Quantum\Cache\Traits\CacheTrait;
use Psr\SimpleCache\CacheInterface;
use Quantum\Config\ConfigSection;
use Quantum\Model\DbModel;
use DateInterval;
use Exception;
Expand All @@ -31,13 +33,13 @@ class DatabaseAdapter implements CacheInterface
private DbModel $cacheModel;

/**
* @param array<string, mixed> $params
* @throws ConfigException
*/
public function __construct(array $params)
public function __construct(ConfigSection $config)
{
$this->ttl = $params['ttl'];
$this->prefix = $params['prefix'];
$this->cacheModel = ModelFactory::createDynamicModel($params['table']);
$this->ttl = $config->getInt('ttl');
$this->prefix = $config->get('prefix');
$this->cacheModel = ModelFactory::createDynamicModel($config->get('table'));
}

/**
Expand Down
10 changes: 5 additions & 5 deletions src/Cache/Adapters/FileAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Quantum\Di\Exceptions\DiException;
use Quantum\Cache\Traits\CacheTrait;
use Psr\SimpleCache\CacheInterface;
use Quantum\Config\ConfigSection;
use Quantum\Storage\FileSystem;
use ReflectionException;
use DateInterval;
Expand All @@ -42,14 +43,13 @@ class FileAdapter implements CacheInterface
* @throws ConfigException
* @throws DiException
* @throws ReflectionException
* @param array<string, mixed> $params
*/
public function __construct(array $params)
public function __construct(ConfigSection $config)
{
$this->fs = FileSystemFactory::get();
$this->ttl = $params['ttl'];
$this->prefix = $params['prefix'];
$this->cacheDir = $params['path'];
$this->ttl = $config->getInt('ttl');
$this->prefix = $config->get('prefix');
$this->cacheDir = $config->get('path');
}

/**
Expand Down
12 changes: 7 additions & 5 deletions src/Cache/Adapters/MemcachedAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@
namespace Quantum\Cache\Adapters;

use Quantum\Cache\Exceptions\InvalidCacheKeyException;
use Quantum\Config\Exceptions\ConfigException;
use Quantum\Cache\Exceptions\CacheException;
use Quantum\App\Exceptions\BaseException;
use Quantum\Cache\Traits\CacheTrait;
use Psr\SimpleCache\CacheInterface;
use Quantum\Config\ConfigSection;
use DateInterval;
use Memcached;
use Throwable;
Expand All @@ -36,15 +38,15 @@ class MemcachedAdapter implements CacheInterface

/**
* @throws BaseException
* @param array<string, mixed> $params
* @throws ConfigException
*/
public function __construct(array $params)
public function __construct(ConfigSection $config)
{
$this->ttl = $params['ttl'];
$this->prefix = $params['prefix'];
$this->ttl = $config->getInt('ttl');
$this->prefix = $config->get('prefix');

$this->memcached = new Memcached();
$this->memcached->addServer($params['host'], (int) $params['port']);
$this->memcached->addServer($config->get('host'), $config->getInt('port'));

if (!$this->memcached->getStats()) {
throw CacheException::cantConnect('Memcached server');
Expand Down
Loading
Loading