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