1 | <?php |
||
12 | trait Download |
||
13 | { |
||
14 | /** |
||
15 | * Download a file |
||
16 | * @param string $filePath Server path to file to download |
||
17 | * @param string|null $fileName Name + extension for the user to download |
||
18 | * @param bool $forceDownload Force file to be downloaded. If false, displays file in browser |
||
19 | * @throws \FMUP\Exception |
||
20 | */ |
||
21 | 3 | public function download($filePath, $fileName = null, $forceDownload = true) |
|
22 | { |
||
23 | 3 | if (!$this instanceof \FMUP\Controller) { |
|
24 | 1 | throw new \FMUP\Exception('Unable to use Download trait'); |
|
25 | } |
||
26 | 2 | if (!file_exists($filePath)) { |
|
27 | 1 | if ($this instanceof Logger\LoggerInterface && $this->hasLogger()) { |
|
28 | 1 | $this->getLogger()->log( |
|
29 | 1 | Logger\Channel\System::NAME, |
|
30 | 1 | Logger::ERROR, |
|
31 | 1 | 'Unable to find requested file', |
|
32 | 1 | array('filePath' => $filePath) |
|
33 | ); |
||
34 | } |
||
35 | 1 | throw new \FMUP\Exception\Status\NotFound('Unable to find requested file'); |
|
36 | } |
||
37 | 1 | $fileName = $fileName ? $fileName : basename($filePath); |
|
38 | 1 | $fInfo = new \finfo(); |
|
39 | 1 | $mimeType = $fInfo->file($filePath, FILEINFO_MIME_TYPE); |
|
40 | /** @var $this $this */ |
||
41 | 1 | $this->downloadHeaders($mimeType, $fileName, $forceDownload)->send(); |
|
42 | 1 | $file = fopen($filePath, 'r'); |
|
43 | 1 | ini_set('max_execution_time', 0); //@todo find a better way |
|
44 | 1 | while (!feof($file)) { |
|
45 | 1 | echo fread($file, 4096); |
|
46 | 1 | $this->obFlush(); |
|
47 | } |
||
48 | 1 | fclose($file); |
|
49 | /** @var $this \FMUP\Controller */ |
||
50 | 1 | $this->getResponse()->clearHeader(); |
|
51 | 1 | } |
|
52 | |||
53 | /** |
||
54 | * @codeCoverageIgnore |
||
55 | */ |
||
56 | protected function obFlush() |
||
60 | |||
61 | /** |
||
62 | * Set header to download a file |
||
63 | * @param string $mimeType Mime Type to render |
||
64 | * @param string|null $fileName Name + extension for the user to download |
||
65 | * @param bool $forceDownload Force file to be downloaded. If false, displays file in browser |
||
66 | * @return \FMUP\Response |
||
67 | * @throws \FMUP\Exception |
||
68 | */ |
||
69 | 2 | public function downloadHeaders($mimeType, $fileName = null, $forceDownload = true) |
|
87 | } |
||
88 |