1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bone\Controller; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
8
|
|
|
use Laminas\Diactoros\Response; |
9
|
|
|
use Laminas\Diactoros\Stream; |
10
|
|
|
|
11
|
|
|
class DownloadController |
12
|
|
|
{ |
13
|
|
|
/** @var string $uploadsDirectory */ |
14
|
|
|
private $uploadsDirectory; |
15
|
|
|
|
16
|
5 |
|
public function __construct(string $uploadsDirectory) |
17
|
|
|
{ |
18
|
5 |
|
if (!is_dir($uploadsDirectory)) { |
19
|
1 |
|
throw new InvalidArgumentException('Directory ' . $uploadsDirectory . ' not found'); |
20
|
|
|
} |
21
|
|
|
|
22
|
4 |
|
$this->uploadsDirectory = $uploadsDirectory; |
23
|
4 |
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param ServerRequestInterface $request |
27
|
|
|
* @return ResponseInterface |
28
|
|
|
* @throws ControllerException |
29
|
|
|
*/ |
30
|
4 |
|
public function downloadAction(ServerRequestInterface $request): ResponseInterface |
31
|
|
|
{ |
32
|
4 |
|
$queryParams = $request->getQueryParams(); |
33
|
4 |
|
$path = $this->getFilePath($queryParams); |
34
|
2 |
|
$mimeType = $this->getMimeType($path); |
35
|
2 |
|
$contents = file_get_contents($path); |
36
|
2 |
|
$stream = new Stream('php://memory', 'r+'); |
37
|
2 |
|
$stream->write($contents); |
38
|
2 |
|
$response = new Response(); |
39
|
2 |
|
$response = $response->withBody($stream); |
40
|
2 |
|
$response = $response->withHeader('Content-Type', $mimeType); |
41
|
|
|
|
42
|
2 |
|
return $response; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param string $path |
47
|
|
|
* @return string |
48
|
|
|
*/ |
49
|
2 |
|
private function getMimeType(string $path): string |
50
|
|
|
{ |
51
|
2 |
|
$finfo = finfo_open(FILEINFO_MIME); // return mime type |
52
|
2 |
|
$mimeType = finfo_file($finfo, $path); |
53
|
2 |
|
finfo_close($finfo); |
54
|
|
|
|
55
|
2 |
|
return $mimeType; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param array $queryParams |
60
|
|
|
* @return string |
61
|
|
|
* @throws ControllerException |
62
|
|
|
*/ |
63
|
4 |
|
private function getFilePath(array $queryParams): string |
64
|
|
|
{ |
65
|
4 |
|
if (!isset($queryParams['file'])) { |
66
|
1 |
|
throw new ControllerException('Invalid Request.', 400); |
67
|
|
|
} |
68
|
|
|
|
69
|
3 |
|
$file = $queryParams['file']; |
70
|
3 |
|
$path = $this->uploadsDirectory . $file; |
71
|
|
|
|
72
|
3 |
|
if (file_exists('public' . $file)) { |
73
|
1 |
|
$path = 'public' . $file; |
74
|
2 |
|
} else if (!file_exists($path)) { |
75
|
1 |
|
throw new ControllerException($path . ' not found.', 404); |
76
|
|
|
} |
77
|
|
|
|
78
|
2 |
|
return $path; |
79
|
|
|
} |
80
|
|
|
} |