diff --git a/src/Console/Commands/StaticWarm.php b/src/Console/Commands/StaticWarm.php index a7a052df15..55d45dd38a 100644 --- a/src/Console/Commands/StaticWarm.php +++ b/src/Console/Commands/StaticWarm.php @@ -42,6 +42,7 @@ class StaticWarm extends Command {--include= : Only warm specific URLs} {--exclude= : Exclude specific URLs} {--max-requests= : Maximum number of requests to warm} + {--header=* : Set custom header (e.g. "Authorization: Bearer your_token")} '; protected $description = 'Warms the static cache by visiting all URLs'; @@ -167,8 +168,10 @@ private function getRelativeUri(int $index): string private function requests() { - return $this->uris()->map(function ($uri) { - return new Request('GET', $uri); + $headers = $this->parseHeaders($this->option('header')); + + return $this->uris()->map(function ($uri) use ($headers) { + return new Request('GET', $uri, $headers); })->all(); } @@ -374,4 +377,25 @@ protected function additionalUris(): Collection return $uris->map(fn ($uri) => URL::makeAbsolute($uri)); } + + private function parseHeaders($headerOptions): array + { + $headers = []; + if (empty($headerOptions)) { + return $headers; + } + if (! is_array($headerOptions)) { + $headerOptions = [$headerOptions]; + } + foreach ($headerOptions as $header) { + if (strpos($header, ':') !== false) { + [$key, $value] = explode(':', $header, 2); + $headers[trim($key)] = trim($value); + } else { + $this->line("Warning: Invalid header format: '$header'. Headers should be in 'Key: Value' format."); + } + } + + return $headers; + } } diff --git a/tests/Console/Commands/StaticWarmTest.php b/tests/Console/Commands/StaticWarmTest.php index 344fdff0bc..3520413a93 100644 --- a/tests/Console/Commands/StaticWarmTest.php +++ b/tests/Console/Commands/StaticWarmTest.php @@ -271,6 +271,25 @@ public static function queueConnectionsProvider() ]; } + #[Test] + public function it_sets_custom_headers_on_requests() + { + config(['statamic.static_caching.strategy' => 'half']); + + $mock = Mockery::mock(\GuzzleHttp\Client::class); + $mock->shouldReceive('send')->andReturnUsing(function ($request) { + $this->assertEquals('Bearer testtoken', $request->getHeaderLine('Authorization')); + $this->assertEquals('Bar', $request->getHeaderLine('X-Foo')); + + return Mockery::mock(\GuzzleHttp\Psr7\Response::class); + }); + $this->app->instance(\GuzzleHttp\Client::class, $mock); + + $this->artisan('statamic:static:warm', [ + '--header' => ['Authorization: Bearer testtoken', 'X-Foo: Bar'], + ])->assertExitCode(0); + } + private function createPage($slug, $attributes = []) { $this->makeCollection()->save();