Skip to content

Commit 32d9c3b

Browse files
[5.x] Add --headers option to static warm command
1 parent ac50ce1 commit 32d9c3b

2 files changed

Lines changed: 42 additions & 2 deletions

File tree

src/Console/Commands/StaticWarm.php

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ class StaticWarm extends Command
4242
{--include= : Only warm specific URLs}
4343
{--exclude= : Exclude specific URLs}
4444
{--max-requests= : Maximum number of requests to warm}
45+
{--headers= : Set custom headers (e.g. --headers="Authorization: Bearer your_token", can be used multiple times)}
4546
';
4647

4748
protected $description = 'Warms the static cache by visiting all URLs';
@@ -167,8 +168,9 @@ private function getRelativeUri(int $index): string
167168

168169
private function requests()
169170
{
170-
return $this->uris()->map(function ($uri) {
171-
return new Request('GET', $uri);
171+
$headers = $this->parseHeaders($this->option('headers'));
172+
return $this->uris()->map(function ($uri) use ($headers) {
173+
return new Request('GET', $uri, $headers);
172174
})->all();
173175
}
174176

@@ -374,4 +376,24 @@ protected function additionalUris(): Collection
374376

375377
return $uris->map(fn ($uri) => URL::makeAbsolute($uri));
376378
}
379+
380+
private function parseHeaders($headerOptions): array
381+
{
382+
$headers = [];
383+
if (empty($headerOptions)) {
384+
return $headers;
385+
}
386+
if (!is_array($headerOptions)) {
387+
$headerOptions = [$headerOptions];
388+
}
389+
foreach ($headerOptions as $header) {
390+
if (strpos($header, ':') !== false) {
391+
[$key, $value] = explode(':', $header, 2);
392+
$headers[trim($key)] = trim($value);
393+
} else {
394+
$this->line("<fg=yellow;options=bold>Warning:</> Invalid header format: '$header'. Headers should be in 'Key: Value' format.");
395+
}
396+
}
397+
return $headers;
398+
}
377399
}

tests/Console/Commands/StaticWarmTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,24 @@ public static function queueConnectionsProvider()
271271
];
272272
}
273273

274+
#[Test]
275+
public function it_sets_custom_headers_on_requests()
276+
{
277+
config(['statamic.static_caching.strategy' => 'half']);
278+
279+
$mock = Mockery::mock(\GuzzleHttp\Client::class);
280+
$mock->shouldReceive('send')->andReturnUsing(function ($request) {
281+
$this->assertEquals('Bearer testtoken', $request->getHeaderLine('Authorization'));
282+
283+
return Mockery::mock(\GuzzleHttp\Psr7\Response::class);
284+
});
285+
$this->app->instance(\GuzzleHttp\Client::class, $mock);
286+
287+
$this->artisan('statamic:static:warm', [
288+
'--headers' => ['Authorization: Bearer testtoken'],
289+
])->assertExitCode(0);
290+
}
291+
274292
private function createPage($slug, $attributes = [])
275293
{
276294
$this->makeCollection()->save();

0 commit comments

Comments
 (0)