DownloadFile   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 5
eloc 22
c 3
b 0
f 0
dl 0
loc 39
ccs 0
cts 22
cp 0
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A handle() 0 35 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Handler;
6
7
use Ecodev\Felix\Handler\AbstractHandler;
8
use Laminas\Diactoros\Response;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
12
class DownloadFile extends AbstractHandler
13
{
14
    public const COUNTER_PATH = 'data/download-file-counter/counter.txt';
15
16
    public function handle(ServerRequestInterface $request): ResponseInterface
17
    {
18
        $path = 'data/download-file-counter/alternative_groceries_report_nov_2024.pdf';
19
        $cookie_name = 'artisans_pdf_download_1';
20
21
        // Increment counter if no cookie = first visit
22
        if (!isset($_COOKIE[$cookie_name])) {
23
            $download_count = 0;
24
            if (file_exists(self::COUNTER_PATH)) {
25
                $download_count = (int) (file_get_contents(self::COUNTER_PATH));
26
            }
27
            ++$download_count;
28
            file_put_contents(self::COUNTER_PATH, $download_count);
29
        }
30
31
        // Flag cookie
32
        setcookie($cookie_name, 'true', time() + (86400 * 60), '/'); // 60 days
33
34
        if (!is_readable($path)) {
35
            return $this->createError('File not found on disk, or not readable');
36
        }
37
38
        $resource = fopen($path, 'rb');
39
        if ($resource === false) {
40
            return $this->createError('Cannot open file on disk');
41
        }
42
43
        $size = filesize($path);
44
        $response = new Response($resource, 200, [
45
            'content-type' => 'application/pdf',
46
            'Content-Disposition' => 'attachment; filename="' . basename($path) . '"',
47
            'content-length' => $size,
48
        ]);
49
50
        return $response;
51
    }
52
}
53