diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c395b448..7fef3b519 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) @@ -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) @@ -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 diff --git a/src/App/Helpers/misc.php b/src/App/Helpers/misc.php index 286161e47..8d0e01e2d 100644 --- a/src/App/Helpers/misc.php +++ b/src/App/Helpers/misc.php @@ -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); } /** diff --git a/src/Auth/Adapters/JwtAuthAdapter.php b/src/Auth/Adapters/JwtAuthAdapter.php index c0caa4ed0..3b2e27964 100644 --- a/src/Auth/Adapters/JwtAuthAdapter.php +++ b/src/Auth/Adapters/JwtAuthAdapter.php @@ -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; @@ -35,20 +37,29 @@ class JwtAuthAdapter implements AuthenticatableInterface protected JwtToken $jwt; /** - * @param array $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 diff --git a/src/Auth/Adapters/SessionAuthAdapter.php b/src/Auth/Adapters/SessionAuthAdapter.php index 2c7abcc5b..8a28a96f4 100644 --- a/src/Auth/Adapters/SessionAuthAdapter.php +++ b/src/Auth/Adapters/SessionAuthAdapter.php @@ -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; @@ -36,20 +37,32 @@ class SessionAuthAdapter implements AuthenticatableInterface private const DEFAULT_REMEMBER_LIFETIME = 2592000; + private int $rememberLifetime; + /** - * @param array $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 @@ -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, diff --git a/src/Auth/Factories/AuthFactory.php b/src/Auth/Factories/AuthFactory.php index cdc8cb36c..fe611bf68 100644 --- a/src/Auth/Factories/AuthFactory.php +++ b/src/Auth/Factories/AuthFactory.php @@ -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) diff --git a/src/Auth/Traits/AuthTrait.php b/src/Auth/Traits/AuthTrait.php index 6b1254eb7..61510d19d 100644 --- a/src/Auth/Traits/AuthTrait.php +++ b/src/Auth/Traits/AuthTrait.php @@ -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; @@ -39,10 +40,9 @@ trait AuthTrait protected int $otpLength = 6; - /** - * @var array - */ - protected array $config = []; + protected bool $twoFactorEnabled = false; + + protected int $otpExpires = 2; /** * @var array @@ -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], @@ -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 $schema @@ -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; } } diff --git a/src/Cache/Adapters/DatabaseAdapter.php b/src/Cache/Adapters/DatabaseAdapter.php index 8d7346b92..897d9471f 100644 --- a/src/Cache/Adapters/DatabaseAdapter.php +++ b/src/Cache/Adapters/DatabaseAdapter.php @@ -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; @@ -31,13 +33,13 @@ class DatabaseAdapter implements CacheInterface private DbModel $cacheModel; /** - * @param array $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')); } /** diff --git a/src/Cache/Adapters/FileAdapter.php b/src/Cache/Adapters/FileAdapter.php index 1c989efd2..fd48a5917 100644 --- a/src/Cache/Adapters/FileAdapter.php +++ b/src/Cache/Adapters/FileAdapter.php @@ -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; @@ -42,14 +43,13 @@ class FileAdapter implements CacheInterface * @throws ConfigException * @throws DiException * @throws ReflectionException - * @param array $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'); } /** diff --git a/src/Cache/Adapters/MemcachedAdapter.php b/src/Cache/Adapters/MemcachedAdapter.php index c26f143ad..cb9ef3025 100644 --- a/src/Cache/Adapters/MemcachedAdapter.php +++ b/src/Cache/Adapters/MemcachedAdapter.php @@ -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; @@ -36,15 +38,15 @@ class MemcachedAdapter implements CacheInterface /** * @throws BaseException - * @param array $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'); diff --git a/src/Cache/Adapters/RedisAdapter.php b/src/Cache/Adapters/RedisAdapter.php index 57d050562..dfdbb769c 100644 --- a/src/Cache/Adapters/RedisAdapter.php +++ b/src/Cache/Adapters/RedisAdapter.php @@ -11,8 +11,10 @@ namespace Quantum\Cache\Adapters; use Quantum\Cache\Exceptions\InvalidCacheKeyException; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Cache\Traits\CacheTrait; use Psr\SimpleCache\CacheInterface; +use Quantum\Config\ConfigSection; use RedisException; use DateInterval; use Throwable; @@ -30,15 +32,15 @@ class RedisAdapter implements CacheInterface /** * @throws RedisException - * @param array $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->redis = new Redis(); - $this->redis->connect($params['host'], (int) $params['port']); + $this->redis->connect($config->get('host'), $config->getInt('port')); } /** diff --git a/src/Cache/Factories/CacheFactory.php b/src/Cache/Factories/CacheFactory.php index 48f341aeb..e6c8c7de2 100644 --- a/src/Cache/Factories/CacheFactory.php +++ b/src/Cache/Factories/CacheFactory.php @@ -76,7 +76,7 @@ public function resolve(?string $adapter = null): Cache */ private function createInstance(string $adapterClass, string $adapter): Cache { - $cacheAdapter = new $adapterClass(config()->get('cache.' . $adapter)); + $cacheAdapter = new $adapterClass(config()->section('cache.' . $adapter)); if (!$cacheAdapter instanceof CacheInterface) { throw CacheException::adapterNotSupported($adapter); diff --git a/src/Captcha/Adapters/HcaptchaAdapter.php b/src/Captcha/Adapters/HcaptchaAdapter.php index f4b7606dd..714ce5bf0 100644 --- a/src/Captcha/Adapters/HcaptchaAdapter.php +++ b/src/Captcha/Adapters/HcaptchaAdapter.php @@ -13,6 +13,7 @@ use Quantum\Captcha\Contracts\CaptchaInterface; use Quantum\Captcha\Traits\CaptchaTrait; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; /** * Class HcaptchaAdapter @@ -35,14 +36,13 @@ class HcaptchaAdapter implements CaptchaInterface /** * Hcaptcha constructor - * @param array $params */ - public function __construct(array $params, HttpClient $httpClient) + public function __construct(ConfigSection $config, HttpClient $httpClient) { $this->http = $httpClient; - $this->secretKey = $params['secret_key']; - $this->siteKey = $params['site_key']; - $this->type = $params['type'] ?? null; + $this->secretKey = $config->get('secret_key'); + $this->siteKey = $config->get('site_key'); + $this->type = $config->get('type'); } } diff --git a/src/Captcha/Adapters/RecaptchaAdapter.php b/src/Captcha/Adapters/RecaptchaAdapter.php index 4d16e8a4b..df0abfc5b 100644 --- a/src/Captcha/Adapters/RecaptchaAdapter.php +++ b/src/Captcha/Adapters/RecaptchaAdapter.php @@ -13,6 +13,7 @@ use Quantum\Captcha\Contracts\CaptchaInterface; use Quantum\Captcha\Traits\CaptchaTrait; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; /** * Class RecaptchaAdapter @@ -35,14 +36,13 @@ class RecaptchaAdapter implements CaptchaInterface /** * RecaptchaAdapter constructor - * @param array $params */ - public function __construct(array $params, HttpClient $httpClient) + public function __construct(ConfigSection $config, HttpClient $httpClient) { $this->http = $httpClient; - $this->secretKey = $params['secret_key']; - $this->siteKey = $params['site_key']; - $this->type = $params['type'] ?? null; + $this->secretKey = $config->get('secret_key'); + $this->siteKey = $config->get('site_key'); + $this->type = $config->get('type'); } } diff --git a/src/Captcha/Factories/CaptchaFactory.php b/src/Captcha/Factories/CaptchaFactory.php index 8ce862b26..593bb42d9 100644 --- a/src/Captcha/Factories/CaptchaFactory.php +++ b/src/Captcha/Factories/CaptchaFactory.php @@ -76,7 +76,7 @@ public function resolve(?string $adapter = null): Captcha */ private function createInstance(string $adapterClass, string $adapter): Captcha { - $adapterInstance = new $adapterClass(config()->get('captcha.' . $adapter), new HttpClient()); + $adapterInstance = new $adapterClass(config()->section('captcha.' . $adapter), new HttpClient()); if (!$adapterInstance instanceof CaptchaInterface) { throw CaptchaException::adapterNotSupported($adapter); diff --git a/src/Config/Config.php b/src/Config/Config.php index 96b9fb04d..b109182a5 100644 --- a/src/Config/Config.php +++ b/src/Config/Config.php @@ -13,19 +13,24 @@ use Quantum\Config\Exceptions\ConfigException; use Quantum\Config\Contracts\ConfigInterface; use Quantum\Config\Traits\TypedValuesTrait; -use Quantum\Config\Traits\ConfigFileTrait; -use Quantum\Config\Traits\ValueTrait; +use Quantum\Config\Traits\WriteTrait; +use Quantum\Config\Traits\ReadTrait; use Dflydev\DotAccessData\Data; +use Quantum\App\App; /** * Class Config + * + * The application config, built up while the app runs: load() at boot, + * import() when a package is first used. section() gives a read-only part of it. + * * @package Quantum\Config */ class Config implements ConfigInterface { - use ConfigFileTrait; - use ValueTrait; + use ReadTrait; use TypedValuesTrait; + use WriteTrait; private ?Data $configs = null; @@ -41,4 +46,86 @@ public function load(Setup $setup): void $this->configs = new Data($this->loadConfig($setup)); } + + /** + * @inheritDoc + * @throws ConfigException + */ + public function import(Setup $setup): void + { + $fileName = $setup->getFilename(); + + if ($fileName && $this->has($fileName)) { + throw ConfigException::configCollision($fileName); + } + + $data = $this->loadConfig($setup); + + if (!$this->configs) { + $this->configs = new Data([$fileName => $data]); + } else { + $this->configs->import([$fileName => $data]); + } + } + + /** + * @inheritDoc + * @throws ConfigException + */ + public function importIfExists(Setup $setup): bool + { + if ($this->resolveFilePath($setup) === null) { + return false; + } + + $this->import($setup); + + return true; + } + + /** + * @return array + * @throws ConfigException + */ + private function loadConfig(Setup $setup): array + { + $filePath = $this->resolveFilePath($setup); + + if ($filePath === null) { + throw new ConfigException(_message($setup->getExceptionMessage(), $setup->getFilename() ?? '')); + } + + return require $filePath; + } + + private function resolveFilePath(Setup $setup): ?string + { + $baseDir = App::getBaseDir(); + + $filePath = $baseDir . DS; + + if ($setup->getModule()) { + $filePath = modules_dir() . DS . $setup->getModule() . DS; + } + + if ($setup->getPathPrefix()) { + $filePath .= $setup->getPathPrefix() . DS; + } + + $filePath .= $setup->getFilename() . '.php'; + + if (file_exists($filePath)) { + return $filePath; + } + + $filePath = $baseDir . DS . 'shared' . DS + . strtolower($setup->getPathPrefix() ?? '') . DS + . $setup->getFilename() . '.php'; + + if (file_exists($filePath)) { + return $filePath; + } + + return null; + } } diff --git a/src/Config/ConfigSection.php b/src/Config/ConfigSection.php new file mode 100644 index 000000000..f4c0e5b9b --- /dev/null +++ b/src/Config/ConfigSection.php @@ -0,0 +1,44 @@ + $data + */ + public function __construct(array $data = []) + { + if ($data !== []) { + $this->configs = new Data($data); + } + } +} diff --git a/src/Config/Contracts/ConfigInterface.php b/src/Config/Contracts/ConfigInterface.php index c48ff52c9..d1fddff04 100644 --- a/src/Config/Contracts/ConfigInterface.php +++ b/src/Config/Contracts/ConfigInterface.php @@ -10,6 +10,7 @@ namespace Quantum\Config\Contracts; +use Quantum\Config\ConfigSection; use Quantum\Config\Setup; /** @@ -18,12 +19,6 @@ */ interface ConfigInterface { - /** - * Gets whole storage data - * @return mixed - */ - public function all(); - /** * Checks if the storage contains a key */ @@ -36,6 +31,17 @@ public function has(string $key): bool; */ public function get(string $key, $default = null); + /** + * Gets the values under the key as a new, read-only section; empty when the value is missing or not an array + */ + public function section(string $key): ConfigSection; + + /** + * Gets all values as an array + * @return array + */ + public function all(): array; + /** * Sets storage value with the given key * @param mixed $value diff --git a/src/Config/Enums/ExceptionMessages.php b/src/Config/Enums/ExceptionMessages.php index 2ed8ce801..a6dfc0830 100644 --- a/src/Config/Enums/ExceptionMessages.php +++ b/src/Config/Enums/ExceptionMessages.php @@ -20,4 +20,5 @@ final class ExceptionMessages extends BaseExceptionMessages { public const CONFIG_COLLISION = 'Config key `{%1}` is already in use'; public const INVALID_WHOLE_NUMBER = 'The config key `{%1}` has the value `{%2}`, which is not a whole number.'; + public const MISSING_KEY = 'The config key `{%1}` is missing.'; } diff --git a/src/Config/Exceptions/ConfigException.php b/src/Config/Exceptions/ConfigException.php index b354c1e90..2b75e3505 100644 --- a/src/Config/Exceptions/ConfigException.php +++ b/src/Config/Exceptions/ConfigException.php @@ -34,4 +34,12 @@ public static function invalidValue(string $key, string $value): self E_ERROR ); } + + public static function missingKey(string $key): self + { + return new self( + _message(ExceptionMessages::MISSING_KEY, [$key]), + E_ERROR + ); + } } diff --git a/src/Config/Traits/ConfigFileTrait.php b/src/Config/Traits/ConfigFileTrait.php deleted file mode 100644 index 73aae5c2e..000000000 --- a/src/Config/Traits/ConfigFileTrait.php +++ /dev/null @@ -1,105 +0,0 @@ -getFilename(); - - if ($fileName && $this->has($fileName)) { - throw ConfigException::configCollision($fileName); - } - - $data = $this->loadConfig($setup); - - if (!$this->configs) { - $this->configs = new Data([$fileName => $data]); - } else { - $this->configs->import([$fileName => $data]); - } - } - - /** - * @inheritDoc - * @throws ConfigException - */ - public function importIfExists(Setup $setup): bool - { - if ($this->resolveFilePath($setup) === null) { - return false; - } - - $this->import($setup); - - return true; - } - - /** - * @return array - * @throws ConfigException - */ - private function loadConfig(Setup $setup): array - { - $filePath = $this->resolveFilePath($setup); - - if ($filePath === null) { - throw new ConfigException(_message($setup->getExceptionMessage(), $setup->getFilename() ?? '')); - } - - return require $filePath; - } - - private function resolveFilePath(Setup $setup): ?string - { - $baseDir = App::getBaseDir(); - - $filePath = $baseDir . DS; - - if ($setup->getModule()) { - $filePath = modules_dir() . DS . $setup->getModule() . DS; - } - - if ($setup->getPathPrefix()) { - $filePath .= $setup->getPathPrefix() . DS; - } - - $filePath .= $setup->getFilename() . '.php'; - - if (file_exists($filePath)) { - return $filePath; - } - - $filePath = $baseDir . DS . 'shared' . DS - . strtolower($setup->getPathPrefix() ?? '') . DS - . $setup->getFilename() . '.php'; - - if (file_exists($filePath)) { - return $filePath; - } - - return null; - } -} diff --git a/src/Config/Traits/ReadTrait.php b/src/Config/Traits/ReadTrait.php new file mode 100644 index 000000000..404c03b5e --- /dev/null +++ b/src/Config/Traits/ReadTrait.php @@ -0,0 +1,65 @@ +configs, shared by Config and ConfigSection. + * + * @package Quantum\Config + */ +trait ReadTrait +{ + /** + * Gets the value by the key, or the default when the key is missing + * @param mixed $default + * @return mixed + */ + public function get(string $key, $default = null) + { + if ($this->configs instanceof Data && $this->configs->has($key)) { + return $this->configs->get($key); + } + + return $default; + } + + /** + * Checks if the key exists + */ + public function has(string $key): bool + { + return $this->configs instanceof Data && $this->configs->has($key); + } + + /** + * Gets all values as an array + * @return array + */ + public function all(): array + { + return $this->configs instanceof Data ? $this->configs->export() : []; + } + + /** + * Gets the values under the key as a new, read-only section; empty when the value is missing or not an array + */ + public function section(string $key): ConfigSection + { + $value = $this->get($key); + + return new ConfigSection(is_array($value) ? $value : []); + } +} diff --git a/src/Config/Traits/TypedValuesTrait.php b/src/Config/Traits/TypedValuesTrait.php index f32ead390..44a9ca984 100644 --- a/src/Config/Traits/TypedValuesTrait.php +++ b/src/Config/Traits/TypedValuesTrait.php @@ -26,14 +26,16 @@ trait TypedValuesTrait abstract public function get(string $key, $default = null); /** - * Gets the value as a boolean + * Gets the value as a boolean; without a default, the key is required. + * A missing key, `null` and empty text (such as `KEY=` in .env) count as not set. + * @throws ConfigException */ - public function getBool(string $key, bool $default = false): bool + public function getBool(string $key, ?bool $default = null): bool { $value = $this->get($key); - if ($value === null) { - return $default; + if ($value === null || $value === '') { + return $default ?? throw ConfigException::missingKey($key); } if (is_bool($value)) { @@ -44,15 +46,16 @@ public function getBool(string $key, bool $default = false): bool } /** - * Gets the value as an integer + * Gets the value as an integer; without a default, the key is required. + * A missing key, `null` and empty text (such as `KEY=` in .env) count as not set. * @throws ConfigException */ - public function getInt(string $key, int $default = 0): int + public function getInt(string $key, ?int $default = null): int { $value = $this->get($key); - if ($value === null) { - return $default; + if ($value === null || $value === '') { + return $default ?? throw ConfigException::missingKey($key); } if (is_int($value)) { diff --git a/src/Config/Traits/ValueTrait.php b/src/Config/Traits/ValueTrait.php deleted file mode 100644 index 72f2382bd..000000000 --- a/src/Config/Traits/ValueTrait.php +++ /dev/null @@ -1,76 +0,0 @@ -configs instanceof Data && $this->configs->has($key)) { - return $this->configs->get($key); - } - - return $default; - } - - /** - * @inheritDoc - */ - public function all(): ?Data - { - return $this->configs; - } - - /** - * @inheritDoc - */ - public function has(string $key): bool - { - return $this->configs instanceof Data && !empty($this->configs->has($key)); - } - - /** - * @inheritDoc - */ - public function set(string $key, $value): void - { - if (!$this->configs) { - $this->configs = new Data([$key => $value]); - } else { - $this->configs->set($key, $value); - } - } - - /** - * @inheritDoc - */ - public function delete(string $key): void - { - $this->configs instanceof Data && $this->configs->remove($key); - } - - /** - * @inheritDoc - */ - public function flush(): void - { - $this->configs = null; - } -} diff --git a/src/Config/Traits/WriteTrait.php b/src/Config/Traits/WriteTrait.php new file mode 100644 index 000000000..984af1483 --- /dev/null +++ b/src/Config/Traits/WriteTrait.php @@ -0,0 +1,51 @@ +configs, used only by Config. + * + * @package Quantum\Config + */ +trait WriteTrait +{ + /** + * @inheritDoc + */ + public function set(string $key, $value): void + { + if (!$this->configs) { + $this->configs = new Data(); + } + + $this->configs->set($key, $value); + } + + /** + * @inheritDoc + */ + public function delete(string $key): void + { + $this->configs instanceof Data && $this->configs->remove($key); + } + + /** + * @inheritDoc + */ + public function flush(): void + { + $this->configs = null; + } +} diff --git a/src/Debugger/Debugger.php b/src/Debugger/Debugger.php index b9f4ea68b..841a3991e 100644 --- a/src/Debugger/Debugger.php +++ b/src/Debugger/Debugger.php @@ -104,7 +104,7 @@ public function __construct(?DebuggerStore $store = null, ?DebugBar $debugBar = */ public function isEnabled(): bool { - return config()->getBool('app.debug'); + return config()->getBool('app.debug', false); } public function initStore(): void diff --git a/src/Lang/Adapters/DeepLAdapter.php b/src/Lang/Adapters/DeepLAdapter.php index ff925f632..2b3a9be6d 100644 --- a/src/Lang/Adapters/DeepLAdapter.php +++ b/src/Lang/Adapters/DeepLAdapter.php @@ -15,6 +15,7 @@ use Quantum\Lang\Exceptions\LangException; use Quantum\App\Exceptions\BaseException; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; use ReflectionException; use ErrorException; @@ -28,13 +29,10 @@ class DeepLAdapter implements LangAdapterInterface protected string $lang; - /** - * @param array $params - */ - public function __construct(string $lang, array $params, ?HttpClient $httpClient = null) + public function __construct(string $lang, ConfigSection $config, ?HttpClient $httpClient = null) { $this->lang = $lang; - $this->params = $params; + $this->config = $config; $this->httpClient = $httpClient ?? new HttpClient(); } @@ -62,14 +60,14 @@ public function get(string $key, $params = null): string return $cached; } - $authKey = (string) ($this->params['auth_key'] ?? ''); + $authKey = (string) ($this->config->get('auth_key') ?? ''); if ($authKey === '') { throw LangException::missingConfig('lang.deepl.auth_key'); } $response = $this->sendRequest( - (string) ($this->params['api_url'] ?? self::API_URL), + (string) ($this->config->get('api_url') ?? self::API_URL), $this->buildPayload($text), [ 'Authorization' => 'DeepL-Auth-Key ' . $authKey, @@ -97,8 +95,8 @@ private function buildPayload(string $text): string 'target_lang' => strtoupper($this->lang), ]; - if (!empty($this->params['source_locale'])) { - $payload['source_lang'] = strtoupper((string) $this->params['source_locale']); + if (!empty($this->config->get('source_locale'))) { + $payload['source_lang'] = strtoupper((string) $this->config->get('source_locale')); } $payloadJson = json_encode($payload); diff --git a/src/Lang/Adapters/FileAdapter.php b/src/Lang/Adapters/FileAdapter.php index f36b7c9e0..386691b2c 100644 --- a/src/Lang/Adapters/FileAdapter.php +++ b/src/Lang/Adapters/FileAdapter.php @@ -15,6 +15,7 @@ use Quantum\Lang\Exceptions\LangException; use Quantum\App\Exceptions\BaseException; use Quantum\Di\Exceptions\DiException; +use Quantum\Config\ConfigSection; use Dflydev\DotAccessData\Data; use ReflectionException; @@ -22,20 +23,14 @@ class FileAdapter implements LangAdapterInterface { protected string $lang; - /** - * @var array - */ - protected array $params = []; + protected ConfigSection $config; private ?Data $translations = null; - /** - * @param array $params - */ - public function __construct(string $lang, array $params = []) + public function __construct(string $lang, ConfigSection $config = new ConfigSection()) { $this->lang = $lang; - $this->params = $params; + $this->config = $config; } public function setLang(string $lang): LangAdapterInterface diff --git a/src/Lang/Adapters/GoogleTranslateAdapter.php b/src/Lang/Adapters/GoogleTranslateAdapter.php index 42d6ff8d4..52ad5a1bd 100644 --- a/src/Lang/Adapters/GoogleTranslateAdapter.php +++ b/src/Lang/Adapters/GoogleTranslateAdapter.php @@ -15,6 +15,7 @@ use Quantum\Lang\Exceptions\LangException; use Quantum\App\Exceptions\BaseException; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; use ReflectionException; use ErrorException; @@ -26,13 +27,10 @@ class GoogleTranslateAdapter implements LangAdapterInterface protected string $lang; - /** - * @param array $params - */ - public function __construct(string $lang, array $params, ?HttpClient $httpClient = null) + public function __construct(string $lang, ConfigSection $config, ?HttpClient $httpClient = null) { $this->lang = $lang; - $this->params = $params; + $this->config = $config; $this->httpClient = $httpClient ?? new HttpClient(); } @@ -60,14 +58,14 @@ public function get(string $key, $params = null): string return $cached; } - $apiKey = (string) ($this->params['api_key'] ?? ''); + $apiKey = (string) ($this->config->get('api_key') ?? ''); if ($apiKey === '') { throw LangException::missingConfig('lang.google_translate.api_key'); } $response = $this->sendRequest( - (string) ($this->params['api_url'] ?? self::API_URL) . '?key=' . urlencode($apiKey), + (string) ($this->config->get('api_url') ?? self::API_URL) . '?key=' . urlencode($apiKey), $this->buildPayload($text), [ 'Content-Type' => 'application/json', @@ -92,8 +90,8 @@ private function buildPayload(string $text): string 'format' => 'text', ]; - if (!empty($this->params['source_locale'])) { - $payload['source'] = (string) $this->params['source_locale']; + if (!empty($this->config->get('source_locale'))) { + $payload['source'] = (string) $this->config->get('source_locale'); } $payloadJson = json_encode($payload); diff --git a/src/Lang/Factories/LangFactory.php b/src/Lang/Factories/LangFactory.php index 764708207..aad7a5a27 100644 --- a/src/Lang/Factories/LangFactory.php +++ b/src/Lang/Factories/LangFactory.php @@ -99,7 +99,7 @@ private function getAdapterClass(string $adapter): string */ private function createInstance(string $adapterClass, string $adapter, string $lang): Lang { - $langConfig = (array) config()->get('lang.' . $adapter); + $langConfig = config()->section('lang.' . $adapter); $langAdapter = $adapter === LangType::FILE ? new $adapterClass($lang, $langConfig) @@ -155,7 +155,7 @@ private function getLangFromQuery(array $supported): ?string */ private function getLangFromUrlSegment(array $supported): ?string { - $segmentIndex = config()->getInt('lang.url_segment'); + $segmentIndex = config()->getInt('lang.url_segment', 0); if (!in_array(request()->getRoutePrefix(), [null, '', '0'], true) && $segmentIndex === 1) { $segmentIndex++; diff --git a/src/Lang/Traits/RemoteAdapterTrait.php b/src/Lang/Traits/RemoteAdapterTrait.php index ba827c1f4..069310b72 100644 --- a/src/Lang/Traits/RemoteAdapterTrait.php +++ b/src/Lang/Traits/RemoteAdapterTrait.php @@ -19,6 +19,7 @@ use Quantum\Lang\Adapters\FileAdapter; use Quantum\Di\Exceptions\DiException; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; use ReflectionException; use ErrorException; @@ -26,10 +27,7 @@ trait RemoteAdapterTrait { protected HttpClient $httpClient; - /** - * @var array - */ - protected array $params = []; + protected ConfigSection $config; /** * @param array|string|null $params @@ -138,43 +136,45 @@ protected function sendRequest(string $url, $data = null, array $headers = [], a private function isCacheEnabled(): bool { - return filter_var($this->params['cache']['enabled'] ?? false, FILTER_VALIDATE_BOOLEAN); + return $this->config->getBool('cache.enabled', false); } private function getCacheAdapter(): string { - return (string) ($this->params['cache']['default'] ?? ''); + return (string) ($this->config->get('cache.default') ?? ''); } private function getCacheTtl(): ?int { - if (!isset($this->params['cache']['ttl'])) { + if ($this->config->get('cache.ttl') === null) { return null; } - return (int) $this->params['cache']['ttl']; + return $this->config->getInt('cache.ttl'); } private function getCacheKey(string $adapter, string $text): string { - $prefix = (string) ($this->params['cache']['prefix'] ?? ''); - $sourceLocale = (string) ($this->params['source_locale'] ?? 'auto'); + $prefix = (string) ($this->config->get('cache.prefix') ?? ''); + $sourceLocale = (string) ($this->config->get('source_locale') ?? 'auto'); return $prefix . sha1($adapter . '|' . $this->lang . '|' . $sourceLocale . '|' . $text); } private function usesSourceCatalog(): bool { - return filter_var($this->params['use_source_catalog'] ?? false, FILTER_VALIDATE_BOOLEAN); + return $this->config->getBool('use_source_catalog', false); } private function getSourceLocale(): ?string { - if (!isset($this->params['source_locale']) || $this->params['source_locale'] === '') { + $sourceLocale = $this->config->get('source_locale'); + + if ($sourceLocale === null || $sourceLocale === '') { return null; } - return (string) $this->params['source_locale']; + return (string) $sourceLocale; } private function getSourceLocaleConfigPath(): string diff --git a/src/Logger/Adapters/DailyAdapter.php b/src/Logger/Adapters/DailyAdapter.php index 723a3f30f..f7058ab6a 100644 --- a/src/Logger/Adapters/DailyAdapter.php +++ b/src/Logger/Adapters/DailyAdapter.php @@ -17,6 +17,7 @@ use Quantum\App\Exceptions\BaseException; use Quantum\Logger\Traits\LoggerTrait; use Quantum\Di\Exceptions\DiException; +use Quantum\Config\ConfigSection; use ReflectionException; /** @@ -29,26 +30,24 @@ class DailyAdapter implements ReportableInterface /** * DailyAdapter constructor - * @param array $params * @throws LoggerException|ConfigException|DiException|BaseException|ReflectionException */ - public function __construct(array $params) + public function __construct(ConfigSection $config) { $this->fs = FileSystemFactory::get(); - $this->initialize($params); + $this->initialize($config); } /** * Initialize the adapter for Daily logs - * @param array $params * @throws LoggerException */ - protected function initialize(array $params): void + protected function initialize(ConfigSection $config): void { - if (!$this->fs->isDirectory($params['path'])) { - throw LoggerException::logPathIsNotDirectory($params['path']); + if (!$this->fs->isDirectory($config->get('path'))) { + throw LoggerException::logPathIsNotDirectory($config->get('path')); } - $this->logFile = $params['path'] . DS . date('Y-m-d') . '.log'; + $this->logFile = $config->get('path') . DS . date('Y-m-d') . '.log'; } } diff --git a/src/Logger/Adapters/SingleAdapter.php b/src/Logger/Adapters/SingleAdapter.php index 9b2532b14..3c6cee09d 100644 --- a/src/Logger/Adapters/SingleAdapter.php +++ b/src/Logger/Adapters/SingleAdapter.php @@ -17,6 +17,7 @@ use Quantum\App\Exceptions\BaseException; use Quantum\Logger\Traits\LoggerTrait; use Quantum\Di\Exceptions\DiException; +use Quantum\Config\ConfigSection; use ReflectionException; /** @@ -29,26 +30,24 @@ class SingleAdapter implements ReportableInterface /** * SingleAdapter constructor - * @param array $params * @throws LoggerException|ConfigException|DiException|BaseException|ReflectionException */ - public function __construct(array $params) + public function __construct(ConfigSection $config) { $this->fs = FileSystemFactory::get(); - $this->initialize($params); + $this->initialize($config); } /** * Initialize the adapter for Single logs - * @param array $params * @throws LoggerException */ - protected function initialize(array $params): void + protected function initialize(ConfigSection $config): void { - if (!$this->fs->extension($params['path'])) { - throw LoggerException::logPathIsNotFile($params['path']); + if (!$this->fs->extension($config->get('path'))) { + throw LoggerException::logPathIsNotFile($config->get('path')); } - $this->logFile = $params['path']; + $this->logFile = $config->get('path'); } } diff --git a/src/Logger/Factories/LoggerFactory.php b/src/Logger/Factories/LoggerFactory.php index f074a0348..23e92080e 100644 --- a/src/Logger/Factories/LoggerFactory.php +++ b/src/Logger/Factories/LoggerFactory.php @@ -89,7 +89,7 @@ private function createInstance(string $adapterClass, string $adapter): Logger return new Logger(new MessageAdapter(config()->getInt('logging.message.limit', 1000))); } - $adapterInstance = new $adapterClass(config()->get('logging.' . $adapter)); + $adapterInstance = new $adapterClass(config()->section('logging.' . $adapter)); if (!$adapterInstance instanceof ReportableInterface) { throw LoggerException::adapterNotSupported($adapter); diff --git a/src/Logger/Traits/LoggerTrait.php b/src/Logger/Traits/LoggerTrait.php index 5bf784b6b..0a1d70277 100644 --- a/src/Logger/Traits/LoggerTrait.php +++ b/src/Logger/Traits/LoggerTrait.php @@ -11,6 +11,7 @@ namespace Quantum\Logger\Traits; use Quantum\Logger\Exceptions\LoggerException; +use Quantum\Config\ConfigSection; use Quantum\Storage\FileSystem; use Stringable; use Throwable; @@ -29,7 +30,7 @@ trait LoggerTrait * Initialize the logger * @throws LoggerException */ - abstract protected function initialize(array $params): void; + abstract protected function initialize(ConfigSection $config): void; /** * Reports a log message diff --git a/src/Mailer/Adapters/MailgunAdapter.php b/src/Mailer/Adapters/MailgunAdapter.php index 6acafb42e..8edfb5f3c 100644 --- a/src/Mailer/Adapters/MailgunAdapter.php +++ b/src/Mailer/Adapters/MailgunAdapter.php @@ -13,6 +13,7 @@ use Quantum\Mailer\Contracts\MailerInterface; use Quantum\Mailer\Traits\MailerTrait; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; use Exception; /** @@ -38,14 +39,13 @@ class MailgunAdapter implements MailerInterface /** * MailgunAdapter constructor - * @param array $params */ - public function __construct(array $params) + public function __construct(ConfigSection $config) { $this->httpClient = new HttpClient(); - $this->apiKey = $params['api_key']; - $this->apiUrl .= $params['domain'] . '/messages'; + $this->apiKey = $config->get('api_key'); + $this->apiUrl .= $config->get('domain') . '/messages'; } /** diff --git a/src/Mailer/Adapters/MandrillAdapter.php b/src/Mailer/Adapters/MandrillAdapter.php index 5d246218d..00f4987ac 100644 --- a/src/Mailer/Adapters/MandrillAdapter.php +++ b/src/Mailer/Adapters/MandrillAdapter.php @@ -13,6 +13,7 @@ use Quantum\Mailer\Contracts\MailerInterface; use Quantum\Mailer\Traits\MailerTrait; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; use Exception; /** @@ -36,13 +37,12 @@ class MandrillAdapter implements MailerInterface /** * MandrillAdapter constructor - * @param array $params */ - public function __construct(array $params) + public function __construct(ConfigSection $config) { $this->httpClient = new HttpClient(); - $this->data['key'] = $params['api_key']; + $this->data['key'] = $config->get('api_key'); } /** diff --git a/src/Mailer/Adapters/ResendAdapter.php b/src/Mailer/Adapters/ResendAdapter.php index 75f75fe31..7e356b6ae 100644 --- a/src/Mailer/Adapters/ResendAdapter.php +++ b/src/Mailer/Adapters/ResendAdapter.php @@ -13,6 +13,7 @@ use Quantum\Mailer\Contracts\MailerInterface; use Quantum\Mailer\Traits\MailerTrait; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; use Exception; /** @@ -38,12 +39,11 @@ class ResendAdapter implements MailerInterface /** * ResendAdapter constructor - * @param array $params */ - public function __construct(array $params) + public function __construct(ConfigSection $config) { $this->httpClient = new HttpClient(); - $this->apiKey = $params['api_key']; + $this->apiKey = $config->get('api_key'); } /** diff --git a/src/Mailer/Adapters/SendgridAdapter.php b/src/Mailer/Adapters/SendgridAdapter.php index 40259af64..29cb0bc5f 100644 --- a/src/Mailer/Adapters/SendgridAdapter.php +++ b/src/Mailer/Adapters/SendgridAdapter.php @@ -13,6 +13,7 @@ use Quantum\Mailer\Contracts\MailerInterface; use Quantum\Mailer\Traits\MailerTrait; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; use Exception; /** @@ -38,13 +39,12 @@ class SendgridAdapter implements MailerInterface /** * SendgridAdapter constructor - * @param array $params */ - public function __construct(array $params) + public function __construct(ConfigSection $config) { $this->httpClient = new HttpClient(); - $this->apiKey = $params['api_key']; + $this->apiKey = $config->get('api_key'); } /** diff --git a/src/Mailer/Adapters/SendinblueAdapter.php b/src/Mailer/Adapters/SendinblueAdapter.php index 600d87a26..ecf377177 100644 --- a/src/Mailer/Adapters/SendinblueAdapter.php +++ b/src/Mailer/Adapters/SendinblueAdapter.php @@ -13,6 +13,7 @@ use Quantum\Mailer\Contracts\MailerInterface; use Quantum\Mailer\Traits\MailerTrait; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; use Exception; /** @@ -38,13 +39,12 @@ class SendinblueAdapter implements MailerInterface /** * SendinblueAdapter constructor - * @param array $params */ - public function __construct(array $params) + public function __construct(ConfigSection $config) { $this->httpClient = new HttpClient(); - $this->apiKey = $params['api_key']; + $this->apiKey = $config->get('api_key'); } /** diff --git a/src/Mailer/Adapters/SmtpAdapter.php b/src/Mailer/Adapters/SmtpAdapter.php index 0aa4d9d61..18f6c5eb2 100644 --- a/src/Mailer/Adapters/SmtpAdapter.php +++ b/src/Mailer/Adapters/SmtpAdapter.php @@ -10,10 +10,12 @@ namespace Quantum\Mailer\Adapters; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Mailer\Contracts\MailerInterface; use Quantum\Di\Exceptions\DiException; use Quantum\Mailer\Traits\MailerTrait; use PHPMailer\PHPMailer\PHPMailer; +use Quantum\Config\ConfigSection; use PHPMailer\PHPMailer\SMTP; use ReflectionException; use Exception; @@ -32,16 +34,15 @@ class SmtpAdapter implements MailerInterface /** * SmtpAdapter constructor - * @param array $params - * @throws DiException|ReflectionException + * @throws ConfigException|DiException|ReflectionException */ - public function __construct(array $params) + public function __construct(ConfigSection $config) { $this->mailer = new PHPMailer(true); $this->mailer->CharSet = 'UTF-8'; - $this->setupSmtp($params); + $this->setupSmtp($config); if (is_debug_mode()) { $this->mailer->SMTPDebug = SMTP::DEBUG_SERVER; @@ -219,17 +220,16 @@ protected function resetTransportState(): void /** * Setups the SMTP - * @param array $params */ - private function setupSmtp(array $params): void + private function setupSmtp(ConfigSection $config): void { $this->mailer->isSMTP(); $this->mailer->SMTPAuth = true; - $this->mailer->Host = $params['host']; - $this->mailer->SMTPSecure = $params['secure']; - $this->mailer->Port = $params['port']; - $this->mailer->Username = $params['username']; - $this->mailer->Password = $params['password']; + $this->mailer->Host = $config->get('host'); + $this->mailer->SMTPSecure = $config->get('secure'); + $this->mailer->Port = $config->getInt('port', 25); + $this->mailer->Username = $config->get('username'); + $this->mailer->Password = $config->get('password'); } /** diff --git a/src/Mailer/Factories/MailerFactory.php b/src/Mailer/Factories/MailerFactory.php index 93b8fb7be..9b1ee9f72 100644 --- a/src/Mailer/Factories/MailerFactory.php +++ b/src/Mailer/Factories/MailerFactory.php @@ -80,7 +80,7 @@ public function resolve(?string $adapter = null): Mailer */ private function createInstance(string $adapterClass, string $adapter): Mailer { - $adapterInstance = new $adapterClass(config()->get('mailer.' . $adapter)); + $adapterInstance = new $adapterClass(config()->section('mailer.' . $adapter)); if (!$adapterInstance instanceof MailerInterface) { throw MailerException::adapterNotSupported($adapter); diff --git a/src/Mailer/Traits/MailerTrait.php b/src/Mailer/Traits/MailerTrait.php index d57c69dfb..303fe52ea 100644 --- a/src/Mailer/Traits/MailerTrait.php +++ b/src/Mailer/Traits/MailerTrait.php @@ -231,7 +231,7 @@ public function send(): bool $this->prepare(); - $sent = config()->getBool('mailer.mail_trap') ? $this->saveEmail() : $this->sendEmail(); + $sent = config()->getBool('mailer.mail_trap', false) ? $this->saveEmail() : $this->sendEmail(); $this->resetFields(); diff --git a/src/Module/Templates/DemoApi/src/Controllers/AuthController.php.tpl b/src/Module/Templates/DemoApi/src/Controllers/AuthController.php.tpl index e354d3f16..78189105b 100644 --- a/src/Module/Templates/DemoApi/src/Controllers/AuthController.php.tpl +++ b/src/Module/Templates/DemoApi/src/Controllers/AuthController.php.tpl @@ -30,7 +30,7 @@ class AuthController extends BaseController try { $code = auth()->signin($request->get('email'), $request->get('password')); - if (config()->getBool('auth.two_fa')) { + if (config()->getBool('auth.two_fa', false)) { $response->set('code', $code); } diff --git a/src/Module/Templates/DemoWeb/src/Controllers/AuthController.php.tpl b/src/Module/Templates/DemoWeb/src/Controllers/AuthController.php.tpl index 768820d84..e128251d1 100644 --- a/src/Module/Templates/DemoWeb/src/Controllers/AuthController.php.tpl +++ b/src/Module/Templates/DemoWeb/src/Controllers/AuthController.php.tpl @@ -59,7 +59,7 @@ class AuthController extends BaseController try { $code = auth()->signin($request->get('email'), $request->get('password'), !!$request->get('remember')); - if (config()->getBool('auth.two_fa')) { + if (config()->getBool('auth.two_fa', false)) { return redirect(base_url(true) . '/' . current_lang() . '/verify/' . $code); } else { return redirect(base_url(true) . '/' . current_lang()); diff --git a/src/RateLimit/Adapters/FileRateLimitAdapter.php b/src/RateLimit/Adapters/FileRateLimitAdapter.php index e9cfb9951..d37a7a09c 100644 --- a/src/RateLimit/Adapters/FileRateLimitAdapter.php +++ b/src/RateLimit/Adapters/FileRateLimitAdapter.php @@ -14,6 +14,7 @@ use Quantum\Config\Exceptions\ConfigException; use Quantum\App\Exceptions\BaseException; use Quantum\Di\Exceptions\DiException; +use Quantum\Config\ConfigSection; use Quantum\Storage\FileSystem; use ReflectionException; @@ -32,14 +33,13 @@ class FileRateLimitAdapter implements RateLimitAdapterInterface private readonly string $prefix; /** - * @param array $params * @throws ConfigException|DiException|BaseException|ReflectionException */ - public function __construct(array $params) + public function __construct(ConfigSection $config) { - $this->resetInterval = $params['ttl']; - $this->path = $params['path']; - $this->prefix = (string) ($params['prefix'] ?? ''); + $this->resetInterval = $config->getInt('ttl'); + $this->path = $config->get('path'); + $this->prefix = (string) $config->get('prefix', ''); $this->fs = fs(); if (!$this->fs->isDirectory($this->path)) { diff --git a/src/RateLimit/Adapters/RedisRateLimitAdapter.php b/src/RateLimit/Adapters/RedisRateLimitAdapter.php index 24950162f..20ac85dc1 100644 --- a/src/RateLimit/Adapters/RedisRateLimitAdapter.php +++ b/src/RateLimit/Adapters/RedisRateLimitAdapter.php @@ -11,6 +11,8 @@ namespace Quantum\RateLimit\Adapters; use Quantum\RateLimit\Contracts\RateLimitAdapterInterface; +use Quantum\Config\Exceptions\ConfigException; +use Quantum\Config\ConfigSection; use RedisException; use Redis; @@ -27,16 +29,16 @@ class RedisRateLimitAdapter implements RateLimitAdapterInterface private readonly string $prefix; /** - * @param array $params * @throws RedisException + * @throws ConfigException */ - public function __construct(array $params) + public function __construct(ConfigSection $config) { - $this->resetInterval = $params['ttl']; - $this->prefix = (string) ($params['prefix'] ?? ''); + $this->resetInterval = $config->getInt('ttl'); + $this->prefix = (string) $config->get('prefix', ''); $this->redis = new Redis(); - $this->redis->connect($params['host'], (int) $params['port']); + $this->redis->connect($config->get('host'), $config->getInt('port')); } public function hit(string $key, int $limit, int $interval): bool diff --git a/src/RateLimit/Factories/RateLimiterFactory.php b/src/RateLimit/Factories/RateLimiterFactory.php index 5b0504f48..b128f2583 100644 --- a/src/RateLimit/Factories/RateLimiterFactory.php +++ b/src/RateLimit/Factories/RateLimiterFactory.php @@ -82,10 +82,10 @@ private function getAdapterClass(string $adapter): string private function createInstance(string $adapterClass, string $adapter): RateLimiter { - $params = (array) config()->get('rate_limit.' . $adapter, []); + $config = config()->section('rate_limit.' . $adapter); /** @var RateLimitAdapterInterface $adapterInstance */ - $adapterInstance = new $adapterClass($params); + $adapterInstance = new $adapterClass($config); return new RateLimiter($adapterInstance); } diff --git a/src/Renderer/Adapters/HtmlAdapter.php b/src/Renderer/Adapters/HtmlAdapter.php index 4a98f4dba..f996af4a8 100644 --- a/src/Renderer/Adapters/HtmlAdapter.php +++ b/src/Renderer/Adapters/HtmlAdapter.php @@ -16,6 +16,7 @@ use Quantum\Config\Exceptions\ConfigException; use Quantum\App\Exceptions\BaseException; use Quantum\Di\Exceptions\DiException; +use Quantum\Config\ConfigSection; use Quantum\Storage\FileSystem; use ReflectionException; @@ -27,18 +28,14 @@ class HtmlAdapter implements TemplateRendererInterface { protected FileSystem $fs; - /** - * @var array|null - */ - protected ?array $configs; + protected ConfigSection $config; /** - * @param array|null $configs * @throws ConfigException|DiException|BaseException|ReflectionException */ - public function __construct(?array $configs = []) + public function __construct(ConfigSection $config = new ConfigSection()) { - $this->configs = $configs; + $this->config = $config; $this->fs = FileSystemFactory::get(); } diff --git a/src/Renderer/Adapters/TwigAdapter.php b/src/Renderer/Adapters/TwigAdapter.php index ee2a46f09..90204958f 100644 --- a/src/Renderer/Adapters/TwigAdapter.php +++ b/src/Renderer/Adapters/TwigAdapter.php @@ -17,6 +17,7 @@ use Quantum\App\Exceptions\BaseException; use Quantum\Di\Exceptions\DiException; use Twig\Loader\FilesystemLoader; +use Quantum\Config\ConfigSection; use Quantum\Storage\FileSystem; use Twig\Error\RuntimeError; use Twig\Error\LoaderError; @@ -33,18 +34,14 @@ class TwigAdapter implements TemplateRendererInterface { protected FileSystem $fs; - /** - * @var array|null - */ - protected ?array $configs; + protected ConfigSection $config; /** - * @param array|null $configs * @throws ConfigException|DiException|BaseException|ReflectionException */ - public function __construct(?array $configs = []) + public function __construct(ConfigSection $config = new ConfigSection()) { - $this->configs = $configs; + $this->config = $config; $this->fs = FileSystemFactory::get(); } @@ -58,7 +55,7 @@ public function render(string $view, array $params = []): string { $loader = $this->getLoader($view); - $twig = new Environment($loader, $this->configs ?? []); + $twig = new Environment($loader, $this->config->all()); $this->addFunctionsToTwig($twig); diff --git a/src/Renderer/Factories/RendererFactory.php b/src/Renderer/Factories/RendererFactory.php index a70096afa..d0f25e4c1 100644 --- a/src/Renderer/Factories/RendererFactory.php +++ b/src/Renderer/Factories/RendererFactory.php @@ -72,7 +72,7 @@ public function resolve(?string $adapter = null): Renderer */ private function createInstance(string $adapterClass, string $adapter): Renderer { - $adapterInstance = new $adapterClass(config()->get('view.' . $adapter)); + $adapterInstance = new $adapterClass(config()->section('view.' . $adapter)); if (!$adapterInstance instanceof TemplateRendererInterface) { throw RendererException::adapterNotSupported($adapter); diff --git a/src/ResourceCache/ViewCache.php b/src/ResourceCache/ViewCache.php index 80c4e853c..81e1d67fb 100644 --- a/src/ResourceCache/ViewCache.php +++ b/src/ResourceCache/ViewCache.php @@ -44,7 +44,7 @@ class ViewCache */ public function __construct() { - $this->isEnabled = request()->getRouteCacheSettings()['enabled'] ?? config()->getBool('resource_cache'); + $this->isEnabled = request()->getRouteCacheSettings()['enabled'] ?? config()->getBool('resource_cache', false); $this->fs = FileSystemFactory::get(); } diff --git a/src/Session/Adapters/Database/DatabaseSessionAdapter.php b/src/Session/Adapters/Database/DatabaseSessionAdapter.php index 7d479c04b..7cc73e594 100644 --- a/src/Session/Adapters/Database/DatabaseSessionAdapter.php +++ b/src/Session/Adapters/Database/DatabaseSessionAdapter.php @@ -17,6 +17,7 @@ use Quantum\App\Exceptions\BaseException; use Quantum\Session\Traits\SessionTrait; use Quantum\Di\Exceptions\DiException; +use Quantum\Config\ConfigSection; use ReflectionException; /** @@ -33,10 +34,9 @@ class DatabaseSessionAdapter implements SessionStorageInterface public const SESSION_TABLE = 'sessions'; /** - * Session params - * @var array|null + * Session config, kept to start the session again after regenerateId() */ - private static ?array $params = []; + private static ?ConfigSection $config = null; /** * Session storage @@ -45,21 +45,19 @@ class DatabaseSessionAdapter implements SessionStorageInterface private static array $storage = []; /** - * @param array|null $params * @throws SessionException|ModelException|BaseException|DiException|ReflectionException */ - public function __construct(?array $params = null) + public function __construct(ConfigSection $config = new ConfigSection()) { - $this->initializeSession($params); + $this->initializeSession($config); } /** - * @param array|null $params * @throws SessionException|ModelException|BaseException|DiException|ReflectionException */ - protected function initializeSession(?array $params = null): void + protected function initializeSession(ConfigSection $config): void { - $sessionTable = $params['table'] ?? self::SESSION_TABLE; + $sessionTable = $config->get('table') ?? self::SESSION_TABLE; $sessionModel = ModelFactory::createDynamicModel($sessionTable); @@ -71,7 +69,7 @@ protected function initializeSession(?array $params = null): void } } - self::$params = $params; + self::$config = $config; self::$storage = &$_SESSION; } } diff --git a/src/Session/Adapters/Native/NativeSessionAdapter.php b/src/Session/Adapters/Native/NativeSessionAdapter.php index 963f9def8..af7533c20 100644 --- a/src/Session/Adapters/Native/NativeSessionAdapter.php +++ b/src/Session/Adapters/Native/NativeSessionAdapter.php @@ -12,7 +12,9 @@ use Quantum\Session\Contracts\SessionStorageInterface; use Quantum\Session\Exceptions\SessionException; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Session\Traits\SessionTrait; +use Quantum\Config\ConfigSection; /** * Class Session @@ -28,10 +30,9 @@ class NativeSessionAdapter implements SessionStorageInterface public const SESSION_TIMEOUT = 30 * 60; /** - * Session params - * @var array|null + * Session config, kept to start the session again after regenerateId() */ - private static ?array $params = []; + private static ?ConfigSection $config = null; /** * Session storage @@ -40,21 +41,19 @@ class NativeSessionAdapter implements SessionStorageInterface private static array $storage = []; /** - * @param array|null $params - * @throws SessionException + * @throws ConfigException|SessionException */ - public function __construct(?array $params = null) + public function __construct(ConfigSection $config = new ConfigSection()) { - $this->initializeSession($params); + $this->initializeSession($config); } /** - * @param array|null $params - * @throws SessionException + * @throws ConfigException|SessionException */ - protected function initializeSession(?array $params = null): void + protected function initializeSession(ConfigSection $config): void { - $timeout = $params['timeout'] ?? self::SESSION_TIMEOUT; + $timeout = $config->getInt('timeout', self::SESSION_TIMEOUT); if (session_status() !== PHP_SESSION_ACTIVE && @session_start() === false) { throw SessionException::sessionNotStarted(); @@ -66,7 +65,7 @@ protected function initializeSession(?array $params = null): void $_SESSION['LAST_ACTIVITY'] = time(); - self::$params = $params; + self::$config = $config; self::$storage = &$_SESSION; } } diff --git a/src/Session/Factories/SessionFactory.php b/src/Session/Factories/SessionFactory.php index ff1d2ebd8..2c5c7b584 100644 --- a/src/Session/Factories/SessionFactory.php +++ b/src/Session/Factories/SessionFactory.php @@ -72,7 +72,7 @@ public function resolve(?string $adapter = null): Session */ private function createInstance(string $adapterClass, string $adapter): Session { - $adapterInstance = new $adapterClass(config()->get('session.' . $adapter)); + $adapterInstance = new $adapterClass(config()->section('session.' . $adapter)); if (!$adapterInstance instanceof SessionStorageInterface) { throw SessionException::adapterNotSupported($adapter); diff --git a/src/Session/Traits/SessionTrait.php b/src/Session/Traits/SessionTrait.php index 480d8e5ad..61bc80b8f 100644 --- a/src/Session/Traits/SessionTrait.php +++ b/src/Session/Traits/SessionTrait.php @@ -10,10 +10,11 @@ namespace Quantum\Session\Traits; -use Quantum\App\Exceptions\BaseException; -use Quantum\Di\Exceptions\DiException; use Quantum\Session\Exceptions\SessionException; use Quantum\Model\Exceptions\ModelException; +use Quantum\App\Exceptions\BaseException; +use Quantum\Di\Exceptions\DiException; +use Quantum\Config\ConfigSection; use ReflectionException; /** @@ -135,7 +136,7 @@ public function regenerateId(): bool session_write_close(); } - $this->initializeSession(self::$params); + $this->initializeSession(self::$config ?? new ConfigSection()); return $result; } diff --git a/tests/Unit/App/Helpers/MiscHelperTest.php b/tests/Unit/App/Helpers/MiscHelperTest.php index 203f61464..5bac70070 100644 --- a/tests/Unit/App/Helpers/MiscHelperTest.php +++ b/tests/Unit/App/Helpers/MiscHelperTest.php @@ -42,4 +42,11 @@ public function testSlugify(): void $this->assertEquals('ebay-com-itm-dual-arm-tv-trkparms-aid-3d111001-26brand-3dunbranded-trksid-p2380057', slugify('ebay.com/itm/DUAL-ARM-TV/?_trkparms=aid%3D111001%26brand%3DUnbranded&_trksid=p2380057')); } + + public function testIsDebugModeIsOffWhenTheDebugKeyIsNotSet(): void + { + config()->flush(); + + $this->assertFalse(is_debug_mode()); + } } diff --git a/tests/Unit/Auth/Adapters/JwtAuthAdapterTest.php b/tests/Unit/Auth/Adapters/JwtAuthAdapterTest.php index 7efa4740f..efce0db13 100644 --- a/tests/Unit/Auth/Adapters/JwtAuthAdapterTest.php +++ b/tests/Unit/Auth/Adapters/JwtAuthAdapterTest.php @@ -2,12 +2,14 @@ namespace Quantum\Tests\Unit\Auth\Adapters; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Auth\Exceptions\AuthException; use Quantum\Auth\Adapters\JwtAuthAdapter; use Quantum\Auth\Enums\ExceptionMessages; use Quantum\Tests\Unit\Auth\AuthTestCase; use Quantum\Hasher\Hasher; use Quantum\Jwt\JwtToken; +use ArgumentCountError; use Quantum\Auth\User; class JwtAuthAdapterTest extends AuthTestCase @@ -43,7 +45,7 @@ private function createJwtAuth(): JwtAuthAdapter $this->mailer, (new Hasher())->setCost(4), $jwt, - (array) config()->get('auth') + config()->section('auth') ); } @@ -56,6 +58,24 @@ public function tearDown(): void parent::tearDown(); } + public function testApiAdapterRequiresItsConfig(): void + { + $this->expectException(ArgumentCountError::class); + + new JwtAuthAdapter($this->authService, $this->mailer, (new Hasher())->setCost(4), new JwtToken()); + } + + public function testApiAdapterRejectsAnOtpExpiryThatIsNotANumberEvenWithTwoFactorOff(): void + { + config()->set('auth.two_fa', false); + config()->set('auth.otp_expires', 'abc'); + + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `otp_expires` has the value `abc`, which is not a whole number.'); + + $this->createJwtAuth(); + } + public function testApiAdapterConstructor(): void { $this->assertInstanceOf(JwtAuthAdapter::class, $this->jwtAuth); diff --git a/tests/Unit/Auth/Adapters/SessionAuthAdapterTest.php b/tests/Unit/Auth/Adapters/SessionAuthAdapterTest.php index 91df932ff..7e959ee96 100644 --- a/tests/Unit/Auth/Adapters/SessionAuthAdapterTest.php +++ b/tests/Unit/Auth/Adapters/SessionAuthAdapterTest.php @@ -3,12 +3,17 @@ namespace Quantum\Tests\Unit\Auth\Adapters; use Quantum\Auth\Contracts\AuthServiceInterface; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Auth\Adapters\SessionAuthAdapter; use Quantum\Auth\Exceptions\AuthException; use Quantum\Auth\Enums\ExceptionMessages; use Quantum\Tests\Unit\Auth\AuthTestCase; +use Quantum\Auth\Adapters\JwtAuthAdapter; +use Quantum\Auth\Traits\AuthTrait; use Quantum\Hasher\Hasher; +use ArgumentCountError; use Quantum\Auth\User; +use ReflectionMethod; use Mockery; class SessionAuthAdapterTest extends AuthTestCase @@ -34,7 +39,7 @@ private function createSessionAuth(): SessionAuthAdapter $this->authService, $this->mailer, (new Hasher())->setCost(4), - (array) config()->get('auth') + config()->section('auth') ); } @@ -52,6 +57,22 @@ public function testWebAdapterConstructor(): void $this->assertInstanceOf(SessionAuthAdapter::class, $this->sessionAuth); } + public function testWebAdapterRequiresItsConfig(): void + { + $this->expectException(ArgumentCountError::class); + + new SessionAuthAdapter($this->authService, $this->mailer, (new Hasher())->setCost(4)); + } + + public function testEveryAuthAdapterReadsItsOwnConfig(): void + { + $this->assertTrue((new ReflectionMethod(AuthTrait::class, 'readConfig'))->isAbstract()); + + foreach ([SessionAuthAdapter::class, JwtAuthAdapter::class] as $adapter) { + $this->assertSame($adapter, (new ReflectionMethod($adapter, 'readConfig'))->getDeclaringClass()->getName()); + } + } + public function testWebAdapterRejectsAUserSchemaWithAMissingKey(): void { $schema = $this->userSchema; @@ -63,7 +84,7 @@ public function testWebAdapterRejectsAUserSchemaWithAMissingKey(): void $this->expectException(AuthException::class); $this->expectExceptionMessage(ExceptionMessages::INCORRECT_USER_SCHEMA); - new SessionAuthAdapter($authService, $this->mailer, (new Hasher())->setCost(4), (array) config()->get('auth')); + new SessionAuthAdapter($authService, $this->mailer, (new Hasher())->setCost(4), config()->section('auth')); } public function testWebSigninIncorrectCredentials(): void @@ -267,4 +288,51 @@ public function testWebRememberTokenLifetimeAcceptsTheTextFromEnv(): void $this->assertTrue(cookie()->has('remember_token')); } + + public function testWebAdapterRejectsARememberLifetimeThatIsNotANumberBeforeTouchingTheToken(): void + { + $this->sessionAuth->signin('admin@qt.com', 'qwerty', true); + $token = $this->authService->get('email', 'admin@qt.com')->getFieldValue('remember_token'); + + config()->set('auth.session.remember_lifetime', 'abc'); + + try { + $this->createSessionAuth(); + $this->fail('The adapter was built with an invalid remember_lifetime'); + } catch (ConfigException $e) { + $this->assertSame('The config key `session.remember_lifetime` has the value `abc`, which is not a whole number.', $e->getMessage()); + } + + $this->assertNotEmpty($token); + $this->assertSame($token, $this->authService->get('email', 'admin@qt.com')->getFieldValue('remember_token')); + } + + public function testWebSigninWithVerificationReadsTheSettingsGivenAsText(): void + { + config()->set('auth.two_fa', 'yes'); + config()->set('auth.otp_expires', '5'); + $this->sessionAuth = $this->createSessionAuth(); + + $this->assertIsString($this->sessionAuth->signin('admin@qt.com', 'qwerty')); + } + + public function testWebSigninWithVerificationUsesTheDefaultOtpExpiryWhenItIsNotSet(): void + { + config()->set('auth.two_fa', true); + config()->delete('auth.otp_expires'); + $this->sessionAuth = $this->createSessionAuth(); + + $this->assertIsString($this->sessionAuth->signin('admin@qt.com', 'qwerty')); + } + + public function testWebAdapterRejectsAnOtpExpiryThatIsNotANumberEvenWithTwoFactorOff(): void + { + config()->set('auth.two_fa', false); + config()->set('auth.otp_expires', 'abc'); + + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `otp_expires` has the value `abc`, which is not a whole number.'); + + $this->createSessionAuth(); + } } diff --git a/tests/Unit/Auth/AuthTest.php b/tests/Unit/Auth/AuthTest.php index a76d3d6e2..e5b25857d 100644 --- a/tests/Unit/Auth/AuthTest.php +++ b/tests/Unit/Auth/AuthTest.php @@ -35,7 +35,7 @@ public function setUp(): void public function testAuthGetAdapter(): void { - $authConfig = (array) config()->get('auth'); + $authConfig = config()->section('auth'); $auth = new Auth(new SessionAuthAdapter($this->authService, $this->mailer, $this->hasher, $authConfig)); @@ -48,7 +48,7 @@ public function testAuthGetAdapter(): void public function testAuthCallingValidMethod(): void { - $auth = new Auth(new JwtAuthAdapter($this->authService, $this->mailer, $this->hasher, $this->jwt, (array) config()->get('auth'))); + $auth = new Auth(new JwtAuthAdapter($this->authService, $this->mailer, $this->hasher, $this->jwt, config()->section('auth'))); $user = $auth->getAdapter()->signup($this->adminUser); @@ -63,7 +63,7 @@ public function testAuthCallingValidMethod(): void public function testAuthCallingInvalidMethod(): void { - $auth = new Auth(new JwtAuthAdapter($this->authService, $this->mailer, $this->hasher, $this->jwt, (array) config()->get('auth'))); + $auth = new Auth(new JwtAuthAdapter($this->authService, $this->mailer, $this->hasher, $this->jwt, config()->section('auth'))); $this->expectException(AuthException::class); diff --git a/tests/Unit/Cache/Adapters/DatabaseAdapterTest.php b/tests/Unit/Cache/Adapters/DatabaseAdapterTest.php index f6d2ae97c..90867ea03 100644 --- a/tests/Unit/Cache/Adapters/DatabaseAdapterTest.php +++ b/tests/Unit/Cache/Adapters/DatabaseAdapterTest.php @@ -4,9 +4,11 @@ use Quantum\Cache\Exceptions\InvalidCacheKeyException; use Quantum\Database\Adapters\Sleekdb\SleekDbal; +use Quantum\Config\Exceptions\ConfigException; use Psr\SimpleCache\InvalidArgumentException; use Quantum\Cache\Adapters\DatabaseAdapter; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; use Quantum\Config\Setup; use DateInterval; @@ -26,13 +28,13 @@ public function setUp(): void SleekDbal::connect(config()->get('database.sleekdb')); - $params = [ + $config = [ 'prefix' => 'test', 'table' => 'cache', 'ttl' => 60, ]; - $this->databaseCache = new DatabaseAdapter($params); + $this->databaseCache = new DatabaseAdapter(new ConfigSection($config)); } public function tearDown(): void @@ -153,13 +155,13 @@ public function testDatabaseAdapterClear(): void public function testDatabaseAdapterExpired(): void { - $params = [ + $config = [ 'prefix' => 'test', 'table' => 'cache', 'ttl' => -1, ]; - $databaseCache = new DatabaseAdapter($params); + $databaseCache = new DatabaseAdapter(new ConfigSection($config)); $databaseCache->set('test', 'Test value'); @@ -250,4 +252,12 @@ public function testDatabaseAdapterDeleteMultipleRejectsKeysThatAreNotStringsOrI $this->assertTrue($this->databaseCache->has('1')); } + + public function testDatabaseAdapterRejectsAMissingTtl(): void + { + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `ttl` is missing.'); + + new DatabaseAdapter(new ConfigSection(['prefix' => 'test', 'table' => 'cache'])); + } } diff --git a/tests/Unit/Cache/Adapters/FileAdapterTest.php b/tests/Unit/Cache/Adapters/FileAdapterTest.php index c4e8c702e..763969734 100644 --- a/tests/Unit/Cache/Adapters/FileAdapterTest.php +++ b/tests/Unit/Cache/Adapters/FileAdapterTest.php @@ -6,6 +6,7 @@ use Psr\SimpleCache\InvalidArgumentException; use Quantum\Cache\Adapters\FileAdapter; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; use DateInterval; class FileAdapterTest extends AppTestCase @@ -16,13 +17,13 @@ public function setUp(): void { parent::setUp(); - $params = [ + $config = [ 'prefix' => 'test', 'path' => base_dir() . DS . 'cache' . DS . 'data', 'ttl' => 60, ]; - $this->fileCache = new FileAdapter($params); + $this->fileCache = new FileAdapter(new ConfigSection($config)); } public function tearDown(): void @@ -130,13 +131,13 @@ public function testFileAdapterClear(): void public function testFileAdapterExpired(): void { - $params = [ + $config = [ 'prefix' => 'test', 'path' => base_dir() . DS . 'cache' . DS . 'data', 'ttl' => -1, ]; - $fileCache = new FileAdapter($params); + $fileCache = new FileAdapter(new ConfigSection($config)); $fileCache->set('test', 'Test value'); diff --git a/tests/Unit/Cache/Adapters/MemcachedAdapterTest.php b/tests/Unit/Cache/Adapters/MemcachedAdapterTest.php index b786ad453..f1f6be499 100644 --- a/tests/Unit/Cache/Adapters/MemcachedAdapterTest.php +++ b/tests/Unit/Cache/Adapters/MemcachedAdapterTest.php @@ -3,8 +3,10 @@ namespace Quantum\Tests\Unit\Cache\Adapters; use PHPUnit\Framework\Attributes\DataProvider; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Cache\Adapters\MemcachedAdapter; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; use DateInterval; use Memcached; @@ -16,14 +18,14 @@ public function setUp(): void { parent::setUp(); - $params = [ + $config = [ 'prefix' => 'test', 'host' => '127.0.0.1', 'port' => 11211, 'ttl' => 60, ]; - $this->memCached = new MemcachedAdapter($params); + $this->memCached = new MemcachedAdapter(new ConfigSection($config)); } public function tearDown(): void @@ -35,12 +37,12 @@ public function tearDown(): void public function testMemcachedAdapterConnectsWithThePortAsText(): void { - $adapter = new MemcachedAdapter([ + $adapter = new MemcachedAdapter(new ConfigSection([ 'prefix' => 'test', 'host' => '127.0.0.1', 'port' => '11211', 'ttl' => 60, - ]); + ])); $adapter->set('port-as-text', 'connected'); @@ -156,14 +158,14 @@ public function testMemcachedAdapterClear(): void public function testMemcachedAdapterExpired(): void { - $params = [ + $config = [ 'prefix' => 'test', 'host' => '127.0.0.1', 'port' => 11211, 'ttl' => 1, ]; - $memCached = new MemcachedAdapter($params); + $memCached = new MemcachedAdapter(new ConfigSection($config)); $memCached->set('test', 'Test value'); @@ -266,4 +268,19 @@ public static function longTtlProvider(): array ]; } + public function testMemcachedAdapterRejectsAMissingTtl(): void + { + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `ttl` is missing.'); + + new MemcachedAdapter(new ConfigSection(['prefix' => 'test', 'host' => '127.0.0.1', 'port' => 11211])); + } + + public function testMemcachedAdapterRejectsAMissingPort(): void + { + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `port` is missing.'); + + new MemcachedAdapter(new ConfigSection(['prefix' => 'test', 'host' => '127.0.0.1', 'ttl' => 60])); + } } diff --git a/tests/Unit/Cache/Adapters/RedisAdapterTest.php b/tests/Unit/Cache/Adapters/RedisAdapterTest.php index 382994c07..9df218f14 100644 --- a/tests/Unit/Cache/Adapters/RedisAdapterTest.php +++ b/tests/Unit/Cache/Adapters/RedisAdapterTest.php @@ -2,8 +2,10 @@ namespace Quantum\Tests\Unit\Cache\Adapters; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Cache\Adapters\RedisAdapter; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; use DateInterval; class RedisAdapterTest extends AppTestCase @@ -14,14 +16,14 @@ public function setUp(): void { parent::setUp(); - $params = [ + $config = [ 'prefix' => 'test', 'host' => '127.0.0.1', 'port' => 6379, 'ttl' => 60, ]; - $this->redis = new RedisAdapter($params); + $this->redis = new RedisAdapter(new ConfigSection($config)); } public function tearDown(): void @@ -33,12 +35,12 @@ public function tearDown(): void public function testRedisAdapterConnectsWithThePortAsText(): void { - $adapter = new RedisAdapter([ + $adapter = new RedisAdapter(new ConfigSection([ 'prefix' => 'test', 'host' => '127.0.0.1', 'port' => '6379', 'ttl' => 60, - ]); + ])); $adapter->set('port-as-text', 'connected'); @@ -154,14 +156,14 @@ public function testRedisAdapterClear(): void public function testRedisAdapterExpired(): void { - $params = [ + $config = [ 'prefix' => 'test', 'host' => '127.0.0.1', 'port' => 6379, 'ttl' => 1, ]; - $redis = new RedisAdapter($params); + $redis = new RedisAdapter(new ConfigSection($config)); $redis->set('test', 'Test value'); @@ -208,4 +210,19 @@ public function testRedisAdapterExpiredWithCustomTtl(): void $this->assertNull($this->redis->get('test')); } + public function testRedisAdapterRejectsAMissingTtl(): void + { + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `ttl` is missing.'); + + new RedisAdapter(new ConfigSection(['prefix' => 'test', 'host' => '127.0.0.1', 'port' => 6379])); + } + + public function testRedisAdapterRejectsAMissingPort(): void + { + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `port` is missing.'); + + new RedisAdapter(new ConfigSection(['prefix' => 'test', 'host' => '127.0.0.1', 'ttl' => 60])); + } } diff --git a/tests/Unit/Cache/CacheTest.php b/tests/Unit/Cache/CacheTest.php index 77f6c91a4..b7b3fbde9 100644 --- a/tests/Unit/Cache/CacheTest.php +++ b/tests/Unit/Cache/CacheTest.php @@ -6,6 +6,7 @@ use Quantum\Cache\Adapters\FileAdapter; use Psr\SimpleCache\CacheInterface; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; use Quantum\Cache\Cache; class CacheTest extends AppTestCase @@ -17,13 +18,13 @@ public function setUp(): void public function testCacheGetAdapter(): void { - $params = [ + $config = [ 'prefix' => 'test', 'path' => base_dir() . DS . 'cache' . DS . 'data', 'ttl' => 60, ]; - $cache = new Cache(new FileAdapter($params)); + $cache = new Cache(new FileAdapter(new ConfigSection($config))); $this->assertInstanceOf(FileAdapter::class, $cache->getAdapter()); @@ -32,13 +33,13 @@ public function testCacheGetAdapter(): void public function testCacheCallingValidMethod(): void { - $params = [ + $config = [ 'prefix' => 'test', 'path' => base_dir() . DS . 'cache' . DS . 'data', 'ttl' => 60, ]; - $cache = new Cache(new FileAdapter($params)); + $cache = new Cache(new FileAdapter(new ConfigSection($config))); $this->assertFalse($cache->has('test')); @@ -47,13 +48,13 @@ public function testCacheCallingValidMethod(): void public function testCacheCallingInvalidMethod(): void { - $params = [ + $config = [ 'prefix' => 'test', 'path' => base_dir() . DS . 'cache' . DS . 'data', 'ttl' => 60, ]; - $cache = new Cache(new FileAdapter($params)); + $cache = new Cache(new FileAdapter(new ConfigSection($config))); $this->expectException(CacheException::class); diff --git a/tests/Unit/Cache/Factories/CacheFactoryTest.php b/tests/Unit/Cache/Factories/CacheFactoryTest.php index ef6dbf3e2..05ad55d80 100644 --- a/tests/Unit/Cache/Factories/CacheFactoryTest.php +++ b/tests/Unit/Cache/Factories/CacheFactoryTest.php @@ -2,6 +2,7 @@ namespace Quantum\Tests\Unit\Cache\Factories; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Cache\Exceptions\CacheException; use Quantum\Cache\Adapters\MemcachedAdapter; use Quantum\Cache\Adapters\DatabaseAdapter; @@ -10,6 +11,7 @@ use Quantum\Cache\Adapters\FileAdapter; use Quantum\Tests\Unit\AppTestCase; use Quantum\Cache\Enums\CacheType; +use Quantum\Config\Setup; use Quantum\Cache\Cache; use Quantum\Di\Di; @@ -64,6 +66,48 @@ public function testCacheFactoryRedisAdapter(): void $this->assertInstanceOf(RedisAdapter::class, $cache->getAdapter()); } + public function testCacheFactoryReadsTheTtlGivenAsText(): void + { + $this->setCacheConfig('file.ttl', '600'); + + $cache = CacheFactory::get(CacheType::FILE); + + $this->assertTrue($cache->set('ttl_as_text', 'value')); + $this->assertSame('value', $cache->get('ttl_as_text')); + + $cache->delete('ttl_as_text'); + } + + public function testCacheFactoryRejectsAMissingTtl(): void + { + $this->setCacheConfig('file', ['prefix' => '', 'path' => base_dir() . DS . 'cache' . DS . 'data']); + + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `ttl` is missing.'); + + CacheFactory::get(CacheType::FILE); + } + + public function testCacheFactoryRejectsARedisPortThatIsNotANumber(): void + { + $this->setCacheConfig('redis.port', 'abc'); + + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `port` has the value `abc`, which is not a whole number.'); + + CacheFactory::get(CacheType::REDIS); + } + + public function testCacheFactoryRejectsAMemcachedPortThatIsNotANumber(): void + { + $this->setCacheConfig('memcached.port', 'abc'); + + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `port` has the value `abc`, which is not a whole number.'); + + CacheFactory::get(CacheType::MEMCACHED); + } + public function testCacheFactoryInvalidTypeAdapter(): void { $this->expectException(CacheException::class); @@ -90,4 +134,13 @@ private function resetCacheFactory(): void $factory = Di::get(CacheFactory::class); $this->setPrivateProperty($factory, 'instances', []); } + + private function setCacheConfig(string $key, mixed $value): void + { + if (!config()->has('cache')) { + config()->import(new Setup('config', 'cache')); + } + + config()->set('cache.' . $key, $value); + } } diff --git a/tests/Unit/Captcha/Adapters/HcaptchaAdapterTest.php b/tests/Unit/Captcha/Adapters/HcaptchaAdapterTest.php index 49d26e65a..7562caff0 100644 --- a/tests/Unit/Captcha/Adapters/HcaptchaAdapterTest.php +++ b/tests/Unit/Captcha/Adapters/HcaptchaAdapterTest.php @@ -25,7 +25,7 @@ public function setUp(): void $this->httpClientMock = Mockery::mock(HttpClient::class); - $this->adapter = new HcaptchaAdapter(config()->get('captcha.hcaptcha'), $this->httpClientMock); + $this->adapter = new HcaptchaAdapter(config()->section('captcha.hcaptcha'), $this->httpClientMock); } public function tearDown(): void diff --git a/tests/Unit/Captcha/Adapters/RecaptchaAdapterTest.php b/tests/Unit/Captcha/Adapters/RecaptchaAdapterTest.php index 793dc6a49..bae8bc4d8 100644 --- a/tests/Unit/Captcha/Adapters/RecaptchaAdapterTest.php +++ b/tests/Unit/Captcha/Adapters/RecaptchaAdapterTest.php @@ -26,7 +26,7 @@ public function setUp(): void $this->httpClientMock = Mockery::mock(HttpClient::class); - $this->adapter = new RecaptchaAdapter(config()->get('captcha.recaptcha'), $this->httpClientMock); + $this->adapter = new RecaptchaAdapter(config()->section('captcha.recaptcha'), $this->httpClientMock); } public function tearDown(): void diff --git a/tests/Unit/Captcha/CaptchaTest.php b/tests/Unit/Captcha/CaptchaTest.php index 4edf5f2dd..15de312d8 100644 --- a/tests/Unit/Captcha/CaptchaTest.php +++ b/tests/Unit/Captcha/CaptchaTest.php @@ -7,6 +7,7 @@ use Quantum\Captcha\Adapters\RecaptchaAdapter; use Quantum\Tests\Unit\AppTestCase; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; use Quantum\Captcha\Captcha; class CaptchaTest extends AppTestCase @@ -18,13 +19,13 @@ public function setUp(): void public function testCaptchaGetAdapter(): void { - $params = [ + $config = [ 'type' => 'visible', 'secret_key' => '0xE1a02fB374Bf2', 'site_key' => '07737dfc-abfa-66ac44365d0c', ]; - $captcha = new Captcha(new RecaptchaAdapter($params, new HttpClient())); + $captcha = new Captcha(new RecaptchaAdapter(new ConfigSection($config), new HttpClient())); $this->assertInstanceOf(RecaptchaAdapter::class, $captcha->getAdapter()); @@ -33,26 +34,26 @@ public function testCaptchaGetAdapter(): void public function testCaptchaCallingValidMethod(): void { - $params = [ + $config = [ 'type' => 'visible', 'secret_key' => '0xE1a02fB374Bf2', 'site_key' => '07737dfc-abfa-66ac44365d0c', ]; - $captcha = new Captcha(new RecaptchaAdapter($params, new HttpClient())); + $captcha = new Captcha(new RecaptchaAdapter(new ConfigSection($config), new HttpClient())); $this->assertEquals('visible', $captcha->getType()); } public function testCacheCallingInvalidMethod(): void { - $params = [ + $config = [ 'type' => 'visible', 'secret_key' => '0xE1a02fB374Bf2', 'site_key' => '07737dfc-abfa-66ac44365d0c', ]; - $captcha = new Captcha(new RecaptchaAdapter($params, new HttpClient())); + $captcha = new Captcha(new RecaptchaAdapter(new ConfigSection($config), new HttpClient())); $this->expectException(CaptchaException::class); diff --git a/tests/Unit/Captcha/Factories/CaptchaFactoryTest.php b/tests/Unit/Captcha/Factories/CaptchaFactoryTest.php index 3b3f34d55..5b6dec5a0 100644 --- a/tests/Unit/Captcha/Factories/CaptchaFactoryTest.php +++ b/tests/Unit/Captcha/Factories/CaptchaFactoryTest.php @@ -9,6 +9,7 @@ use Quantum\Captcha\Enums\CaptchaType; use Quantum\Tests\Unit\AppTestCase; use Quantum\Captcha\Captcha; +use Quantum\Config\Setup; use Quantum\Di\Di; class CaptchaFactoryTest extends AppTestCase @@ -65,6 +66,19 @@ public function testAuthFactoryReturnsSameInstance(): void $this->assertSame($captcha1, $captcha2); } + public function testCaptchaFactoryKeepsAMissingTypeAsNull(): void + { + if (!config()->has('captcha')) { + config()->import(new Setup('config', 'captcha')); + } + + config()->set('captcha.recaptcha', ['secret_key' => 'secret', 'site_key' => 'site']); + + $captcha = CaptchaFactory::get(CaptchaType::RECAPTCHA); + + $this->assertNull($captcha->getAdapter()->getType()); + } + private function resetCaptchaFactory(): void { if (!Di::isRegistered(CaptchaFactory::class)) { diff --git a/tests/Unit/Config/ConfigSectionTest.php b/tests/Unit/Config/ConfigSectionTest.php new file mode 100644 index 000000000..68b6c38f0 --- /dev/null +++ b/tests/Unit/Config/ConfigSectionTest.php @@ -0,0 +1,133 @@ + '127.0.0.1', 'prefix' => null]); + + $this->assertSame('127.0.0.1', $section->get('host')); + $this->assertNull($section->get('missing')); + $this->assertSame('localhost', $section->get('missing', 'localhost')); + $this->assertNull($section->get('prefix', 'cache_')); + } + + public function testGetReadsDotKeys(): void + { + $section = new ConfigSection(['cache' => ['enabled' => true, 'ttl' => 60]]); + + $this->assertSame(60, $section->get('cache.ttl')); + $this->assertSame(['enabled' => true, 'ttl' => 60], $section->get('cache')); + $this->assertNull($section->get('cache.prefix')); + } + + public function testHasReportsKeysThatExist(): void + { + $section = new ConfigSection(['cache' => ['ttl' => null]]); + + $this->assertTrue($section->has('cache')); + $this->assertTrue($section->has('cache.ttl')); + $this->assertFalse($section->has('cache.prefix')); + $this->assertFalse($section->has('missing')); + } + + public function testGetBoolReadsTheSection(): void + { + $section = new ConfigSection(['two_fa' => 'yes', 'cache' => ['enabled' => 'off'], 'empty' => null]); + + $this->assertTrue($section->getBool('two_fa')); + $this->assertFalse($section->getBool('cache.enabled', true)); + $this->assertTrue($section->getBool('empty', true)); + $this->assertTrue($section->getBool('missing', true)); + } + + public function testGetIntReadsTheSection(): void + { + $section = new ConfigSection(['port' => '6379', 'cache' => ['ttl' => 60], 'empty' => null]); + + $this->assertSame(6379, $section->getInt('port')); + $this->assertSame(60, $section->getInt('cache.ttl')); + $this->assertSame(25, $section->getInt('empty', 25)); + $this->assertSame(25, $section->getInt('missing', 25)); + } + + public function testGetIntThrowsForTextThatIsNotAWholeNumber(): void + { + $section = new ConfigSection(['port' => 'abc']); + + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `port` has the value `abc`, which is not a whole number.'); + + $section->getInt('port'); + } + + public function testAllReturnsTheWholeSection(): void + { + $data = ['cache' => false, 'debug' => true, 'nested' => ['a' => 1]]; + + $this->assertSame($data, (new ConfigSection($data))->all()); + $this->assertSame([], (new ConfigSection())->all()); + } + + public function testSectionCutsOutASmallerSection(): void + { + $section = new ConfigSection(['session' => ['remember_lifetime' => '3600'], 'two_fa' => true]); + + $sessionSection = $section->section('session'); + + $this->assertSame(['remember_lifetime' => '3600'], $sessionSection->all()); + $this->assertSame(3600, $sessionSection->getInt('remember_lifetime')); + $this->assertSame([], $section->section('two_fa')->all()); + $this->assertSame([], $section->section('missing')->all()); + } + + public function testSectionCannotBeChanged(): void + { + foreach (['set', 'delete', 'flush', 'load', 'import', 'importIfExists'] as $method) { + $this->assertFalse(method_exists(ConfigSection::class, $method), $method); + } + } + + public function testAllReturnsACopyOfNestedArrays(): void + { + $section = new ConfigSection(['redis' => ['options' => ['timeout' => 5]]]); + + $values = $section->all(); + $values['redis']['options']['timeout'] = 99; + + $this->assertSame(5, $section->get('redis.options.timeout')); + } + + public function testSectionReturnsACopyOfNestedArrays(): void + { + $section = new ConfigSection(['redis' => ['options' => ['timeout' => 5]]]); + + $redis = $section->section('redis'); + $values = $redis->all(); + $values['options']['timeout'] = 99; + + $this->assertSame(5, $redis->get('options.timeout')); + $this->assertSame(5, $section->get('redis.options.timeout')); + } + + public function testObjectsInASectionAreShared(): void + { + $handler = new stdClass(); + $handler->calls = 0; + + $section = new ConfigSection(['handler' => $handler]); + + $section->get('handler')->calls++; + + $this->assertSame($handler, $section->get('handler')); + $this->assertSame($handler, $section->all()['handler']); + $this->assertSame(1, $handler->calls); + } +} diff --git a/tests/Unit/Config/ConfigTest.php b/tests/Unit/Config/ConfigTest.php index 463e32601..cb48dc319 100644 --- a/tests/Unit/Config/ConfigTest.php +++ b/tests/Unit/Config/ConfigTest.php @@ -6,7 +6,7 @@ use Quantum\Transformer\Contracts\TransformerInterface; use Quantum\Config\Exceptions\ConfigException; use Quantum\Tests\Unit\AppTestCase; -use Dflydev\DotAccessData\Data; +use Quantum\Config\ConfigSection; use Quantum\Config\Config; use Quantum\Config\Setup; @@ -25,13 +25,12 @@ public function setUp(): void public function testConfigLoad(): void { - $this->assertEmpty($this->config->all()); + $this->assertSame([], $this->config->all()); $this->config->load(new Setup('config', 'app')); $this->assertNotEmpty($this->config->all()); - - $this->assertInstanceOf(Data::class, $this->config->all()); + $this->assertSame('Quantum PHP Framework', $this->config->get('name')); } public function testConfigImport(): void @@ -117,7 +116,7 @@ public function testNonModuleConfigIsResolvedFromApplicationBase(): void public function testImportIfExistsReturnsFalseWithoutChangingConfig(): void { $this->assertFalse($this->config->importIfExists(new Setup('config', 'missing_optional'))); - $this->assertNull($this->config->all()); + $this->assertSame([], $this->config->all()); } public function testImportIfExistsTreatsEmptyConfigAsPresent(): void @@ -213,6 +212,15 @@ public function testConfigSet(): void $this->assertEquals('Nested Value', $this->config->get('other.nested')); } + public function testSetWithADotKeyOnAnEmptyConfigNestsTheValue(): void + { + $this->config->set('cache.redis', ['port' => 6379]); + + $this->assertSame(6379, $this->config->get('cache.redis.port')); + $this->assertSame(['cache' => ['redis' => ['port' => 6379]]], $this->config->all()); + $this->assertSame(6379, $this->config->section('cache.redis')->getInt('port')); + } + public function testConfigDelete(): void { $this->config->import(new Setup('config', 'app')); @@ -237,7 +245,7 @@ public function testGetBoolReadsTrueValues(): void public function testGetBoolReadsFalseValues(): void { - foreach ([false, 0, '0', 'false', 'off', 'no', '', 'abc', []] as $value) { + foreach ([false, 0, '0', 'false', 'off', 'no', 'abc', []] as $value) { $this->config->set('flag', $value); $this->assertFalse($this->config->getBool('flag', true), var_export($value, true)); @@ -246,12 +254,29 @@ public function testGetBoolReadsFalseValues(): void public function testGetBoolReturnsDefaultForMissingOrNullKey(): void { - $this->assertFalse($this->config->getBool('missing')); $this->assertTrue($this->config->getBool('missing', true)); + $this->assertFalse($this->config->getBool('missing', false)); $this->config->set('flag', null); + $this->config->set('empty_flag', ''); $this->assertTrue($this->config->getBool('flag', true)); + $this->assertTrue($this->config->getBool('empty_flag', true)); + } + + public function testGetBoolWithoutADefaultRequiresTheKey(): void + { + $this->config->set('flag', null); + $this->config->set('empty_flag', ''); + + foreach (['missing', 'flag', 'empty_flag'] as $key) { + try { + $this->config->getBool($key); + $this->fail('No exception for ' . $key); + } catch (ConfigException $e) { + $this->assertSame('The config key `' . $key . '` is missing.', $e->getMessage()); + } + } } public function testGetBoolReadsNestedKey(): void @@ -273,17 +298,34 @@ public function testGetIntReadsWholeNumbers(): void public function testGetIntReturnsDefaultForMissingOrNullKey(): void { - $this->assertSame(0, $this->config->getInt('missing')); $this->assertSame(1000, $this->config->getInt('missing', 1000)); + $this->assertSame(0, $this->config->getInt('missing', 0)); $this->config->set('number', null); + $this->config->set('empty_number', ''); $this->assertSame(1000, $this->config->getInt('number', 1000)); + $this->assertSame(25, $this->config->getInt('empty_number', 25)); + } + + public function testGetIntWithoutADefaultRequiresTheKey(): void + { + $this->config->set('number', null); + $this->config->set('empty_number', ''); + + foreach (['missing', 'number', 'empty_number'] as $key) { + try { + $this->config->getInt($key); + $this->fail('No exception for ' . $key); + } catch (ConfigException $e) { + $this->assertSame('The config key `' . $key . '` is missing.', $e->getMessage()); + } + } } public function testGetIntThrowsForTextThatIsNotAWholeNumber(): void { - foreach (['abc', '1.5', '', '12abc', 1.5, []] as $value) { + foreach (['abc', '1.5', ' ', '12abc', 1.5, []] as $value) { $this->config->set('number', $value); try { @@ -303,6 +345,50 @@ public function testGetRawValueIsNotAffectedByTypedReaders(): void $this->assertSame('587', $this->config->get('number')); } + public function testSectionReturnsTheSliceOfTheKey(): void + { + $this->config->set('cache', ['redis' => ['host' => '127.0.0.1', 'port' => '6379']]); + + $section = $this->config->section('cache.redis'); + + $this->assertInstanceOf(ConfigSection::class, $section); + $this->assertNotInstanceOf(Config::class, $section); + $this->assertSame(['host' => '127.0.0.1', 'port' => '6379'], $section->all()); + $this->assertSame(6379, $section->getInt('port')); + } + + public function testSectionOfAMissingKeyIsEmpty(): void + { + $this->assertSame([], $this->config->section('cache.redis')->all()); + } + + public function testSectionOfAValueThatIsNotAnArrayIsEmpty(): void + { + $this->config->set('cache', ['default' => 'redis']); + + $this->assertSame([], $this->config->section('cache.default')->all()); + } + + public function testSectionKeepsTheValuesItWasCreatedWith(): void + { + $this->config->set('cache', ['redis' => ['port' => 6379]]); + + $section = $this->config->section('cache.redis'); + + $this->config->set('cache.redis.port', 6380); + + $this->assertSame(6379, $section->getInt('port')); + } + + public function testAllReturnsAllValues(): void + { + $this->assertSame([], $this->config->all()); + + $this->config->set('cache', ['default' => 'redis']); + + $this->assertSame(['cache' => ['default' => 'redis']], $this->config->all()); + } + public function testConfigFlush(): void { $this->config->import(new Setup('config', 'app')); @@ -311,6 +397,6 @@ public function testConfigFlush(): void $this->config->flush(); - $this->assertEmpty($this->config->all()); + $this->assertSame([], $this->config->all()); } } diff --git a/tests/Unit/Console/CommandRegistrarTest.php b/tests/Unit/Console/CommandRegistrarTest.php index 6d489750b..aafa40bab 100644 --- a/tests/Unit/Console/CommandRegistrarTest.php +++ b/tests/Unit/Console/CommandRegistrarTest.php @@ -96,6 +96,6 @@ public function testCommandRegistrarRegistersTheCoreCommandsWithoutLoadingTheEnv $this->assertTrue($this->application->has('core:env')); $this->assertFalse(Di::has(Environment::class)); - $this->assertNull(config()->all()); + $this->assertSame([], config()->all()); } } diff --git a/tests/Unit/Lang/Adapters/DeepLAdapterTest.php b/tests/Unit/Lang/Adapters/DeepLAdapterTest.php index e3ef1af14..f326caa4b 100644 --- a/tests/Unit/Lang/Adapters/DeepLAdapterTest.php +++ b/tests/Unit/Lang/Adapters/DeepLAdapterTest.php @@ -3,10 +3,12 @@ namespace Quantum\Tests\Unit\Lang\Adapters; use Quantum\Tests\Unit\Storage\HttpClientTestCase; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Lang\Exceptions\LangException; use Quantum\Lang\Adapters\DeepLAdapter; use Quantum\Tests\Unit\AppTestCase; use Quantum\HttpClient\HttpClient; +use Quantum\Config\ConfigSection; use Mockery; class DeepLAdapterTest extends AppTestCase @@ -38,7 +40,7 @@ public function testDeepLAdapterReturnsProviderTranslationAndCachesIt(): void ], ]; - $adapter = new DeepLAdapter('es', $this->getParams(), $this->mockHttpClient()); + $adapter = new DeepLAdapter('es', new ConfigSection($this->getConfig()), $this->mockHttpClient()); $this->assertEquals('Hola', $adapter->get('Hello')); $this->assertSame(DeepLAdapter::TIMEOUT, $this->options[$this->url][CURLOPT_TIMEOUT]); @@ -52,21 +54,46 @@ public function testDeepLAdapterReturnsCachedTranslationWithoutProviderCall(): v ], ]; - $firstAdapter = new DeepLAdapter('es', $this->getParams(), $this->mockHttpClient()); + $firstAdapter = new DeepLAdapter('es', new ConfigSection($this->getConfig()), $this->mockHttpClient()); $this->assertEquals('Hola', $firstAdapter->get('Hello')); $httpClientMock = Mockery::mock(HttpClient::class); $httpClientMock->shouldNotReceive('createRequest'); - $secondAdapter = new DeepLAdapter('es', $this->getParams(), $httpClientMock); + $secondAdapter = new DeepLAdapter('es', new ConfigSection($this->getConfig()), $httpClientMock); $this->assertEquals('Hola', $secondAdapter->get('Hello')); } + public function testDeepLAdapterReadsTheCacheSettingsGivenAsText(): void + { + $this->assertTranslationIsCached($this->getConfig(['cache' => ['enabled' => 'yes', 'ttl' => '3600']])); + } + + public function testDeepLAdapterCachesWithTheDefaultTtlWhenTheTtlIsNotSet(): void + { + $config = $this->getConfig(); + unset($config['cache']['ttl']); + + $this->assertTranslationIsCached($config); + } + + public function testDeepLAdapterRejectsACacheTtlThatIsNotANumber(): void + { + $this->currentResponse = (object) ['translations' => [(object) ['text' => 'Hola']]]; + + $adapter = new DeepLAdapter('es', new ConfigSection($this->getConfig(['cache' => ['ttl' => 'abc']])), $this->mockHttpClient()); + + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `cache.ttl` has the value `abc`, which is not a whole number.'); + + $adapter->get('Hello'); + } + public function testDeepLAdapterThrowsIfAuthKeyIsMissing(): void { - $adapter = new DeepLAdapter('es', $this->getParams(['auth_key' => '']), $this->mockHttpClient()); + $adapter = new DeepLAdapter('es', new ConfigSection($this->getConfig(['auth_key' => ''])), $this->mockHttpClient()); $this->expectException(LangException::class); $this->expectExceptionMessage('Could not load config `lang.deepl.auth_key` properly.'); @@ -78,7 +105,7 @@ public function testDeepLAdapterThrowsIfProviderResponseIsInvalid(): void { $this->currentResponse = (object) []; - $adapter = new DeepLAdapter('es', $this->getParams(), $this->mockHttpClient()); + $adapter = new DeepLAdapter('es', new ConfigSection($this->getConfig()), $this->mockHttpClient()); $this->expectException(LangException::class); $this->expectExceptionMessage('The provider `DeepL` returned an invalid translation response.'); @@ -88,7 +115,7 @@ public function testDeepLAdapterThrowsIfProviderResponseIsInvalid(): void public function testDeepLAdapterThrowsIfPayloadCannotBeEncoded(): void { - $adapter = new DeepLAdapter('es', $this->getParams(), $this->mockHttpClient()); + $adapter = new DeepLAdapter('es', new ConfigSection($this->getConfig()), $this->mockHttpClient()); $this->expectException(LangException::class); $this->expectExceptionMessage('The translation payload could not be encoded for `DeepL`.'); @@ -101,7 +128,7 @@ public function testDeepLAdapterReturnsEmptyStringWithoutProviderCall(): void $httpClientMock = Mockery::mock(HttpClient::class); $httpClientMock->shouldNotReceive('createRequest'); - $adapter = new DeepLAdapter('es', $this->getParams(), $httpClientMock); + $adapter = new DeepLAdapter('es', new ConfigSection($this->getConfig()), $httpClientMock); $this->assertSame('', $adapter->get('')); } @@ -114,10 +141,10 @@ public function testDeepLAdapterTranslatesResolvedSourceCatalogText(): void ], ]; - $adapter = new DeepLAdapter('es', $this->getParams([ + $adapter = new DeepLAdapter('es', new ConfigSection($this->getConfig([ 'use_source_catalog' => true, 'source_locale' => 'en', - ]), $this->mockHttpClient()); + ])), $this->mockHttpClient()); $this->assertSame('Hola', $adapter->get('custom.test')); $this->assertJsonStringEqualsJsonString( @@ -135,10 +162,10 @@ public function testDeepLAdapterReturnsResolvedSourceTextWithoutProviderCallWhen $httpClientMock = Mockery::mock(HttpClient::class); $httpClientMock->shouldNotReceive('createRequest'); - $adapter = new DeepLAdapter('en', $this->getParams([ + $adapter = new DeepLAdapter('en', new ConfigSection($this->getConfig([ 'use_source_catalog' => true, 'source_locale' => 'en', - ]), $httpClientMock); + ])), $httpClientMock); $this->assertSame('Testing', $adapter->get('custom.test')); } @@ -148,20 +175,20 @@ public function testDeepLAdapterReturnsKeyWithoutProviderCallWhenSourceCatalogMi $httpClientMock = Mockery::mock(HttpClient::class); $httpClientMock->shouldNotReceive('createRequest'); - $adapter = new DeepLAdapter('es', $this->getParams([ + $adapter = new DeepLAdapter('es', new ConfigSection($this->getConfig([ 'use_source_catalog' => true, 'source_locale' => 'en', - ]), $httpClientMock); + ])), $httpClientMock); $this->assertSame('custom.missing', $adapter->get('custom.missing')); } public function testDeepLAdapterThrowsIfSourceCatalogLocaleIsMissing(): void { - $adapter = new DeepLAdapter('es', $this->getParams([ + $adapter = new DeepLAdapter('es', new ConfigSection($this->getConfig([ 'use_source_catalog' => true, 'source_locale' => null, - ]), $this->mockHttpClient()); + ])), $this->mockHttpClient()); $this->expectException(LangException::class); $this->expectExceptionMessage('Could not load config `lang.deepl.source_locale` properly.'); @@ -173,7 +200,7 @@ public function testDeepLAdapterThrowsIfProviderRequestFails(): void { $this->currentErrors = ['timeout']; - $adapter = new DeepLAdapter('es', $this->getParams(), $this->mockHttpClient()); + $adapter = new DeepLAdapter('es', new ConfigSection($this->getConfig()), $this->mockHttpClient()); $this->expectException(LangException::class); $this->expectExceptionMessage('The translation request to `Quantum\\Lang\\Adapters\\DeepLAdapter` failed'); @@ -181,11 +208,26 @@ public function testDeepLAdapterThrowsIfProviderRequestFails(): void $adapter->get('Hello'); } + /** + * @param array $config + */ + private function assertTranslationIsCached(array $config): void + { + $this->currentResponse = (object) ['translations' => [(object) ['text' => 'Hola']]]; + + $this->assertEquals('Hola', (new DeepLAdapter('es', new ConfigSection($config), $this->mockHttpClient()))->get('Hello')); + + $httpClientMock = Mockery::mock(HttpClient::class); + $httpClientMock->shouldNotReceive('createRequest'); + + $this->assertEquals('Hola', (new DeepLAdapter('es', new ConfigSection($config), $httpClientMock))->get('Hello')); + } + /** * @param array $overrides * @return array */ - private function getParams(array $overrides = []): array + private function getConfig(array $overrides = []): array { return array_replace_recursive([ 'auth_key' => 'test-auth-key', diff --git a/tests/Unit/Lang/Adapters/GoogleTranslateAdapterTest.php b/tests/Unit/Lang/Adapters/GoogleTranslateAdapterTest.php index 1fac0fc0f..453cf4b32 100644 --- a/tests/Unit/Lang/Adapters/GoogleTranslateAdapterTest.php +++ b/tests/Unit/Lang/Adapters/GoogleTranslateAdapterTest.php @@ -7,6 +7,7 @@ use Quantum\Lang\Exceptions\LangException; use Quantum\HttpClient\HttpClient; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; use Mockery; class GoogleTranslateAdapterTest extends AppTestCase @@ -40,7 +41,7 @@ public function testGoogleTranslateAdapterReturnsProviderTranslationAndCachesIt( ], ]; - $adapter = new GoogleTranslateAdapter('es', $this->getParams(), $this->mockHttpClient()); + $adapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig()), $this->mockHttpClient()); $this->assertEquals('Hola', $adapter->get('Hello')); $this->assertStringContainsString('?key=test-api-key', $this->url); @@ -66,21 +67,21 @@ public function testGoogleTranslateAdapterReturnsCachedTranslationWithoutProvide ], ]; - $firstAdapter = new GoogleTranslateAdapter('es', $this->getParams(), $this->mockHttpClient()); + $firstAdapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig()), $this->mockHttpClient()); $this->assertEquals('Hola', $firstAdapter->get('Hello')); $httpClientMock = Mockery::mock(HttpClient::class); $httpClientMock->shouldNotReceive('createRequest'); - $secondAdapter = new GoogleTranslateAdapter('es', $this->getParams(), $httpClientMock); + $secondAdapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig()), $httpClientMock); $this->assertEquals('Hola', $secondAdapter->get('Hello')); } public function testGoogleTranslateAdapterThrowsIfApiKeyIsMissing(): void { - $adapter = new GoogleTranslateAdapter('es', $this->getParams(['api_key' => '']), $this->mockHttpClient()); + $adapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig(['api_key' => ''])), $this->mockHttpClient()); $this->expectException(LangException::class); $this->expectExceptionMessage('Could not load config `lang.google_translate.api_key` properly.'); @@ -92,7 +93,7 @@ public function testGoogleTranslateAdapterThrowsIfProviderResponseIsInvalid(): v { $this->currentResponse = (object) []; - $adapter = new GoogleTranslateAdapter('es', $this->getParams(), $this->mockHttpClient()); + $adapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig()), $this->mockHttpClient()); $this->expectException(LangException::class); $this->expectExceptionMessage('The provider `Google Translate` returned an invalid translation response.'); @@ -102,7 +103,7 @@ public function testGoogleTranslateAdapterThrowsIfProviderResponseIsInvalid(): v public function testGoogleTranslateAdapterThrowsIfPayloadCannotBeEncoded(): void { - $adapter = new GoogleTranslateAdapter('es', $this->getParams(), $this->mockHttpClient()); + $adapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig()), $this->mockHttpClient()); $this->expectException(LangException::class); $this->expectExceptionMessage('The translation payload could not be encoded for `Google Translate`.'); @@ -115,7 +116,7 @@ public function testGoogleTranslateAdapterReturnsEmptyStringWithoutProviderCall( $httpClientMock = Mockery::mock(HttpClient::class); $httpClientMock->shouldNotReceive('createRequest'); - $adapter = new GoogleTranslateAdapter('es', $this->getParams(), $httpClientMock); + $adapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig()), $httpClientMock); $this->assertSame('', $adapter->get('')); } @@ -130,10 +131,10 @@ public function testGoogleTranslateAdapterTranslatesResolvedSourceCatalogText(): ], ]; - $adapter = new GoogleTranslateAdapter('es', $this->getParams([ + $adapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig([ 'use_source_catalog' => true, 'source_locale' => 'en', - ]), $this->mockHttpClient()); + ])), $this->mockHttpClient()); $this->assertSame('Hola', $adapter->get('custom.test')); $this->assertJsonStringEqualsJsonString( @@ -152,10 +153,10 @@ public function testGoogleTranslateAdapterReturnsResolvedSourceTextWithoutProvid $httpClientMock = Mockery::mock(HttpClient::class); $httpClientMock->shouldNotReceive('createRequest'); - $adapter = new GoogleTranslateAdapter('en', $this->getParams([ + $adapter = new GoogleTranslateAdapter('en', new ConfigSection($this->getConfig([ 'use_source_catalog' => true, 'source_locale' => 'en', - ]), $httpClientMock); + ])), $httpClientMock); $this->assertSame('Testing', $adapter->get('custom.test')); } @@ -165,20 +166,20 @@ public function testGoogleTranslateAdapterReturnsKeyWithoutProviderCallWhenSourc $httpClientMock = Mockery::mock(HttpClient::class); $httpClientMock->shouldNotReceive('createRequest'); - $adapter = new GoogleTranslateAdapter('es', $this->getParams([ + $adapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig([ 'use_source_catalog' => true, 'source_locale' => 'en', - ]), $httpClientMock); + ])), $httpClientMock); $this->assertSame('custom.missing', $adapter->get('custom.missing')); } public function testGoogleTranslateAdapterThrowsIfSourceCatalogLocaleIsMissing(): void { - $adapter = new GoogleTranslateAdapter('es', $this->getParams([ + $adapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig([ 'use_source_catalog' => true, 'source_locale' => null, - ]), $this->mockHttpClient()); + ])), $this->mockHttpClient()); $this->expectException(LangException::class); $this->expectExceptionMessage('Could not load config `lang.google_translate.source_locale` properly.'); @@ -190,7 +191,7 @@ public function testGoogleTranslateAdapterThrowsIfProviderRequestFails(): void { $this->currentErrors = ['timeout']; - $adapter = new GoogleTranslateAdapter('es', $this->getParams(), $this->mockHttpClient()); + $adapter = new GoogleTranslateAdapter('es', new ConfigSection($this->getConfig()), $this->mockHttpClient()); $this->expectException(LangException::class); $this->expectExceptionMessage('The translation request to `Quantum\\Lang\\Adapters\\GoogleTranslateAdapter` failed'); @@ -202,7 +203,7 @@ public function testGoogleTranslateAdapterThrowsIfProviderRequestFails(): void * @param array $overrides * @return array */ - private function getParams(array $overrides = []): array + private function getConfig(array $overrides = []): array { return array_replace_recursive([ 'api_key' => 'test-api-key', diff --git a/tests/Unit/Logger/Adapters/DailyAdapterTest.php b/tests/Unit/Logger/Adapters/DailyAdapterTest.php index 91ec9ccd1..fc0626dfa 100644 --- a/tests/Unit/Logger/Adapters/DailyAdapterTest.php +++ b/tests/Unit/Logger/Adapters/DailyAdapterTest.php @@ -5,6 +5,7 @@ use Quantum\Logger\Exceptions\LoggerException; use Quantum\Logger\Adapters\DailyAdapter; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; class DailyAdapterTest extends AppTestCase { @@ -14,9 +15,9 @@ public function setUp(): void { parent::setUp(); - $this->adapter = new DailyAdapter([ + $this->adapter = new DailyAdapter(new ConfigSection([ 'path' => base_dir() . DS . 'logs', - ]); + ])); } public function testDailyAdapterInstance(): void @@ -28,9 +29,9 @@ public function testDailyAdapterConstructorThrowsExceptionForInvalidPath(): void { $this->expectException(LoggerException::class); - new DailyAdapter([ + new DailyAdapter(new ConfigSection([ 'path' => base_dir() . DS . 'invalid_path', - ]); + ])); } public function testDailyAdapterReportWritesToFile(): void diff --git a/tests/Unit/Logger/Adapters/SingleAdapterTest.php b/tests/Unit/Logger/Adapters/SingleAdapterTest.php index f8ca000d6..5ba50ae77 100644 --- a/tests/Unit/Logger/Adapters/SingleAdapterTest.php +++ b/tests/Unit/Logger/Adapters/SingleAdapterTest.php @@ -5,6 +5,7 @@ use Quantum\Logger\Exceptions\LoggerException; use Quantum\Logger\Adapters\SingleAdapter; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; use RuntimeException; use Stringable; @@ -26,9 +27,9 @@ public function setUp(): void $this->fs->remove($this->logFile); } - $this->adapter = new SingleAdapter([ + $this->adapter = new SingleAdapter(new ConfigSection([ 'path' => $this->logFile, - ]); + ])); } public function tearDown(): void @@ -49,9 +50,9 @@ public function testSingleAdapterConstructorThrowsExceptionForInvalidPath(): voi { $this->expectException(LoggerException::class); - new SingleAdapter([ + new SingleAdapter(new ConfigSection([ 'path' => base_dir() . DS . 'invalid_path', - ]); + ])); } public function testSingleAdapterReportWritesToFile(): void diff --git a/tests/Unit/Mailer/Adapters/MailerAdapterTraitTest.php b/tests/Unit/Mailer/Adapters/MailerAdapterTraitTest.php index 147dce1b8..9a690838f 100644 --- a/tests/Unit/Mailer/Adapters/MailerAdapterTraitTest.php +++ b/tests/Unit/Mailer/Adapters/MailerAdapterTraitTest.php @@ -7,6 +7,7 @@ use Quantum\Mailer\Adapters\SmtpAdapter; use Quantum\Mailer\Traits\MailerTrait; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; use Quantum\Config\Setup; class MailerAdapterTraitTest extends AppTestCase @@ -21,7 +22,7 @@ public function setUp(): void config()->import(new Setup('config', 'mailer')); } - $this->adapter = new SmtpAdapter(config()->get('mailer.smtp')); + $this->adapter = new SmtpAdapter(config()->section('mailer.smtp')); } public function testMailerTraitSetGetFrom(): void @@ -90,7 +91,7 @@ public function testSetGetBody(): void public function testMailerTraitGetMessageId(): void { - $adapter = new SendinblueAdapter(['api_key' => 'xxx11122233']); + $adapter = new SendinblueAdapter(new ConfigSection(['api_key' => 'xxx11122233'])); $this->assertIsString($adapter->getMessageId()); } diff --git a/tests/Unit/Mailer/Adapters/MailgunAdapterTest.php b/tests/Unit/Mailer/Adapters/MailgunAdapterTest.php index e2cf78e6f..f7bf4e460 100644 --- a/tests/Unit/Mailer/Adapters/MailgunAdapterTest.php +++ b/tests/Unit/Mailer/Adapters/MailgunAdapterTest.php @@ -5,6 +5,7 @@ use Quantum\Tests\Unit\Mailer\MailerTestCase; use Quantum\Mailer\Contracts\MailerInterface; use Quantum\Mailer\Adapters\MailgunAdapter; +use Quantum\Config\ConfigSection; class MailgunAdapterTest extends MailerTestCase { @@ -17,7 +18,7 @@ public function setUp(): void 'domain' => 'mailgun.example.com', ]; - $this->adapter = new MailgunAdapter($config); + $this->adapter = new MailgunAdapter(new ConfigSection($config)); } public function testMailgunAdapterInstance(): void diff --git a/tests/Unit/Mailer/Adapters/MandrillAdapterTest.php b/tests/Unit/Mailer/Adapters/MandrillAdapterTest.php index 9a9099e8c..f762e6ddb 100644 --- a/tests/Unit/Mailer/Adapters/MandrillAdapterTest.php +++ b/tests/Unit/Mailer/Adapters/MandrillAdapterTest.php @@ -5,6 +5,7 @@ use Quantum\Tests\Unit\Mailer\MailerTestCase; use Quantum\Mailer\Contracts\MailerInterface; use Quantum\Mailer\Adapters\MandrillAdapter; +use Quantum\Config\ConfigSection; class MandrillAdapterTest extends MailerTestCase { @@ -12,7 +13,7 @@ public function setUp(): void { parent::setUp(); - $this->adapter = new MandrillAdapter(['api_key' => 'xxx111222333']); + $this->adapter = new MandrillAdapter(new ConfigSection(['api_key' => 'xxx111222333'])); } public function testMandrillAdapterInstance(): void diff --git a/tests/Unit/Mailer/Adapters/ResendAdapterTest.php b/tests/Unit/Mailer/Adapters/ResendAdapterTest.php index 467f70a76..5822e65ce 100644 --- a/tests/Unit/Mailer/Adapters/ResendAdapterTest.php +++ b/tests/Unit/Mailer/Adapters/ResendAdapterTest.php @@ -5,6 +5,7 @@ use Quantum\Tests\Unit\Mailer\MailerTestCase; use Quantum\Mailer\Contracts\MailerInterface; use Quantum\Mailer\Adapters\ResendAdapter; +use Quantum\Config\ConfigSection; class ResendAdapterTest extends MailerTestCase { @@ -12,7 +13,7 @@ public function setUp(): void { parent::setUp(); - $this->adapter = new ResendAdapter(['api_key' => 'xxx111222333']); + $this->adapter = new ResendAdapter(new ConfigSection(['api_key' => 'xxx111222333'])); } public function testResendAdapterInstance(): void diff --git a/tests/Unit/Mailer/Adapters/SendgridAdapterTest.php b/tests/Unit/Mailer/Adapters/SendgridAdapterTest.php index 635a88432..5dff5513e 100644 --- a/tests/Unit/Mailer/Adapters/SendgridAdapterTest.php +++ b/tests/Unit/Mailer/Adapters/SendgridAdapterTest.php @@ -5,6 +5,7 @@ use Quantum\Tests\Unit\Mailer\MailerTestCase; use Quantum\Mailer\Contracts\MailerInterface; use Quantum\Mailer\Adapters\SendgridAdapter; +use Quantum\Config\ConfigSection; class SendgridAdapterTest extends MailerTestCase { @@ -12,7 +13,7 @@ public function setUp(): void { parent::setUp(); - $this->adapter = new SendgridAdapter(['api_key' => 'xxx111222333']); + $this->adapter = new SendgridAdapter(new ConfigSection(['api_key' => 'xxx111222333'])); } public function testSendgridAdapterInstance(): void diff --git a/tests/Unit/Mailer/Adapters/SendinblueAdapterTest.php b/tests/Unit/Mailer/Adapters/SendinblueAdapterTest.php index 0a066d5c8..cc57a0367 100644 --- a/tests/Unit/Mailer/Adapters/SendinblueAdapterTest.php +++ b/tests/Unit/Mailer/Adapters/SendinblueAdapterTest.php @@ -5,6 +5,7 @@ use Quantum\Mailer\Adapters\SendinblueAdapter; use Quantum\Tests\Unit\Mailer\MailerTestCase; use Quantum\Mailer\Contracts\MailerInterface; +use Quantum\Config\ConfigSection; class SendinblueAdapterTest extends MailerTestCase { @@ -12,7 +13,7 @@ public function setUp(): void { parent::setUp(); - $this->adapter = new SendinblueAdapter(['api_key' => 'xxx111222333']); + $this->adapter = new SendinblueAdapter(new ConfigSection(['api_key' => 'xxx111222333'])); } public function testSendinblueAdapterInstance(): void diff --git a/tests/Unit/Mailer/Adapters/SmtpAdapterTest.php b/tests/Unit/Mailer/Adapters/SmtpAdapterTest.php index 873569386..2c4ead627 100644 --- a/tests/Unit/Mailer/Adapters/SmtpAdapterTest.php +++ b/tests/Unit/Mailer/Adapters/SmtpAdapterTest.php @@ -7,6 +7,7 @@ use Quantum\Mailer\Adapters\SmtpAdapter; use PHPMailer\PHPMailer\Exception; use PHPMailer\PHPMailer\PHPMailer; +use Quantum\Config\ConfigSection; use PHPMailer\PHPMailer\SMTP; use Quantum\Config\Setup; @@ -20,7 +21,7 @@ public function setUp(): void config()->import(new Setup('config', 'mailer')); } - $this->adapter = new SmtpAdapter(config()->get('mailer.smtp')); + $this->adapter = new SmtpAdapter(config()->section('mailer.smtp')); } public function testSmtpAdapterInstance(): void @@ -107,7 +108,7 @@ public function testSmtpAdapterKeepsTheSmtpExchangeInDebugMode(): void { config()->set('app.debug', true); - $adapter = new SmtpAdapter(config()->get('mailer.smtp')); + $adapter = new SmtpAdapter(config()->section('mailer.smtp')); $debugOutput = $this->getPrivateProperty($adapter, 'mailer')->Debugoutput; @@ -121,7 +122,7 @@ public function testSmtpAdapterCutsTheSmtpExchangeToItsLastLinesAtTheNextSend(): config()->set('app.debug', true); config()->set('mailer.transport_log_limit', 2); - $adapter = new SmtpAdapter(config()->get('mailer.smtp')); + $adapter = new SmtpAdapter(config()->section('mailer.smtp')); $debugOutput = $this->getPrivateProperty($adapter, 'mailer')->Debugoutput; @@ -147,7 +148,7 @@ public function testSmtpAdapterKeepsTheSmtpExchangeOfAFailedSendAndCutsItAtTheNe config()->set('mailer.mail_trap', false); config()->set('mailer.transport_log_limit', 1); - $adapter = new SmtpAdapter(config()->get('mailer.smtp')); + $adapter = new SmtpAdapter(config()->section('mailer.smtp')); $failingMailer = new class (true) extends PHPMailer { public int $sends = 0; @@ -189,7 +190,7 @@ public function testSmtpAdapterSendsThroughTheTransportWhenMailTrapIsTheTextFals { config()->set('mailer.mail_trap', 'false'); - $adapter = new SmtpAdapter(config()->get('mailer.smtp')); + $adapter = new SmtpAdapter(config()->section('mailer.smtp')); $this->setPrivateProperty($adapter, 'mailer', new class (true) extends PHPMailer { public function send() @@ -224,7 +225,7 @@ public function testSmtpAdapterKeepsNoSmtpExchangeOutsideDebugMode(): void { config()->set('app.debug', false); - $adapter = new SmtpAdapter(config()->get('mailer.smtp')); + $adapter = new SmtpAdapter(config()->section('mailer.smtp')); $this->assertSame(SMTP::DEBUG_OFF, $this->getPrivateProperty($adapter, 'mailer')->SMTPDebug); } @@ -241,4 +242,15 @@ public function testSmtpAdapterSend(): void $this->assertTrue($this->adapter->send()); } + + public function testSmtpAdapterUsesPort25WhenThePortIsMissingOrEmpty(): void + { + $config = ['host' => '127.0.0.1', 'secure' => 'ssl', 'username' => 'user', 'password' => 'secret']; + + foreach ([$config, $config + ['port' => '']] as $values) { + $adapter = new SmtpAdapter(new ConfigSection($values)); + + $this->assertSame(25, $this->getPrivateProperty($adapter, 'mailer')->Port); + } + } } diff --git a/tests/Unit/Mailer/Factories/MailerFactoryTest.php b/tests/Unit/Mailer/Factories/MailerFactoryTest.php index c3aff5f64..95975ceae 100644 --- a/tests/Unit/Mailer/Factories/MailerFactoryTest.php +++ b/tests/Unit/Mailer/Factories/MailerFactoryTest.php @@ -3,6 +3,7 @@ namespace Quantum\Tests\Unit\Mailer\Factories; use Quantum\Mailer\Exceptions\MailerException; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Mailer\Adapters\SendinblueAdapter; use Quantum\Mailer\Adapters\MandrillAdapter; use Quantum\Mailer\Adapters\SendgridAdapter; @@ -102,6 +103,25 @@ public function testMailerFactoryReturnsSameInstance(): void $this->assertSame($mailer1, $mailer2); } + public function testMailerFactoryReadsTheSmtpPortGivenAsText(): void + { + config()->set('mailer.smtp.port', '587'); + + $adapter = MailerFactory::get(MailerType::SMTP)->getAdapter(); + + $this->assertSame(587, $this->getPrivateProperty($adapter, 'mailer')->Port); + } + + public function testMailerFactoryRejectsAnSmtpPortThatIsNotANumber(): void + { + config()->set('mailer.smtp.port', 'abc'); + + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `port` has the value `abc`, which is not a whole number.'); + + MailerFactory::get(MailerType::SMTP); + } + private function resetMailerFactory(): void { if (!Di::isRegistered(MailerFactory::class)) { diff --git a/tests/Unit/Mailer/MailerTest.php b/tests/Unit/Mailer/MailerTest.php index 128248616..01b0a0ed4 100644 --- a/tests/Unit/Mailer/MailerTest.php +++ b/tests/Unit/Mailer/MailerTest.php @@ -12,6 +12,7 @@ use Quantum\Mailer\Adapters\ResendAdapter; use Quantum\Mailer\Adapters\SmtpAdapter; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; use Quantum\Mailer\Mailer; use Quantum\Config\Setup; use ReflectionMethod; @@ -29,7 +30,7 @@ public function setUp(): void public function testMailerGetAdapter(): void { - $mailer = new Mailer(new SmtpAdapter(config()->get('mailer.smtp'))); + $mailer = new Mailer(new SmtpAdapter(config()->section('mailer.smtp'))); $this->assertInstanceOf(SmtpAdapter::class, $mailer->getAdapter()); @@ -38,7 +39,7 @@ public function testMailerGetAdapter(): void public function testMailerCallingValidMethod(): void { - $mailer = new Mailer(new SmtpAdapter(config()->get('mailer.smtp'))); + $mailer = new Mailer(new SmtpAdapter(config()->section('mailer.smtp'))); $mailer->setSubject('Welcome'); @@ -47,7 +48,7 @@ public function testMailerCallingValidMethod(): void public function testMailerCallingInvalidMethod(): void { - $mailer = new Mailer(new SmtpAdapter(config()->get('mailer.smtp'))); + $mailer = new Mailer(new SmtpAdapter(config()->section('mailer.smtp'))); $this->expectException(MailerException::class); @@ -57,9 +58,9 @@ public function testMailerCallingInvalidMethod(): void } #[DataProvider('httpAdapterProvider')] - public function testHttpAdapterGetTransportErrorsReturnsArray(string $adapterClass, array $params): void + public function testHttpAdapterGetTransportErrorsReturnsArray(string $adapterClass, array $config): void { - $adapter = new $adapterClass($params); + $adapter = new $adapterClass(new ConfigSection($config)); $httpClient = $this->getPrivateProperty($adapter, 'httpClient'); $httpClient->createRequest('http://localhost'); diff --git a/tests/Unit/RateLimit/Adapters/FileRateLimitAdapterTest.php b/tests/Unit/RateLimit/Adapters/FileRateLimitAdapterTest.php index 5363bf355..0edad533b 100644 --- a/tests/Unit/RateLimit/Adapters/FileRateLimitAdapterTest.php +++ b/tests/Unit/RateLimit/Adapters/FileRateLimitAdapterTest.php @@ -4,6 +4,7 @@ use Quantum\RateLimit\Adapters\FileRateLimitAdapter; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; class FileRateLimitAdapterTest extends AppTestCase { @@ -33,11 +34,11 @@ public function tearDown(): void public function testFileAdapterHitAndResetFlow(): void { - $adapter = new FileRateLimitAdapter([ + $adapter = new FileRateLimitAdapter(new ConfigSection([ 'ttl' => 30, 'prefix' => 'test', 'path' => $this->rateLimitDir, - ]); + ])); $this->assertTrue($adapter->hit('k1', 2, 60)); $this->assertTrue($adapter->hit('k1', 2, 60)); @@ -49,11 +50,11 @@ public function testFileAdapterHitAndResetFlow(): void public function testFileAdapterRepeatedHitsRespectExactLimitBoundary(): void { - $adapter = new FileRateLimitAdapter([ + $adapter = new FileRateLimitAdapter(new ConfigSection([ 'ttl' => 30, 'prefix' => 'test', 'path' => $this->rateLimitDir, - ]); + ])); for ($i = 0; $i < 100; $i++) { $this->assertTrue($adapter->hit('boundary', 100, 60)); @@ -71,11 +72,11 @@ public function testFileAdapterCreatesStorageDirectoryWhenMissing(): void } try { - new FileRateLimitAdapter([ + new FileRateLimitAdapter(new ConfigSection([ 'ttl' => 30, 'prefix' => 'test', 'path' => $path, - ]); + ])); $this->assertTrue(fs()->isDirectory($path)); } finally { @@ -93,11 +94,11 @@ public function testFileAdapterCreatesMissingParentDirectories(): void deleteDirectoryWithFiles($root); try { - new FileRateLimitAdapter([ + new FileRateLimitAdapter(new ConfigSection([ 'ttl' => 30, 'prefix' => 'test', 'path' => $path, - ]); + ])); $this->assertTrue(fs()->isDirectory($path)); } finally { @@ -107,11 +108,11 @@ public function testFileAdapterCreatesMissingParentDirectories(): void public function testFileAdapterRetryAfterReturnsZeroForMissingOrInvalidState(): void { - $adapter = new FileRateLimitAdapter([ + $adapter = new FileRateLimitAdapter(new ConfigSection([ 'ttl' => 30, 'prefix' => 'test', 'path' => $this->rateLimitDir, - ]); + ])); $this->assertSame(0, $adapter->retryAfter('missing-key')); diff --git a/tests/Unit/RateLimit/Adapters/RedisRateLimitAdapterTest.php b/tests/Unit/RateLimit/Adapters/RedisRateLimitAdapterTest.php index 830e2d52f..c95ac1380 100644 --- a/tests/Unit/RateLimit/Adapters/RedisRateLimitAdapterTest.php +++ b/tests/Unit/RateLimit/Adapters/RedisRateLimitAdapterTest.php @@ -3,7 +3,9 @@ namespace Quantum\Tests\Unit\RateLimit\Adapters; use Quantum\RateLimit\Adapters\RedisRateLimitAdapter; +use Quantum\Config\Exceptions\ConfigException; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; class RedisRateLimitAdapterTest extends AppTestCase { @@ -13,11 +15,11 @@ public function setUp(): void { parent::setUp(); - $this->adapter = new RedisRateLimitAdapter([ + $this->adapter = new RedisRateLimitAdapter(new ConfigSection([ 'host' => '127.0.0.1', 'port' => 6379, 'ttl' => 30, - ]); + ])); } public function tearDown(): void @@ -29,11 +31,11 @@ public function tearDown(): void public function testRedisAdapterConnectsWithThePortAsText(): void { - $adapter = new RedisRateLimitAdapter([ + $adapter = new RedisRateLimitAdapter(new ConfigSection([ 'host' => '127.0.0.1', 'port' => '6379', 'ttl' => 30, - ]); + ])); $this->assertTrue($adapter->hit('k2', 5, 30)); } @@ -52,4 +54,20 @@ public function testRedisAdapterRetryAfterReturnsZeroForMissingKey(): void $this->adapter->reset('missing-key'); $this->assertSame(0, $this->adapter->retryAfter('missing-key')); } + + public function testRedisRateLimitAdapterRejectsAMissingTtl(): void + { + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `ttl` is missing.'); + + new RedisRateLimitAdapter(new ConfigSection(['prefix' => 'test', 'host' => '127.0.0.1', 'port' => 6379])); + } + + public function testRedisRateLimitAdapterRejectsAMissingPort(): void + { + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `port` is missing.'); + + new RedisRateLimitAdapter(new ConfigSection(['prefix' => 'test', 'host' => '127.0.0.1', 'ttl' => 60])); + } } diff --git a/tests/Unit/RateLimit/Factories/RateLimiterFactoryTest.php b/tests/Unit/RateLimit/Factories/RateLimiterFactoryTest.php index 731092861..0d8e6791c 100644 --- a/tests/Unit/RateLimit/Factories/RateLimiterFactoryTest.php +++ b/tests/Unit/RateLimit/Factories/RateLimiterFactoryTest.php @@ -6,9 +6,11 @@ use Quantum\RateLimit\Exceptions\RateLimitException; use Quantum\RateLimit\Adapters\FileRateLimitAdapter; use Quantum\RateLimit\Factories\RateLimiterFactory; +use Quantum\Config\Exceptions\ConfigException; use Quantum\RateLimit\Enums\RateLimitType; use Quantum\Tests\Unit\AppTestCase; use Quantum\RateLimit\RateLimiter; +use Quantum\Config\Setup; use Quantum\Di\Di; class RateLimiterFactoryTest extends AppTestCase @@ -37,6 +39,35 @@ public function testRateLimiterFactoryRedisAdapter(): void $this->assertInstanceOf(RedisRateLimitAdapter::class, $limiter->getAdapter()); } + public function testRateLimiterFactoryReadsTheTtlGivenAsText(): void + { + $this->setRateLimitConfig('file.ttl', '30'); + + $limiter = RateLimiterFactory::get(RateLimitType::FILE); + + $this->assertInstanceOf(FileRateLimitAdapter::class, $limiter->getAdapter()); + } + + public function testRateLimiterFactoryRejectsAMissingTtl(): void + { + $this->setRateLimitConfig('file', ['prefix' => '', 'path' => base_dir() . DS . 'cache' . DS . 'data']); + + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `ttl` is missing.'); + + RateLimiterFactory::get(RateLimitType::FILE); + } + + public function testRateLimiterFactoryRejectsARedisPortThatIsNotANumber(): void + { + $this->setRateLimitConfig('redis.port', 'abc'); + + $this->expectException(ConfigException::class); + $this->expectExceptionMessage('The config key `port` has the value `abc`, which is not a whole number.'); + + RateLimiterFactory::get(RateLimitType::REDIS); + } + public function testRateLimiterFactoryThrowsForInvalidAdapter(): void { $this->expectException(RateLimitException::class); @@ -61,4 +92,13 @@ private function resetRateLimiterFactory(): void $factory = Di::get(RateLimiterFactory::class); $this->setPrivateProperty($factory, 'instances', []); } + + private function setRateLimitConfig(string $key, mixed $value): void + { + if (!config()->has('rate_limit')) { + config()->import(new Setup('config', 'rate_limit')); + } + + config()->set('rate_limit.' . $key, $value); + } } diff --git a/tests/Unit/Renderer/Adapters/TwigAdapterTest.php b/tests/Unit/Renderer/Adapters/TwigAdapterTest.php index 292fc41eb..9adfd7c39 100644 --- a/tests/Unit/Renderer/Adapters/TwigAdapterTest.php +++ b/tests/Unit/Renderer/Adapters/TwigAdapterTest.php @@ -4,7 +4,9 @@ use Quantum\Renderer\Adapters\TwigAdapter; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; use Quantum\Router\MatchedRoute; +use Twig\Error\RuntimeError; use Quantum\Router\Route; class TwigAdapterTest extends AppTestCase @@ -37,4 +39,22 @@ public function testTwigAdapterRenderView(): void $this->assertSame('

Hello Tester, this is rendered twig view

', $output); } + + public function testTwigAdapterPassesItsConfigToTwig(): void + { + $template = PROJECT_ROOT . DS . 'modules' . DS . 'Test' . DS . 'Views' . DS . 'strict_probe.twig.php'; + $this->assertFileDoesNotExist($template); + + try { + $this->createFile($template, '

{{ missing }}

'); + + $this->assertSame('

', (new TwigAdapter())->render('strict_probe.twig')); + + $this->expectException(RuntimeError::class); + + (new TwigAdapter(new ConfigSection(['strict_variables' => true])))->render('strict_probe.twig'); + } finally { + $this->removeFile($template); + } + } } diff --git a/tests/Unit/Session/Adapters/Native/NativeSessionAdapterTest.php b/tests/Unit/Session/Adapters/Native/NativeSessionAdapterTest.php index c33249aec..cbc121997 100644 --- a/tests/Unit/Session/Adapters/Native/NativeSessionAdapterTest.php +++ b/tests/Unit/Session/Adapters/Native/NativeSessionAdapterTest.php @@ -4,6 +4,7 @@ use Quantum\Session\Adapters\Native\NativeSessionAdapter; use Quantum\Tests\Unit\AppTestCase; +use Quantum\Config\ConfigSection; class NativeSessionAdapterTest extends AppTestCase { @@ -113,4 +114,16 @@ public function testNativeSessionRegenerateSessionId(): void $this->assertNotEquals(session_id(), $sessionId); } + + public function testNativeSessionKeepsItsConfigAfterRegenerateId(): void + { + $session = new NativeSessionAdapter(new ConfigSection(['timeout' => '60'])); + + $session->regenerateId(); + + $config = $this->getPrivateProperty($session, 'config'); + + $this->assertInstanceOf(ConfigSection::class, $config); + $this->assertSame(60, $config->getInt('timeout')); + } }