Skip to content

Commit d463258

Browse files
fix(http): fix so referer header is resolved depending on request class in invalid response (#604)
1 parent effb684 commit d463258

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

src/Tempest/Http/src/Responses/Invalid.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,26 @@ public function __construct(
2121
/** @var \Tempest\Validation\Rule[][] $failingRules */
2222
array $failingRules = [],
2323
) {
24-
$referer = $request->getHeader('referer')[0] ?? throw new Exception("No referer found, could not redirect (this shouldn't happen, please create a bug report)");
24+
$referer = $this->getReferer($request);
2525
$body = $request instanceof PsrRequest ? $request->getParsedBody() : $request->getBody();
2626

2727
$this->addHeader('Location', $referer);
2828
$this->status = Status::FOUND;
2929
$this->flash(Session::VALIDATION_ERRORS, $failingRules);
3030
$this->flash(Session::ORIGINAL_VALUES, $body);
3131
}
32+
33+
private function getReferer(PsrRequest|Request $request): string
34+
{
35+
$referer = match (true) {
36+
$request instanceof Request => $request->getHeaders()['referer'] ?? null,
37+
$request instanceof PsrRequest => $request->getHeader('referer')[0] ?? null,
38+
};
39+
40+
if (! $referer) {
41+
throw new Exception("No referer found, could not redirect (this shouldn't happen, please create a bug report)");
42+
}
43+
44+
return $referer;
45+
}
3246
}

tests/Integration/Http/Responses/InvalidTest.php

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,40 @@
2020
*/
2121
final class InvalidTest extends FrameworkIntegrationTestCase
2222
{
23-
public function test_invalid(): void
23+
public function test_invalid_with_psr_request(): void
2424
{
2525
/** @var PsrRequest $request */
2626
$request = map(new GenericRequest(Method::GET, '/original', ['foo' => 'bar']))->with(RequestToPsrRequestMapper::class);
2727
$request = $request->withHeader('Referer', '/original');
2828

29+
$response = new Invalid(
30+
$request,
31+
[
32+
'foo' => [
33+
new NotEmpty(),
34+
],
35+
]
36+
);
37+
38+
$this->assertSame(Status::FOUND, $response->getStatus());
39+
$this->assertSame('/original', $response->getHeader('Location')->values[0]);
40+
41+
$session = $this->container->get(Session::class);
42+
43+
$this->assertArrayHasKey('foo', $session->get(Session::VALIDATION_ERRORS));
44+
$this->assertArrayHasKey('foo', $session->get(Session::ORIGINAL_VALUES));
45+
}
46+
47+
public function test_invalid_with_request()
48+
{
49+
$request = new GenericRequest(
50+
method: Method::GET,
51+
uri: '/original',
52+
body: ['foo' => 'bar'],
53+
headers: ['referer' => '/original']
54+
);
55+
56+
2957
$response = new Invalid(
3058
$request,
3159
[

0 commit comments

Comments
 (0)