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
|
8 |
|
public function __construct(string $uploadsDirectory) |
19
|
|
|
{ |
20
|
8 |
|
if (!is_dir($uploadsDirectory)) { |
21
|
|
|
throw new InvalidArgumentException('Directory ' . $uploadsDirectory . 'not found'); |
22
|
|
|
} |
23
|
|
|
|
24
|
8 |
|
$this->uploadsDirectory = $uploadsDirectory; |
25
|
8 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param ServerRequestInterface $request |
29
|
|
|
* @param array $args |
30
|
|
|
* @return ResponseInterface |
31
|
|
|
*/ |
32
|
|
|
public function downloadAction(ServerRequestInterface $request, array $args): ResponseInterface |
|
|
|
|
33
|
|
|
{ |
34
|
|
|
$file = $request->getQueryParams()['file']; |
35
|
|
|
|
36
|
|
|
if (file_exists('public' . $file)) { |
37
|
|
|
$path = 'public' . $file; |
38
|
|
|
} else if (!file_exists($this->uploadsDirectory . $file)) { |
39
|
|
|
throw new Exception($path . ' not found.', 404); |
40
|
|
|
} else { |
41
|
|
|
$path = $this->uploadsDirectory . $file; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
// magic_mime module installed? |
45
|
|
|
if (function_exists('mime_content_type')) { |
46
|
|
|
$mimeType = mime_content_type($path); |
47
|
|
|
} else if (function_exists('finfo_file')) { // or fileinfo module installed? |
48
|
|
|
$finfo = finfo_open(FILEINFO_MIME); // return mime type |
49
|
|
|
$mimeType = finfo_file($finfo, $path); |
50
|
|
|
finfo_close($finfo); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$contents = file_get_contents($path); |
54
|
|
|
$stream = new Stream('php://memory', 'r+'); |
55
|
|
|
$stream->write($contents); |
56
|
|
|
$response = new Response(); |
57
|
|
|
$response = $response->withBody($stream); |
58
|
|
|
$response = $response->withHeader('Content-Type', $mimeType); |
|
|
|
|
59
|
|
|
|
60
|
|
|
return $response; |
61
|
|
|
} |
62
|
|
|
} |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.