|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of Symplify |
|
7
|
|
|
* Copyright (c) 2016 Tomas Votruba (http://tomasvotruba.cz). |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace Symplify\PHP7_Sculpin\HttpServer; |
|
11
|
|
|
|
|
12
|
|
|
use React\Http\Request; |
|
13
|
|
|
use React\Http\Response; |
|
14
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
|
15
|
|
|
use Symplify\PHP7_Sculpin\HttpServer\MimeType\MimeTypeDetector; |
|
16
|
|
|
|
|
17
|
|
|
final class ResponseWriter |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* @var OutputInterface |
|
21
|
|
|
*/ |
|
22
|
|
|
private $output; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var MimeTypeDetector |
|
26
|
|
|
*/ |
|
27
|
|
|
private $mimeTypeDetector; |
|
28
|
|
|
|
|
29
|
7 |
|
public function __construct(OutputInterface $output, MimeTypeDetector $mimeTypeDetector) |
|
30
|
|
|
{ |
|
31
|
7 |
|
$this->output = $output; |
|
32
|
7 |
|
$this->mimeTypeDetector = $mimeTypeDetector; |
|
33
|
7 |
|
} |
|
34
|
|
|
|
|
35
|
1 |
|
public function send404Response(Request $request, Response $response) |
|
36
|
|
|
{ |
|
37
|
1 |
|
$this->writeResponse(404, $request->getPath()); |
|
38
|
1 |
|
$response->writeHead(404, [ |
|
39
|
1 |
|
'Content-Type' => 'text/html', |
|
40
|
|
|
]); |
|
41
|
|
|
|
|
42
|
1 |
|
$response->end( |
|
43
|
|
|
'<h1>404 - Not Found</h1>' . |
|
44
|
1 |
|
'<p>Sculpin web server could not find the requested resource.</p>' |
|
45
|
|
|
); |
|
46
|
1 |
|
} |
|
47
|
|
|
|
|
48
|
1 |
|
public function send200Response(Request $request, Response $response, string $path) |
|
49
|
|
|
{ |
|
50
|
1 |
|
$response->writeHead(200, [ |
|
51
|
1 |
|
'Content-Type' => $this->mimeTypeDetector->detectForFilename($path), |
|
52
|
|
|
]); |
|
53
|
|
|
|
|
54
|
1 |
|
$this->writeResponse(200, $request->getPath()); |
|
55
|
1 |
|
$response->end(file_get_contents($path)); |
|
56
|
1 |
|
} |
|
57
|
|
|
|
|
58
|
2 |
|
private function writeResponse(int $responseCode, string $path) |
|
59
|
|
|
{ |
|
60
|
2 |
|
$message = sprintf( |
|
61
|
2 |
|
'Response code "%s" for path: "%s"', |
|
62
|
|
|
$responseCode, |
|
63
|
|
|
$path |
|
64
|
|
|
); |
|
65
|
|
|
|
|
66
|
2 |
|
$this->output->writeln($this->prepareResponseMessage($responseCode, $message)); |
|
67
|
2 |
|
} |
|
68
|
|
|
|
|
69
|
2 |
|
private function prepareResponseMessage(int $responseCode, string $message) : string |
|
70
|
|
|
{ |
|
71
|
2 |
|
$wrapOpen = '<info>'; |
|
72
|
2 |
|
$wrapClose = '</info>'; |
|
73
|
2 |
|
if ($responseCode >= 400) { |
|
74
|
1 |
|
$wrapOpen = '<error>'; |
|
75
|
1 |
|
$wrapClose = '</error>'; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
2 |
|
return $wrapOpen . $message . $wrapClose; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|