1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace AbterPhp\Files\Http\Controllers\Website; |
6
|
|
|
|
7
|
|
|
use AbterPhp\Files\Service\File\Downloader as DownloadService; |
8
|
|
|
use League\Flysystem\FilesystemException; |
9
|
|
|
use Opulence\Http\Responses\Response; |
10
|
|
|
use Opulence\Http\Responses\ResponseHeaders; |
11
|
|
|
use Opulence\Http\Responses\StreamResponse; |
12
|
|
|
use Opulence\Orm\OrmException; |
13
|
|
|
use Opulence\Routing\Controller; |
14
|
|
|
|
15
|
|
|
class File extends Controller |
16
|
|
|
{ |
17
|
|
|
/** @var DownloadService */ |
18
|
|
|
protected $downloadService; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* File constructor. |
22
|
|
|
* |
23
|
|
|
* @param DownloadService $downloadService |
24
|
|
|
*/ |
25
|
|
|
public function __construct(DownloadService $downloadService) |
26
|
|
|
{ |
27
|
|
|
$this->downloadService = $downloadService; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param string $filesystemName |
32
|
|
|
* |
33
|
|
|
* @return Response |
34
|
|
|
*/ |
35
|
|
|
public function download(string $filesystemName): Response |
36
|
|
|
{ |
37
|
|
|
try { |
38
|
|
|
$entity = $this->downloadService->getPublicFile($filesystemName); |
39
|
|
|
if (!$entity) { |
40
|
|
|
return new Response('', ResponseHeaders::HTTP_UNAUTHORIZED); |
41
|
|
|
} |
42
|
|
|
$streamCallable = $this->downloadService->getStream($entity); |
43
|
|
|
} catch (FilesystemException | OrmException $e) { |
44
|
|
|
return new Response('', ResponseHeaders::HTTP_UNAUTHORIZED); |
45
|
|
|
} catch (\Exception $e) { |
46
|
|
|
return new Response($e->getMessage(), ResponseHeaders::HTTP_INTERNAL_SERVER_ERROR); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return new StreamResponse( |
50
|
|
|
$streamCallable, |
51
|
|
|
ResponseHeaders::HTTP_OK, |
52
|
|
|
$this->getHeaders($entity->getPublicName()) |
53
|
|
|
); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param string $filename |
58
|
|
|
* |
59
|
|
|
* @return array |
60
|
|
|
*/ |
61
|
|
|
protected function getHeaders(string $filename): array |
62
|
|
|
{ |
63
|
|
|
return [ |
64
|
|
|
'Content-type' => 'application/octet-stream', |
65
|
|
|
'Content-Transfer-Encoding' => 'Binary', |
66
|
|
|
'Content-disposition' => sprintf('attachment; filename=%s', $filename), |
67
|
|
|
]; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|