Skip to content

Commit cafc595

Browse files
claudef3l1x
authored andcommitted
Feature: add withRedirect() shortcut method
Add a convenience method for HTTP redirects that simplifies the common pattern of setting status code and Location header together. Closes #19
1 parent 1652928 commit cafc595

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/Extra/ExtraResponseTrait.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,15 @@ public function withHeaders(array $headers): static
8181
return $new;
8282
}
8383

84+
/*
85+
* REDIRECT ***************************************************************
86+
*/
87+
88+
public function withRedirect(string $url, int $statusCode = 302): static
89+
{
90+
return $this
91+
->withStatus($statusCode)
92+
->withHeader('Location', $url);
93+
}
94+
8495
}

tests/Cases/Psr7ResponseTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,30 @@ public function testWithAttributes(): void
8888
Assert::equal('baz', $this->response->getHeaderLine('X-Bar'));
8989
}
9090

91+
public function testWithRedirect(): void
92+
{
93+
$this->response = $this->response->withRedirect('https://example.com');
94+
95+
Assert::equal(302, $this->response->getStatusCode());
96+
Assert::equal('https://example.com', $this->response->getHeaderLine('Location'));
97+
}
98+
99+
public function testWithRedirectCustomStatusCode(): void
100+
{
101+
$this->response = $this->response->withRedirect('https://example.com', 301);
102+
103+
Assert::equal(301, $this->response->getStatusCode());
104+
Assert::equal('https://example.com', $this->response->getHeaderLine('Location'));
105+
}
106+
107+
public function testWithRedirect303(): void
108+
{
109+
$this->response = $this->response->withRedirect('https://example.com/other', 303);
110+
111+
Assert::equal(303, $this->response->getStatusCode());
112+
Assert::equal('https://example.com/other', $this->response->getHeaderLine('Location'));
113+
}
114+
91115
public function testOf(): void
92116
{
93117
$this->response = $this->response

0 commit comments

Comments
 (0)