|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace VM\ErrorHandler\Services; |
|
6
|
|
|
|
|
7
|
|
|
use Fig\Http\Message\StatusCodeInterface; |
|
8
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
|
9
|
|
|
use RuntimeException; |
|
10
|
|
|
use Throwable; |
|
11
|
|
|
use VM\ErrorHandler\Exceptions\HttpException; |
|
12
|
|
|
use VM\ErrorHandler\Interfaces\ErrorHandler; |
|
13
|
|
|
|
|
14
|
|
|
class StaticFileHandler implements ErrorHandler |
|
15
|
|
|
{ |
|
16
|
|
|
private $filePath; |
|
17
|
|
|
private $response; |
|
18
|
|
|
private $filesForCodes; |
|
19
|
|
|
|
|
20
|
4 |
|
public function __construct(string $filePath, Response $response, array $filesForCodes = []) |
|
21
|
|
|
{ |
|
22
|
4 |
|
$this->filePath = $filePath; |
|
23
|
4 |
|
$this->response = $response; |
|
24
|
4 |
|
$this->filesForCodes = $filesForCodes; |
|
25
|
4 |
|
} |
|
26
|
|
|
|
|
27
|
2 |
|
public function handle(Throwable $error): Response |
|
28
|
|
|
{ |
|
29
|
2 |
|
return $this->writeFile(StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
2 |
|
public function handleHttpException(HttpException $httpException): Response |
|
33
|
|
|
{ |
|
34
|
2 |
|
return $this->writeFile($httpException->getHttpStatusCode()); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
4 |
|
private function writeFile(int $statusCode): Response |
|
38
|
|
|
{ |
|
39
|
4 |
|
$filePath = $this->findFilePath($statusCode); |
|
40
|
3 |
|
$contents = file_get_contents($filePath); |
|
41
|
3 |
|
$this->response->getBody()->write($contents); |
|
42
|
3 |
|
$this->response = $this->response->withHeader('Cache-Control', self::NO_CACHE_HEADER); |
|
43
|
3 |
|
return $this->response->withStatus($statusCode); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
4 |
|
private function findFilePath(int $statusCode): string |
|
47
|
|
|
{ |
|
48
|
4 |
|
$filePath = $this->filePath; |
|
49
|
4 |
|
if (!empty($this->filesForCodes[$statusCode])) { |
|
50
|
1 |
|
$filePath = $this->filesForCodes[$statusCode]; |
|
51
|
|
|
} |
|
52
|
4 |
|
$this->validateFilePath($filePath); |
|
53
|
3 |
|
return $filePath; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
4 |
|
private function validateFilePath(string $filePath): void |
|
57
|
|
|
{ |
|
58
|
4 |
|
if (!file_exists($filePath)) { |
|
59
|
1 |
|
throw new RuntimeException("unable to load error file: '{$filePath}'"); |
|
60
|
|
|
} |
|
61
|
3 |
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|