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