StaticFileHandler   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
eloc 21
dl 0
loc 46
rs 10
c 0
b 0
f 0
ccs 24
cts 24
cp 1

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A handleHttpException() 0 3 1
A validateFilePath() 0 4 2
A findFilePath() 0 8 2
A handle() 0 3 1
A writeFile() 0 7 1
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