Skip to content

Commit 4b739d5

Browse files
[5.x] Set etags (#11441)
Co-authored-by: Jason Varga <[email protected]>
1 parent 9b7d759 commit 4b739d5

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/Http/Responses/DataResponse.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,12 @@ public function toResponse($request)
4242
->make($this->contents())
4343
->withHeaders($this->headers);
4444

45+
if ($content = $response->getContent()) {
46+
$response
47+
->setEtag(md5($content))
48+
->isNotModified($request);
49+
}
50+
4551
ResponseCreated::dispatch($response, $this->data);
4652

4753
return $response;

tests/FrontendTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1064,4 +1064,32 @@ public function it_protects_404_pages()
10641064
->get('/does-not-exist')
10651065
->assertStatus(404);
10661066
}
1067+
1068+
#[Test]
1069+
public function it_sets_etag_header_and_returns_304_when_content_matches()
1070+
{
1071+
$this->withStandardBlueprints();
1072+
$this->withFakeViews();
1073+
$this->viewShouldReturnRaw('layout', '{{ template_content }}');
1074+
$this->viewShouldReturnRaw('default', '<h1>Test Page</h1>');
1075+
1076+
$this->createPage('about');
1077+
1078+
$response = $this->get('/about');
1079+
$response->assertStatus(200);
1080+
1081+
$content = trim($response->content());
1082+
$this->assertEquals('<h1>Test Page</h1>', $content);
1083+
1084+
$etag = $response->headers->get('ETag');
1085+
$this->assertEquals('"'.md5($content).'"', $etag); // Per spec, the quotes need to be in the string.
1086+
1087+
$response = $this->get('/about', ['If-None-Match' => $etag]);
1088+
$response->assertStatus(304);
1089+
$this->assertEmpty($response->content());
1090+
1091+
$response = $this->get('/about', ['If-None-Match' => '"wrong-etag"']);
1092+
$response->assertStatus(200);
1093+
$this->assertEquals('<h1>Test Page</h1>', trim($response->content()));
1094+
}
10671095
}

0 commit comments

Comments
 (0)