diff --git a/v3.0/advanced-features/configuration.md b/v3.0/advanced-features/configuration.md index 4692b52..1754c76 100644 --- a/v3.0/advanced-features/configuration.md +++ b/v3.0/advanced-features/configuration.md @@ -29,7 +29,8 @@ The `Config` class loads configuration files described by a `Quantum\Config\Setu - `set(string $key, $value)`: Set or overwrite config value. - `delete(string $key)`: Remove a config key. - `flush()`: Clear all loaded config data. -- `all()`: Retrieve all configs as dot-accessible object. +- `all()`: Retrieve all config values as an array (a copy). +- `section(string $key)`: Retrieve the values under a key as a read-only `ConfigSection`, the shape adapters receive their settings in. ## Environment Support diff --git a/v3.0/packages/auth/adapters.md b/v3.0/packages/auth/adapters.md index f7b4fac..261f33c 100644 --- a/v3.0/packages/auth/adapters.md +++ b/v3.0/packages/auth/adapters.md @@ -33,6 +33,10 @@ The adapter then: The remember cookie lifetime comes from `auth.session.remember_lifetime`. If that setting is absent, the default is `2592000` seconds (30 days). +### When the settings are read + +The adapter reads `two_fa`, `otp_expires` and `session.remember_lifetime` once, when it is built. An invalid value, such as an `otp_expires` that is not a [whole number](../config/contracts.md#typed-reader-contract), therefore fails there, also while two-factor authentication is off, and never halfway through a sign-in. An auth adapter of your own that uses `Quantum\Auth\Traits\AuthTrait` implements `readConfig(ConfigSection $config)` to read its settings the same way. + On sign-out, the adapter deletes the session user, regenerates the session ID, clears the stored remember token, and deletes the cookie. ### Two-factor caveat diff --git a/v3.0/packages/auth/usage.md b/v3.0/packages/auth/usage.md index 2309e77..448db36 100644 --- a/v3.0/packages/auth/usage.md +++ b/v3.0/packages/auth/usage.md @@ -58,7 +58,7 @@ Result shape depends on the adapter: - session adapter: `true` and the user is written to session - JWT adapter: fresh `accessToken` and `refreshToken` values -If the code expires, verification fails with an auth exception. OTP expiry defaults to 2 minutes unless `otp_expires` is configured. +If the code expires, verification fails with an auth exception. OTP expiry defaults to 2 minutes unless `otp_expires` is configured (see [When the settings are read](adapters.md#when-the-settings-are-read)). ## Registration and activation diff --git a/v3.0/packages/cache/adapters.md b/v3.0/packages/cache/adapters.md index f053077..475cc27 100644 --- a/v3.0/packages/cache/adapters.md +++ b/v3.0/packages/cache/adapters.md @@ -9,6 +9,10 @@ Quantum's cache package exposes one API across four backends. Pick the adapter b - Use `memcached` for an external shared cache server. - Use `redis` for an external shared cache database. +## Config values + +Each adapter receives its own part of the config, such as `cache.redis`, as a read-only `ConfigSection` (see [Read one part of the config](../config/usage.md#read-one-part-of-the-config)). `ttl`, and `port` for Memcached and Redis, are required: the adapter reads them as [whole numbers](../config/contracts.md#typed-reader-contract) when it is built. + ## File adapter Use the file adapter when local disk storage is enough. diff --git a/v3.0/packages/config/architecture.md b/v3.0/packages/config/architecture.md index 941d14c..e550cbf 100644 --- a/v3.0/packages/config/architecture.md +++ b/v3.0/packages/config/architecture.md @@ -12,13 +12,29 @@ Config sits between the PHP config files and the rest of the framework. After that, reads come from memory through `get()`, `has()`, and `all()`. `getBool()` and `getInt()` read through `get()` and convert the value on the way out. -## How `Config` is organised +## How `Config` and `ConfigSection` are organised -`Config` implements `ConfigInterface` and keeps only its state and `load()`. The rest comes from three traits in `Quantum\Config\Traits`: +Two classes read config, and they share the reading code: -- `ConfigFileTrait`: `import()`, `importIfExists()` and the file lookup -- `ValueTrait`: `get()`, `has()`, `set()`, `delete()`, `all()` and `flush()` -- `TypedValuesTrait`: the typed readers `getBool()` and `getInt()` +- `Config` is the application config. It loads and imports the config files itself (`load()`, `import()`, `importIfExists()` and the file lookup) and implements `ConfigInterface`. +- `ConfigSection` is one read-only part of it, such as `cache.redis`. It is `final` and has no method that loads or changes values. + +The shared code lives in `Quantum\Config\Traits`: + +- `ReadTrait`: `get()`, `has()`, `all()` and `section()`, used by both classes +- `TypedValuesTrait`: the typed readers `getBool()` and `getInt()`, used by both classes +- `WriteTrait`: `set()`, `delete()` and `flush()`, used by `Config` only + +## Sections + +An adapter needs its own settings, not the whole config, and it should not be able to change them. So a factory cuts out the adapter's part and passes it in: + +```php +// CacheFactory, with $adapter = 'redis' +$cacheAdapter = new $adapterClass(config()->section('cache.' . $adapter)); +``` + +`section()` copies the values under the key into a new `ConfigSection`. What that copy guarantees is listed in the [section contract](contracts.md#section-contract). ## Two storage modes diff --git a/v3.0/packages/config/contracts.md b/v3.0/packages/config/contracts.md index a7fbdf2..bf59823 100644 --- a/v3.0/packages/config/contracts.md +++ b/v3.0/packages/config/contracts.md @@ -1,6 +1,6 @@ # Config Contracts -This page covers the behavior other code can rely on when using `Quantum\Config\Config`. +This page covers the behavior other code can rely on when using `Quantum\Config\Config` and `Quantum\Config\ConfigSection`. ## Load contract @@ -53,8 +53,8 @@ $config->importIfExists($setup): bool ### `get(string $key, $default = null)` -- returns the stored value when the key exists -- returns the provided default when the key is missing +- returns the stored value when the key exists, `null` and empty text included +- returns the provided default only when the key is missing Keys use dot notation because the backing store is a dot-accessible data container. @@ -63,33 +63,57 @@ Keys use dot notation because the backing store is a dot-accessible data contain - returns `true` when the key exists in the current store - returns `false` when the store is empty or the key is missing -### `all(): ?Data` +### `all(): array` -- returns the whole data container -- returns `null` before anything has been loaded, imported, or set +- returns all values as an array, a copy: changing it does not change the config +- returns `[]` before anything has been loaded, imported, or set + +### `section(string $key): ConfigSection` + +- returns the values under the key as a new `ConfigSection`, described in the [section contract](#section-contract) ## Typed reader contract `getBool()` and `getInt()` read through `get()`. For how to use them, see [Reading booleans and numbers](usage.md#reading-booleans-and-numbers). ```php -public function getBool(string $key, bool $default = false): bool; -public function getInt(string $key, int $default = 0): int; +public function getBool(string $key, ?bool $default = null): bool; +public function getInt(string $key, ?int $default = null): int; ``` -- a missing key, or a key whose value is `null`, returns the default -- `getBool()` returns `true` for `true`, `1`, `on` and `yes`, ignoring letter case, and `false` for every other value, including `false`, `0`, `off`, `no` and an empty value -- `getInt()` returns the number for a whole number or whole-number text such as `587`, and throws `ConfigException::invalidValue()` for any other value, such as `abc`, `1.5` or an empty value +- a key that is missing, `null`, or empty text (such as `KEY=` in `.env`) is not set +- a key that is not set returns the default when one is passed, and throws `ConfigException::missingKey()` ("The config key `x` is missing.") when none is passed, so a reader without a default states a required key +- `getBool()` returns `true` for `true`, `1`, `on` and `yes`, ignoring letter case, and `false` for every other value, including `false`, `0`, `off` and `no` +- `getInt()` returns the number for a whole number or whole-number text such as `587`, and throws `ConfigException::invalidValue()` for any other value, such as `abc` or `1.5` - `get()` is not affected and keeps returning the raw value -The methods belong to the `Config` class. `ConfigInterface` does not declare them, so code that depends on the interface alone cannot call them. +`Config` and `ConfigSection` both have these methods. `ConfigInterface` does not declare them, so code that depends on the interface alone cannot call them. + +## Section contract + +`Quantum\Config\ConfigSection` is the read-only part of the config that adapters receive. `config()->section('cache.redis')` returns one, and `new ConfigSection([...])` builds one from an array: + +```php +use Quantum\Config\ConfigSection; + +$section = new ConfigSection(['host' => '127.0.0.1', 'port' => '6379']); + +$section->getInt('port'); // 6379 +``` + +- it has `get()`, `has()`, `all()`, `section()`, `getBool()` and `getInt()`, with the rules above +- it has no `load()`, `import()`, `set()`, `delete()` or `flush()`, and the class is `final` +- `section()` gives an empty section when the key is missing or its value is not an array +- a section keeps the values it was created with: later changes to the config do not reach it +- arrays are copied, so a section and the arrays it returns never change each other +- objects stored in the config, such as closures or services, are not cloned: they are shared ## Write contract ### `set(string $key, $value): void` - creates the store if needed -- writes or overwrites the value at the given key +- writes or overwrites the value at the given key; a dotted key such as `cache.redis` nests the value ### `delete(string $key): void` @@ -99,7 +123,7 @@ The methods belong to the `Config` class. `ConfigInterface` does not declare the ### `flush(): void` - clears the entire in-memory store -- makes `all()` return `null` again +- makes `all()` return `[]` again - allows a later `load()` call to run again ## Failure behavior @@ -107,4 +131,5 @@ The methods belong to the `Config` class. `ConfigInterface` does not declare the - a missing file in `load()` or `import()` raises `ConfigException` with the `Setup` exception message (by default ``File `/` not found!``) - duplicate imported section names raise `ConfigException` - `getInt()` raises `ConfigException::invalidValue()` for a value that is not a whole number +- `getBool()` and `getInt()` without a default raise `ConfigException::missingKey()` for a key that is not set - helper resolution can fail if DI registration or resolution fails diff --git a/v3.0/packages/config/overview.md b/v3.0/packages/config/overview.md index 3e13b10..de0cc73 100644 --- a/v3.0/packages/config/overview.md +++ b/v3.0/packages/config/overview.md @@ -10,6 +10,7 @@ Use it when you want to load PHP config files, read values with dot notation, an - stores values in one dot-accessible container - supports two loading modes: `load()` for the root store and `import()` for named config sections, plus `importIfExists()` for optional files - reads a value as a boolean or a whole number with `getBool()` and `getInt()` +- hands one part of the config, such as `cache.redis`, to an adapter as a read-only `ConfigSection` - exposes a DI-backed `config()` helper for shared access ## Most applications use `import()` @@ -46,9 +47,10 @@ With `load()`, keys come from the file directly. With `import()`, the same file ## Package shape -- `Quantum\Config\Config` manages the in-memory store +- `Quantum\Config\Config` manages the in-memory store and loads the config files +- `Quantum\Config\ConfigSection` is a read-only part of the config, the shape adapters receive their settings in - `Quantum\Config\Contracts\ConfigInterface` defines the public API -- `Quantum\Config\Traits` holds the code `Config` is built from: `ConfigFileTrait`, `ValueTrait` and `TypedValuesTrait` +- `Quantum\Config\Traits` holds the code both classes share (see [Architecture](architecture.md#how-config-and-configsection-are-organised)) - `Quantum\Config\Setup` describes which file to load - `Quantum\Config\Helpers\config.php` exposes the shared helper - `Quantum\Config\Exceptions\ConfigException` reports missing files and import-name collisions diff --git a/v3.0/packages/config/usage.md b/v3.0/packages/config/usage.md index 757713a..6b0728f 100644 --- a/v3.0/packages/config/usage.md +++ b/v3.0/packages/config/usage.md @@ -39,13 +39,25 @@ Use this pattern for isolated tasks where one file should define the whole confi A config value is whatever the PHP file put there, and often that is text. A line such as `'debug' => env('APP_DEBUG')` stores the string `'false'` when `.env` says `APP_DEBUG=false`, and PHP treats that string as true. Convert the value where you read it: ```php -$debug = config()->getBool('app.debug'); +$debug = config()->getBool('app.debug', false); $limit = config()->getInt('mailer.transport_log_limit', 1000); +$port = config()->getInt('cache.redis.port'); ``` -`getBool()` returns `true` for `true`, `1`, `on` and `yes`, in any letter case, and `false` for everything else, including an empty value. `getInt()` returns the number, and throws a `ConfigException` when the value is not a whole number, so a typo such as `abc` shows up at once instead of silently becoming `0`. When the key is missing, or its value is `null`, both return the default: `false` and `0` unless you pass another. `get()` keeps returning the raw value. +Text such as `'587'` becomes `587`, and a typo such as `abc` throws a `ConfigException` at once instead of silently becoming `0`. The default says whether a key is optional: with one, as for `app.debug`, a key that is not set gives the default; without one, as for the Redis port, the key is required and the reader throws. The exact rules, including what counts as not set, are in the [typed reader contract](contracts.md#typed-reader-contract). -Both are methods of the `Config` class, so `config()` has them. They are available since 3.1.2; the exact rules are on the [contracts page](contracts.md#typed-reader-contract). +## Read one part of the config + +`section()` returns the values under a key as a read-only `ConfigSection`. Framework factories use it to hand each adapter its own settings, and it reads with the same methods: + +```php +$redis = config()->section('cache.redis'); + +$host = $redis->get('host'); +$port = $redis->getInt('port'); +``` + +The section is a read-only copy; the [section contract](contracts.md#section-contract) lists what that guarantees. ## Override values at runtime diff --git a/v3.0/packages/lang/usage.md b/v3.0/packages/lang/usage.md index abf4319..172932e 100644 --- a/v3.0/packages/lang/usage.md +++ b/v3.0/packages/lang/usage.md @@ -142,7 +142,7 @@ What gets translated depends on `use_source_catalog`: - **`false`:** the key itself is the text. `t('Welcome back, {%1}!', [$name])` fills the placeholder and sends `Welcome back, Anna!` to the provider. - **`true`:** the text comes from your translation files in `source_locale`, so `t('custom.test')` reads `custom.test` from `resources/lang/en/` and sends that. A key with no source text, or a request whose language is the source language itself, is answered from the files without calling the provider. `source_locale` is required in this mode. -With `cache.enabled`, every answer is stored through the Cache package adapter named in `cache.default`, for `ttl` seconds, so the same text in the same language is sent to the provider only once. +With `cache.enabled`, every answer is stored through the Cache package adapter named in `cache.default`, for `ttl` seconds, so the same text in the same language is sent to the provider only once. When `ttl` is not set, the cache adapter's own default TTL applies. Errors to expect: diff --git a/v3.0/packages/logger/architecture.md b/v3.0/packages/logger/architecture.md index 3ee4794..b58b54a 100644 --- a/v3.0/packages/logger/architecture.md +++ b/v3.0/packages/logger/architecture.md @@ -33,7 +33,7 @@ After that, the factory reads: - `logging.default` for the default adapter name - `logging..level` for the severity threshold -- `logging.` for adapter-specific constructor parameters +- `logging.` for the adapter's own settings, passed to the adapter as a read-only `ConfigSection` - `logging.message.limit` for the number of messages the `message` adapter keeps ## Debug-mode override diff --git a/v3.0/packages/mailer/adapters.md b/v3.0/packages/mailer/adapters.md index 5e00657..7f86a44 100644 --- a/v3.0/packages/mailer/adapters.md +++ b/v3.0/packages/mailer/adapters.md @@ -20,6 +20,8 @@ The adapter reads these keys from `mailer.smtp`: ] ``` +A missing or empty `port`, such as `MAIL_PORT=` in `.env`, uses 25, PHPMailer's default. + ### Extra methods SMTP is the only adapter with extra composition methods: diff --git a/v3.0/packages/mailer/architecture.md b/v3.0/packages/mailer/architecture.md index c16535d..e732725 100644 --- a/v3.0/packages/mailer/architecture.md +++ b/v3.0/packages/mailer/architecture.md @@ -30,7 +30,7 @@ The practical effect is: After that, it reads: - `mailer.default` for the default adapter name -- `mailer.` for adapter-specific constructor parameters +- `mailer.` for the adapter's own settings, passed to the adapter as a read-only `ConfigSection` - `mailer.mail_trap` during `send()` to decide whether to save or deliver - `mailer.transport_log_limit` during `send()` to bound the [transport log](contracts.md#transport-log) diff --git a/v3.0/packages/ratelimit/adapters.md b/v3.0/packages/ratelimit/adapters.md index e02b9cb..a3bbccd 100644 --- a/v3.0/packages/ratelimit/adapters.md +++ b/v3.0/packages/ratelimit/adapters.md @@ -29,6 +29,8 @@ return [ ]; ``` +Each adapter receives its own part of this config as a read-only `ConfigSection` (see [Read one part of the config](../config/usage.md#read-one-part-of-the-config)). `ttl`, and `port` for Redis, are required: the adapter reads them as [whole numbers](../config/contracts.md#typed-reader-contract) when it is built. + ## File adapter `FileRateLimitAdapter` stores one JSON state file per rate-limit key and uses a lock file to serialize updates. diff --git a/v3.0/packages/renderer/adapters.md b/v3.0/packages/renderer/adapters.md index 5a473ae..4ff6306 100644 --- a/v3.0/packages/renderer/adapters.md +++ b/v3.0/packages/renderer/adapters.md @@ -22,7 +22,7 @@ return [ ]; ``` -The package passes `view.` into the adapter constructor. +The factory passes the `view.` part of the config to the adapter as a read-only `ConfigSection` (see [Read one part of the config](../config/usage.md#read-one-part-of-the-config)). An adapter built by hand without one gets an empty section. In the current starter project, the default config is: @@ -60,7 +60,7 @@ makes `$post` and `$title` available inside `posts/show.php`. - Missing files throw a renderer exception. - Parameter keys become PHP variables, so avoid keys that collide with names already used inside the template. -- The adapter accepts a config array but does not apply any built-in HTML-specific options during rendering. +- The adapter accepts its config section but does not apply any built-in HTML-specific options during rendering. ## Twig adapter @@ -73,7 +73,7 @@ Use it when you want Twig syntax and Twig environment options while keeping Quan - resolves `.php` from the same module-first lookup path - points Twig's filesystem loader at the directory that contains that file - creates a new Twig `Environment` for the render call -- passes the provided config array into Twig as environment options +- passes every option of its config section, `all()`, into Twig as environment options - renders `.php` with the given params For the built-in adapter, top-level logical names such as `home` or `invoice` are the clearest fit. Those map directly to files such as `Views/home.php` and `Views/invoice.php`. diff --git a/v3.0/upgrade-guide.md b/v3.0/upgrade-guide.md index 6612eac..1dc31ed 100644 --- a/v3.0/upgrade-guide.md +++ b/v3.0/upgrade-guide.md @@ -126,7 +126,41 @@ new Setup('config', 'app', module: 'Admin'); An old call does not always fail. In a file that declares `strict_types`, it throws 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. Calls that pass only the first two arguments, or the module as a named argument, need no change. -### 10. Check the upgrade +### 10. Config readers and adapter settings + +**`getBool()` and `getInt()` without a default require the key.** A key that is missing, `null` or empty text (such as `MAIL_PORT=` in `.env`) throws `ConfigException::missingKey()`; it gave `false` or `0`. Pass a default where a key is optional: + +```php +// before +$beta = config()->getBool('features.beta'); + +// after +$beta = config()->getBool('features.beta', false); +``` + +The exact rules are in the [typed reader contract](packages/config/contracts.md#typed-reader-contract). + +**`config()->all()` returns an array,** a copy, and `[]` when the config is empty. Code that called methods on the result, such as `config()->all()->get('app.name')`, uses `config()->get('app.name')`, and a check for `null` checks for `[]`. + +**Adapters receive a `ConfigSection`.** The framework's factories pass it for you. Code that builds an adapter itself wraps its array: + +```php +use Quantum\Config\ConfigSection; + +// before: new RedisAdapter(['host' => '127.0.0.1', 'port' => 6379, 'ttl' => 60, 'prefix' => 'app']); +$cache = new RedisAdapter(new ConfigSection(['host' => '127.0.0.1', 'port' => 6379, 'ttl' => 60, 'prefix' => 'app'])); +``` + +Ports, TTLs and lifetimes are read as whole numbers, so a typo such as `abc` now throws instead of becoming `0`, and a missing cache or rate limit `ttl` or `port` throws when the adapter is built. The auth adapters require their config again and read `two_fa`, `otp_expires` and `session.remember_lifetime` when they are built. + +**Code of your own that uses the framework's traits:** + +- `Quantum\Config\Traits\ValueTrait` is renamed `WriteTrait` and keeps `set()`, `delete()` and `flush()`; reading moved to `ReadTrait`. `ConfigFileTrait` is removed, its code is part of `Config`. +- A class that implements `ConfigInterface` adds `section(string $key): ConfigSection` and returns an array from `all()`. +- A log adapter that uses `LoggerTrait` declares `initialize(ConfigSection $config)`. +- An auth adapter that uses `AuthTrait` implements `readConfig(ConfigSection $config)`, see [When the settings are read](packages/auth/adapters.md#when-the-settings-are-read). + +### 11. Check the upgrade Update the dependencies and run the checks you already use: @@ -139,8 +173,9 @@ composer phpstan Then look for the names this part replaced. Each hit is a section above: ```bash -grep -rnF -e 'Generator::scan(' -e '@dataProvider' -e 'verbose=' -e 'setHierarchy(' -e 'getHierarchy(' shared modules helpers tests phpunit.xml +grep -rnF -e 'Generator::scan(' -e '@dataProvider' -e 'verbose=' -e 'setHierarchy(' -e 'getHierarchy(' -e 'Config\Traits\ValueTrait' -e 'ConfigFileTrait' -e '->all()->' shared modules helpers tests phpunit.xml grep -rnE "new Setup\([^,]+,[^,]+, *(true|false)" shared modules helpers tests +grep -rnE -e "->(getBool|getInt)\('[^']+'\)" shared modules helpers tests ``` Finally, open a page with `app.debug` on to check the toolbar, sign in once if you use JWT, and run one `php qt` command.