diff --git a/README.md b/README.md
index 5a5c9ab..5cb1e3e 100644
--- a/README.md
+++ b/README.md
@@ -2,10 +2,10 @@
PHP and Laravel server SDK for [Reflag](https://reflag.com) feature flags.
-- Flags are evaluated **locally** against cached definitions: a read costs no network round trip.
+- Flags are evaluated **locally** against cached definitions: reading a flag never calls Reflag.
- Definitions are shared between requests and workers through your **cache** and revalidated in the background, after the response has been sent.
- Boolean and **multivariate** (JSON-valued) flags, targeting rules, segments, flag dependencies and percentage rollouts.
-- Laravel: auto-discovered service provider, `Reflag` facade, the signed-in user as default context, Blade directives, a testing fake, and `reflag:*` Artisan commands.
+- Laravel: auto-discovered service provider, `Reflag` facade, the signed-in user as default context, Blade directives, route middleware, a testing fake, and `reflag:*` Artisan commands.
- Works without Laravel too (PSR-16 cache, PSR-18 HTTP, PSR-3 logging).
Requires PHP 8.2+. The Laravel integration supports Laravel 12 and 13 (see [Laravel versions](#laravel-versions)).
@@ -22,15 +22,15 @@ Set your environment's secret key:
REFLAG_SECRET_KEY=your-secret-key
```
-## Laravel
-
The service provider and `Reflag` facade are registered automatically. Publish the config if you want to change the defaults:
```bash
php artisan vendor:publish --tag=reflag-config
```
-### Reading flags
+Not using Laravel? See [Plain PHP](#plain-php).
+
+## Reading flags
Reads without an explicit context use the signed-in user:
@@ -41,8 +41,8 @@ if (Reflag::getFlag('new-dashboard')) {
// …
}
-$theme = Reflag::getFlag('theme', 'light'); // string flag, default 'light'
-$limit = Reflag::getFlag('upload-limit-mb', 10); // number flag
+$theme = Reflag::getFlag('theme', 'light'); // string flag, default 'light'
+$limit = Reflag::getFlag('upload-limit-mb', 10); // number flag
$model = Reflag::getFlag('model-config', ['name' => 'small']); // JSON object flag
```
@@ -63,7 +63,26 @@ Reflag::getFlag('beta-search', context: [
You can also inject `Reflag\ReflagClient`, the class behind the facade, into controllers, jobs and services.
-### What Reflag sees about your users
+### Flag types
+
+`getFlag` is the only read method. The default you pass selects the JSON type you expect:
+
+| Call | Returns |
+| --- | --- |
+| `getFlag('x')` | `true` only for a resolved `true`; anything else is `false` |
+| `getFlag('x', 'light')` | a string, or the default |
+| `getFlag('x', 10)` | an int or float, or the default |
+| `getFlag('x', ['a' => 1])` | an associative array (JSON object), or the default |
+| `getFlag('x', ['a', 'b'])` | a list (JSON array), or the default |
+| `getFlag('x', null)` | any JSON value, including `null` |
+
+When a flag has no value or its value has a different type, you get the default and a warning is logged. Values are never coerced: `"false"` is not `false`, and `1` is not `true`. Falsy values such as `0`, `""` and `[]` are returned as they are.
+
+PHP arrays can't tell an empty JSON object from an empty list, so `getFlag` returns both `{}` and `[]` as `[]`. Bootstrap payloads and fallback snapshots keep `{}` intact.
+
+`getFlags()` returns every flag's value (`null` when a flag has none) and registers a check for each one.
+
+## What Reflag sees about your users
By default the user's `id`, `name` and `email` are sent, with no company. To control this, implement `ProvidesReflagContext` on your models:
@@ -86,7 +105,7 @@ A Reflag **company** is whatever your app groups users into: a team, account, wo
Attribute names are case-sensitive. Nested arrays are flattened for targeting (for example `company.address.country`), and lists work with the `ANY_OF`, `CONTAINS`, `IS` and `SET` operators.
-### Blade
+## Blade
```blade
@flag('new-dashboard')
@@ -102,7 +121,25 @@ Attribute names are case-sensitive. Nested arrays are flattened for targeting (f
@endflag
```
-Hand flags to a v2 browser SDK (Browser, React, Vue):
+## Routes
+
+The `reflag` middleware responds with a 404 unless every listed flag is enabled for the signed-in user:
+
+```php
+use Reflag\Laravel\Middleware\EnsureFlagsAreEnabled;
+
+Route::get('/dashboard/new', NewDashboardController::class)->middleware(['auth', 'reflag:new-dashboard']);
+
+Route::middleware(['auth', EnsureFlagsAreEnabled::using('beta-search', 'search-v2')])->group(function () {
+ // …
+});
+```
+
+Put it after `auth` so the signed-in user is known. Only a flag that resolves to `true` lets the request through.
+
+## Front end
+
+Hand flags to a v2 browser SDK (Browser, React, Vue) so it renders without fetching them first. With Blade:
```blade
```
-`@reflagBootstrap` accepts an optional context, for example `@reflagBootstrap($context)`. Only flags marked as client-visible are included, and generating it doesn't register flag checks. The payload includes the full context, so every attribute in it is visible in the browser; bootstrap with a context that contains only what the browser may see.
+With Inertia, share them as a prop:
+
+```php
+// app/Http/Middleware/HandleInertiaRequests.php
+public function share(Request $request): array
+{
+ return [
+ ...parent::share($request),
+ 'reflag' => fn () => Reflag::getFlagsForBootstrap(),
+ ];
+}
+```
+
+```tsx
+
+```
-### Keeping definitions fresh
+`@reflagBootstrap` and `getFlagsForBootstrap()` accept an optional context. Only flags marked as client-visible are included, and generating the payload doesn't register flag checks. The payload includes the full context, so every attribute in it is visible in the browser; bootstrap with a context that contains only what the browser may see.
+
+## Keeping definitions fresh
Definitions are stored in your cache (`REFLAG_CACHE_STORE`, defaulting to the default store). A request serves whatever is cached. When the copy is older than `refresh_interval` (60 seconds), one process revalidates it with a conditional request after its response has been sent. Only a completely empty cache makes a request wait, and then just one process fetches while the others wait for it, up to `cold_start_wait`.
-Two optional additions make updates faster and keep request handlers from ever refreshing:
+Two optional additions make updates faster and keep request handlers from ever refreshing. First, schedule a refresh and a telemetry flush:
```php
// routes/console.php
use Illuminate\Support\Facades\Schedule;
-Schedule::command('reflag:refresh')->everyMinute();
-Schedule::command('reflag:flush')->everyMinute();
+Schedule::command('reflag:refresh')->everyMinute()->onOneServer();
+Schedule::command('reflag:flush')->everyMinute()->onOneServer();
```
-For updates within seconds, run the push listener under Supervisor (or any process manager):
-
-```bash
-php artisan reflag:listen
+For updates within seconds, also run the push listener. It refreshes the cache as soon as flags change, reconnects automatically, and sends buffered telemetry. Run it under Supervisor, like a queue worker:
+
+```ini
+[program:reflag-listen]
+command=php /var/www/app/artisan reflag:listen
+autostart=true
+autorestart=true
+stopwaitsecs=30
+user=forge
+redirect_stderr=true
+stdout_logfile=/var/www/app/storage/logs/reflag-listen.log
```
-It refreshes the cache as soon as flags change, reconnects automatically, and also sends buffered telemetry.
+On `SIGTERM` the listener sends any buffered telemetry and exits. Restart it after each deployment (`supervisorctl restart reflag-listen`) so it runs your new code.
+
+### Artisan commands
+
+| Command | Purpose |
+| --- | --- |
+| `reflag:refresh` | Fetch the latest definitions into the cache. In deploy scripts, `--wait-for-version=N` waits until Reflag has published that flag state version. |
+| `reflag:flush` | Send buffered telemetry. |
+| `reflag:listen` | Keep definitions up to date through push updates. `--max-time=N` stops after N seconds; `--no-drain` leaves telemetry to `reflag:flush`. |
-### Telemetry
+## Telemetry
Flag checks and user and company attributes are queued during the request and sent after the response. With a Redis, Memcached, database or DynamoDB cache, the SDK buffers batches from many requests in the cache and sends them together. This happens through `reflag:flush`, `reflag:listen`, or opportunistically every 10 seconds. With other stores, or `REFLAG_TELEMETRY_DRIVER=request`, each request sends its own batch.
@@ -147,81 +216,52 @@ Reflag::updateCompany($company->id, ['seats' => 25], userId: $user->id);
Queue workers flush after every job; Octane flushes after every request.
-### Testing
+`php artisan serve` can't send a response before PHP finishes, so locally each page also waits for telemetry and any background refresh. PHP-FPM (including Herd and Valet), Octane and queue workers don't have this delay.
-```php
-use Reflag\Laravel\Facades\Reflag;
-
-public function test_dashboard(): void
-{
- $reflag = Reflag::fake(['new-dashboard' => true, 'theme' => 'dark']);
-
- $this->actingAs($user)->get('/dashboard')->assertOk();
-
- $reflag->assertFlagChecked('new-dashboard');
- $reflag->assertFlagNotChecked('old-dashboard');
- $reflag->assertUserUpdated($user->id); // or assertCompanyUpdated($id)
-}
-```
+### Turning off telemetry
-The fake makes no network calls. Values can also come from a closure that receives the `ReflagContext`:
+Leave telemetry on for normal traffic. Turn it off when you evaluate flags on someone's behalf without recording that activity, for example in support impersonation or internal previews:
```php
-Reflag::fake(fn (ReflagContext $context) => ['beta' => $context->companyId() === 'acme']);
+$reflag = Reflag::for($customer, telemetry: false);
+$reflag->getFlag('new-dashboard'); // no check, no attribute sync
```
-## Example app
+Calling `updateUser` or `updateCompany` on the client itself always sends. Pass `active: false` to update attributes without changing **Last seen**.
-[`examples/laravel-app`](examples/laravel-app) is a tiny Laravel app with flag endpoints, Blade directives, browser bootstrap and `Reflag::fake()` tests. It runs offline without a secret key. [`examples/basic.php`](examples/basic.php) shows plain PHP.
+## Testing
-## Plain PHP
+`Reflag::fake()` replaces the client with one that makes no network calls and records flag checks and attribute updates:
```php
-use Reflag\ReflagClient;
-use Reflag\ReflagOptions;
-use Reflag\Store\Psr16Store;
+use App\Models\User;
+use Reflag\Laravel\Facades\Reflag;
-$reflag = new ReflagClient(new ReflagOptions(
- secretKey: getenv('REFLAG_SECRET_KEY'),
- store: new Psr16Store($cache), // any PSR-16 cache; omit in CLI scripts and long-running workers
-));
+it('shows the new dashboard', function () {
+ Reflag::fake(['new-dashboard' => true, 'theme' => 'dark']);
+ $user = User::factory()->create();
-$enabled = $reflag->getFlag('new-dashboard', context: ['user' => ['id' => 'user-123'], 'company' => ['id' => 'acme']]);
+ $this->actingAs($user)->get('/dashboard')->assertOk();
-// At the end of the request or job (also runs when the client is destroyed):
-$reflag->terminate();
+ Reflag::assertFlagChecked('new-dashboard');
+ Reflag::assertFlagNotChecked('old-dashboard');
+ Reflag::assertUserUpdated($user->id); // or assertCompanyUpdated($id)
+});
```
-Without a store, definitions are kept in process memory. That suits CLI scripts, queue consumers and long-running servers (RoadRunner, Swoole, ReactPHP), but under PHP-FPM every request would fetch again, so give FPM applications a shared cache. A plain PSR-16 cache has no atomic operations, so telemetry is sent per request. For buffered telemetry, implement `Reflag\Contracts\SharedStore` over Redis.
-
-To push updates outside Laravel, run a small daemon:
+Values can also come from a closure that receives the `ReflagContext`:
```php
-(new Reflag\FlagUpdatesListener($reflag))->run();
-```
-
-## Multivariate flags
+use Reflag\ReflagContext;
-`getFlag` is the only read method. The default you pass selects the JSON type you expect:
-
-| Call | Returns |
-| --- | --- |
-| `getFlag('x')` | `true` only for a resolved `true`; anything else is `false` |
-| `getFlag('x', 'light')` | a string, or the default |
-| `getFlag('x', 10)` | an int or float, or the default |
-| `getFlag('x', ['a' => 1])` | an associative array (JSON object), or the default |
-| `getFlag('x', ['a', 'b'])` | a list (JSON array), or the default |
-| `getFlag('x', null)` | any JSON value, including `null` |
-
-PHP arrays can't tell an empty JSON object from an empty list, so `getFlag` returns both `{}` and `[]` as `[]`. Bootstrap payloads and fallback snapshots keep `{}` intact.
-
-When a flag has no value or its value has a different type, you get the default and a warning is logged. Values are never coerced: `"false"` is not `false`, and `1` is not `true`. Falsy values such as `0`, `""` and `[]` are returned as they are.
+Reflag::fake(fn (ReflagContext $context) => ['beta' => $context->companyId() === 'acme']);
+```
-`getFlags()` returns every flag's value (`null` when a flag has none) and registers a check for each one.
+The fake ignores `REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED`, so tests see only the flags they pass.
## Overrides
-Overrides replace evaluated values locally. They're useful in development, demos and tests.
+Overrides replace evaluated values locally. They're useful in development and demos.
```dotenv
REFLAG_FLAGS_ENABLED=new-dashboard,beta-search
@@ -231,6 +271,10 @@ REFLAG_FLAGS_DISABLED=legacy-export
```php
// config/reflag.php
'overrides' => ['theme' => 'dark', 'model' => ['name' => 'small']],
+```
+
+```php
+use Reflag\ReflagContext;
Reflag::setFlagOverrides(fn (ReflagContext $context) => ['beta' => $context->companyId() === 'qa']);
@@ -241,7 +285,7 @@ Reflag::withFlagOverrides(['beta' => false], function () {
Reflag::clearFlagOverrides();
```
-The `config/reflag.php` overrides win over the environment lists. `setFlagOverrides()` and `clearFlagOverrides()` replace both. `Reflag::fake()` ignores the environment lists, so tests see only the flags they pass.
+The `config/reflag.php` overrides win over the environment lists. `setFlagOverrides()` and `clearFlagOverrides()` replace both.
Overrides apply after evaluation, so overriding a flag doesn't change other flags that depend on it.
@@ -264,46 +308,35 @@ REFLAG_FALLBACK_DISK=s3
| `gcs` | `fallback.bucket`; a `StorageClient` from the container | `google/cloud-storage` |
| `azure` | `fallback.azure_sas_url`: a container SAS URL | |
-Every live update is saved to the fallback. Static values don't identify authored variants, so checks against them are reported as unresolved. In plain PHP, use `Reflag\Fallback\ReflagFallbackProviders::static()`, `::file()`, `::redis()`, `::s3()`, `::gcs()` or `::azureBlob()`, or implement `FlagsFallbackProvider`.
+Every live update is saved to the fallback. Static values don't identify authored variants, so checks against them are reported as unresolved.
The `file` and `redis` providers use `flagStateVersion` to prevent older snapshots from replacing newer ones. The Redis provider needs `EVAL`, `GET`, and `SET` permissions. Use a phpredis connection with serialization and compression disabled so the script can read the stored JSON. Custom clients must expose `get` and a Predis-compatible `eval`.
-## Turning off telemetry
-
-Leave telemetry on for normal traffic. Turn it off when you evaluate flags on someone's behalf without recording that activity, for example in support impersonation or internal previews:
-
-```php
-$reflag = Reflag::for($customer, telemetry: false);
-$reflag->getFlag('new-dashboard'); // no check, no attribute sync
-```
-
-Calling `updateUser` or `updateCompany` on the client itself always sends. Pass `active: false` to update attributes without changing **Last seen**.
-
## Offline mode
`REFLAG_OFFLINE=true` turns off all network I/O: reads return defaults and overrides, nothing is fetched or loaded from a fallback, and no telemetry is sent.
## Configuration
-| Option (`config/reflag.php`) | `ReflagOptions` | Env | Default |
+| `config/reflag.php` | Env | `ReflagOptions` (plain PHP) | Default |
| --- | --- | --- | --- |
-| `secret_key` | `secretKey` | `REFLAG_SECRET_KEY` | required unless offline |
-| `api_base_url` | `apiBaseUrl` | `REFLAG_API_BASE_URL` | `https://front.reflag.com` |
-| `push_url` | `pushUrl` | `REFLAG_PUSH_URL` | `{api_base_url}/sse/server` |
-| `offline` | `offline` | `REFLAG_OFFLINE` | `false` |
-| `cache_store` | `store` | `REFLAG_CACHE_STORE` | default cache store |
-| `telemetry_driver` | `telemetryDriver` | `REFLAG_TELEMETRY_DRIVER` | `auto` |
-| `refresh_interval` | `refreshInterval` | | `60` seconds |
-| `cold_start_wait` | `coldStartWait` | | `5` seconds |
-| `fetch_timeout` | `fetchTimeout` | | `10` seconds |
-| `fetch_retries` | `fetchRetries` | | `3` (scheduled and pushed refreshes) |
-| `flush_interval` | `flushInterval` | | `10` seconds |
-| `batch_size` | `batchSize` | | `100` |
-| `overrides` | `flagOverrides` | `REFLAG_FLAGS_ENABLED`, `REFLAG_FLAGS_DISABLED` | none |
-| `fallback.*` | `fallbackProvider` | `REFLAG_FALLBACK_*` | none |
-| `log_channel` | `logger` | `REFLAG_LOG_CHANNEL` | default channel |
-
-Options take precedence over environment variables. To customize HTTP (proxies, TLS), bind a PSR-18 client as `reflag.http_client` in Laravel, or pass `httpClient`.
+| `secret_key` | `REFLAG_SECRET_KEY` | `secretKey` | required unless offline |
+| `api_base_url` | `REFLAG_API_BASE_URL` | `apiBaseUrl` | `https://front.reflag.com` |
+| `push_url` | `REFLAG_PUSH_URL` | `pushUrl` | `{api_base_url}/sse/server` |
+| `offline` | `REFLAG_OFFLINE` | `offline` | `false` |
+| `cache_store` | `REFLAG_CACHE_STORE` | `store` | default cache store |
+| `telemetry_driver` | `REFLAG_TELEMETRY_DRIVER` | `telemetryDriver` | `auto` |
+| `refresh_interval` | | `refreshInterval` | `60` seconds |
+| `cold_start_wait` | | `coldStartWait` | `5` seconds |
+| `fetch_timeout` | | `fetchTimeout` | `10` seconds |
+| `fetch_retries` | | `fetchRetries` | `3` (scheduled and pushed refreshes) |
+| `flush_interval` | | `flushInterval` | `10` seconds |
+| `batch_size` | | `batchSize` | `100` |
+| `overrides` | `REFLAG_FLAGS_ENABLED`, `REFLAG_FLAGS_DISABLED` | `flagOverrides` | none |
+| `fallback.*` | `REFLAG_FALLBACK_*` | `fallbackProvider` | none |
+| `log_channel` | `REFLAG_LOG_CHANNEL` | `logger` | default channel |
+
+To customize HTTP (proxies, TLS), bind a PSR-18 client as `reflag.http_client` in a service provider.
## Failed evaluations
@@ -311,12 +344,46 @@ If a targeting rule can't be evaluated, for example because a required context f
## Laravel versions
-The SDK itself doesn't depend on Laravel. The integration is tested on Laravel 12 and 13. It also runs on Laravel 11, but every Laravel 11 release has unpatched security advisories, so upgrade.
+The SDK itself doesn't depend on Laravel. The integration is tested on Laravel 12 and 13. It also runs on Laravel 11, but every Laravel 11 release has unpatched security advisories, so we recommend upgrading.
## Remote config
Remote config isn't supported. Use multivariate flags for configuration values.
+## Plain PHP
+
+```php
+use Reflag\ReflagClient;
+use Reflag\ReflagOptions;
+use Reflag\Store\Psr16Store;
+
+$reflag = new ReflagClient(new ReflagOptions(
+ secretKey: getenv('REFLAG_SECRET_KEY'),
+ store: new Psr16Store($cache), // any PSR-16 cache; omit in CLI scripts and long-running workers
+));
+
+$enabled = $reflag->getFlag('new-dashboard', context: ['user' => ['id' => 'user-123'], 'company' => ['id' => 'acme']]);
+
+// At the end of the request or job (also runs when the client is destroyed):
+$reflag->terminate();
+```
+
+Without a store, definitions are kept in process memory. That suits CLI scripts, queue consumers and long-running servers (RoadRunner, Swoole, ReactPHP), but under PHP-FPM every request would fetch again, so give FPM applications a shared cache. A plain PSR-16 cache has no atomic operations, so telemetry is sent per request. For buffered telemetry, implement `Reflag\Contracts\SharedStore` over Redis.
+
+`ReflagOptions` you don't pass are read from `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_OFFLINE`, `REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED`; options you pass win. Pass a PSR-18 client as `httpClient` to customize HTTP.
+
+For fallbacks, use `Reflag\Fallback\ReflagFallbackProviders::static()`, `::file()`, `::redis()`, `::s3()`, `::gcs()` or `::azureBlob()`, or implement `FlagsFallbackProvider`.
+
+To push updates, run a small daemon:
+
+```php
+(new Reflag\FlagUpdatesListener($reflag))->run();
+```
+
+## Example app
+
+[`examples/laravel-app`](examples/laravel-app) is a tiny Laravel app with flag endpoints, Blade directives, browser bootstrap and `Reflag::fake()` tests. It runs offline without a secret key. [`examples/basic.php`](examples/basic.php) shows plain PHP.
+
## License
MIT. See [LICENSE](LICENSE).
diff --git a/examples/laravel-app/routes/console.php b/examples/laravel-app/routes/console.php
index 34e8d28..d3dcdea 100644
--- a/examples/laravel-app/routes/console.php
+++ b/examples/laravel-app/routes/console.php
@@ -4,5 +4,5 @@
// Optional: refresh definitions and send buffered telemetry outside of requests.
// Run `php artisan schedule:work` locally, or `php artisan reflag:listen` for push updates.
-Schedule::command('reflag:refresh')->everyMinute()->withoutOverlapping();
-Schedule::command('reflag:flush')->everyMinute()->withoutOverlapping();
+Schedule::command('reflag:refresh')->everyMinute()->onOneServer();
+Schedule::command('reflag:flush')->everyMinute()->onOneServer();
diff --git a/src/Laravel/Facades/Reflag.php b/src/Laravel/Facades/Reflag.php
index ce8e47c..fde74d8 100644
--- a/src/Laravel/Facades/Reflag.php
+++ b/src/Laravel/Facades/Reflag.php
@@ -26,6 +26,11 @@
* @method static int drainTelemetry()
* @method static \Reflag\ClientStatus status()
* @method static ?int flagStateVersion()
+ * @method static void assertFlagChecked(string $key, ?\Closure $callback = null) After {@see fake()}.
+ * @method static void assertFlagNotChecked(string $key) After {@see fake()}.
+ * @method static void assertUserUpdated(string|int $userId) After {@see fake()}.
+ * @method static void assertCompanyUpdated(string|int $companyId) After {@see fake()}.
+ * @method static list> recorded(?string $type = null) After {@see fake()}.
*
* @see ReflagClient
*/
diff --git a/src/Laravel/Middleware/EnsureFlagsAreEnabled.php b/src/Laravel/Middleware/EnsureFlagsAreEnabled.php
new file mode 100644
index 0000000..1357c5b
--- /dev/null
+++ b/src/Laravel/Middleware/EnsureFlagsAreEnabled.php
@@ -0,0 +1,38 @@
+middleware('reflag:new-dashboard')` or `->middleware(EnsureFlagsAreEnabled::using('a', 'b'))`.
+ */
+final class EnsureFlagsAreEnabled
+{
+ public function __construct(private readonly ReflagClient $reflag)
+ {
+ }
+
+ /** The middleware definition for routes that require all of the given flags. */
+ public static function using(string ...$flags): string
+ {
+ return self::class . ':' . implode(',', $flags);
+ }
+
+ public function handle(Request $request, Closure $next, string ...$flags): Response
+ {
+ foreach ($flags as $flag) {
+ if ($this->reflag->getFlag($flag) !== true) {
+ abort(404);
+ }
+ }
+
+ return $next($request);
+ }
+}
diff --git a/src/Laravel/ReflagServiceProvider.php b/src/Laravel/ReflagServiceProvider.php
index 34e90f6..c3473bc 100644
--- a/src/Laravel/ReflagServiceProvider.php
+++ b/src/Laravel/ReflagServiceProvider.php
@@ -19,6 +19,7 @@
use Reflag\Laravel\Commands\FlushCommand;
use Reflag\Laravel\Commands\ListenCommand;
use Reflag\Laravel\Commands\RefreshCommand;
+use Reflag\Laravel\Middleware\EnsureFlagsAreEnabled;
use Reflag\ReflagClient;
use Reflag\ReflagOptions;
use Reflag\TelemetryDriver;
@@ -47,6 +48,9 @@ public function boot(): void
$this->commands([RefreshCommand::class, FlushCommand::class, ListenCommand::class]);
}
+ // Route::get(...)->middleware('reflag:new-dashboard')
+ $this->app['router']->aliasMiddleware('reflag', EnsureFlagsAreEnabled::class);
+
$flush = function (): void {
if ($this->app->resolved(ReflagClient::class)) {
$this->app->make(ReflagClient::class)->terminate();
diff --git a/tests/Laravel/LaravelTest.php b/tests/Laravel/LaravelTest.php
index a0b7ed3..ac78130 100644
--- a/tests/Laravel/LaravelTest.php
+++ b/tests/Laravel/LaravelTest.php
@@ -215,4 +215,35 @@ public function testConfigIsPublishable(): void
$this->assertArrayHasKey(ReflagServiceProvider::class, \Illuminate\Support\ServiceProvider::$publishes);
$this->assertSame('sec_laravel', config('reflag.secret_key'));
}
+
+ public function testFakeAssertionsThroughTheFacade(): void
+ {
+ Reflag::fake(['new-dashboard' => true]);
+ $this->actingAs(new GenericUser(['id' => 7, 'name' => 'Ada', 'email' => 'ada@example.com', 'remember_token' => null]));
+ \Illuminate\Support\Facades\Route::get('/dashboard', fn () => Reflag::getFlag('new-dashboard') ? 'new' : 'old');
+
+ $this->get('/dashboard')->assertOk()->assertSee('new');
+
+ Reflag::assertFlagChecked('new-dashboard');
+ Reflag::assertFlagNotChecked('old-dashboard');
+ Reflag::assertUserUpdated(7);
+ }
+
+ public function testRouteMiddlewareRequiresEveryFlag(): void
+ {
+ Reflag::fake(fn (ReflagContext $context) => ['beta' => $context->userId() === '7', 'search' => true, 'config' => ['on' => true]]);
+ $route = \Illuminate\Support\Facades\Route::class;
+ $route::get('/beta', fn () => 'beta')->middleware('reflag:beta');
+ $route::get('/both', fn () => 'both')->middleware(\Reflag\Laravel\Middleware\EnsureFlagsAreEnabled::using('beta', 'search'));
+ $route::get('/off', fn () => 'off')->middleware('reflag:beta,missing');
+ $route::get('/value', fn () => 'value')->middleware('reflag:config');
+
+ $this->get('/beta')->assertNotFound();
+ $this->actingAs(new GenericUser(['id' => 7, 'name' => 'Ada', 'email' => 'ada@example.com', 'remember_token' => null]));
+ $this->get('/beta')->assertOk()->assertSee('beta');
+ $this->get('/both')->assertOk();
+ $this->get('/off')->assertNotFound();
+ $this->get('/value')->assertNotFound(); // only boolean true enables a route
+ Reflag::assertFlagChecked('beta');
+ }
}