Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
24 / 24 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
RedirectResponse | |
100.00% |
24 / 24 |
|
100.00% |
2 / 2 |
8 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
2 | |||
getResponseText | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
6 |
1 | <?php |
2 | |
3 | namespace Miniframe\Response; |
4 | |
5 | use Miniframe\Core\Request; |
6 | use Miniframe\Core\Response; |
7 | |
8 | class RedirectResponse extends Response |
9 | { |
10 | /** |
11 | * URL to which we redirect |
12 | * |
13 | * @var string |
14 | */ |
15 | private $url; |
16 | |
17 | public const |
18 | MOVED_PERMANENTLY = 301, // GET methods unchanged. Others may or may not be changed to GET. |
19 | FOUND = 302, // GET methods unchanged. Others may or may not be changed to GET. |
20 | SEE_OTHER = 303, // GET methods unchanged. Others changed to GET (body lost). |
21 | TEMPORARY_REDIRECT = 307, // Method and body not changed. |
22 | PERMANENT_REDIRECT = 308; // Method and body not changed. |
23 | |
24 | /** |
25 | * Initializes a new Redirect response |
26 | * |
27 | * @param string $url URL to redirect to. |
28 | * @param integer $responseCode One of the HTTP response codes for a redirect. |
29 | */ |
30 | public function __construct(string $url, int $responseCode = self::FOUND) |
31 | { |
32 | $signature = Request::getActual()->getServer('SERVER_SIGNATURE'); |
33 | $html = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">' . PHP_EOL |
34 | . '<html><head>' . PHP_EOL |
35 | . '<title>' . $responseCode . ' ' . $this->getResponseText($responseCode) . '</title>' . PHP_EOL |
36 | . '</head><body>' . PHP_EOL |
37 | . '<p>The document has moved <a href="' . htmlspecialchars($url) . '">here</a>.</p>' . PHP_EOL |
38 | . '<hr>' . PHP_EOL |
39 | . (is_string($signature) ? $signature : '') . PHP_EOL |
40 | . '</body></html>'; |
41 | parent::__construct($html); |
42 | |
43 | $this->url = $url; |
44 | $this->setResponseCode($responseCode); |
45 | $this->addHeader('Location: ' . $this->url); |
46 | } |
47 | |
48 | /** |
49 | * Converts a HTTP status code to it's label |
50 | * |
51 | * @param integer $responseCode One of the HTTP response codes for a redirect. |
52 | * |
53 | * @return string |
54 | */ |
55 | private function getResponseText(int $responseCode): string |
56 | { |
57 | if ($responseCode == static::MOVED_PERMANENTLY) { |
58 | return 'Moved permanently'; |
59 | } |
60 | if ($responseCode == static::FOUND) { |
61 | return 'Found'; |
62 | } |
63 | if ($responseCode == static::SEE_OTHER) { |
64 | return 'See other'; |
65 | } |
66 | if ($responseCode == static::TEMPORARY_REDIRECT) { |
67 | return 'Temporary redirect'; |
68 | } |
69 | if ($responseCode == static::PERMANENT_REDIRECT) { |
70 | return 'Permanent redirect'; |
71 | } |
72 | throw new \RuntimeException('Invalid response code for redirects: ' . $responseCode); |
73 | } |
74 | } |