1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace diecoding\flysystem\actions; |
4
|
|
|
|
5
|
|
|
use DateTimeImmutable; |
6
|
|
|
use Yii; |
7
|
|
|
use yii\base\Action; |
8
|
|
|
use yii\helpers\Json; |
9
|
|
|
use yii\web\NotFoundHttpException; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* FileAction for handle LocalComponent. |
13
|
|
|
* |
14
|
|
|
* To use FileAction, you need to do the following steps: |
15
|
|
|
* |
16
|
|
|
* First, declare an action of FileAction type in the `actions()` method of your `SiteController` |
17
|
|
|
* class (or whatever controller you prefer), like the following: |
18
|
|
|
* |
19
|
|
|
* ```php |
20
|
|
|
* public function actions() |
21
|
|
|
* { |
22
|
|
|
* return [ |
23
|
|
|
* 'file' => [ |
24
|
|
|
* 'class' => \diecoding\flysystem\actions\FileAction::class, |
25
|
|
|
* 'component' => 'fs', |
26
|
|
|
* ], |
27
|
|
|
* ]; |
28
|
|
|
* } |
29
|
|
|
* ``` |
30
|
|
|
* |
31
|
|
|
* @link https://sugengsulistiyawan.my.id/ |
32
|
|
|
* @author Sugeng Sulistiyawan <[email protected]> |
33
|
|
|
* @copyright Copyright (c) 2023 |
34
|
|
|
*/ |
35
|
|
|
class FileAction extends Action |
36
|
|
|
{ |
37
|
|
|
/** |
38
|
|
|
* @var string filesystem config component (fs) |
39
|
|
|
*/ |
40
|
|
|
public $component = 'fs'; |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Runs the action. |
44
|
|
|
* |
45
|
|
|
* @param string|null $data |
46
|
|
|
* @return mixed result content |
47
|
|
|
* @throws NotFoundHttpException if data not valid |
48
|
|
|
*/ |
49
|
|
|
public function run($data = null) |
50
|
|
|
{ |
51
|
|
|
/** @var \diecoding\flysystem\AbstractComponent|mixed $filesystem */ |
52
|
|
|
$filesystem = Yii::$app->get($this->component); |
53
|
|
|
|
54
|
|
|
try { |
55
|
|
|
$params = Json::decode($filesystem->/** @scrutinizer ignore-call */decrypt($data)); |
56
|
|
|
|
57
|
|
|
$now = (int) (new DateTimeImmutable())->getTimestamp(); |
58
|
|
|
$expires = (int) $params['expires']; |
59
|
|
|
|
60
|
|
|
if (!$filesystem->fileExists($params['path']) || ($expires > 0 && $expires < $now)) { |
61
|
|
|
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.')); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$attachmentName = (string) pathinfo($params['path'], PATHINFO_BASENAME); |
65
|
|
|
$content = $filesystem->read($params['path']); |
66
|
|
|
$mimeType = $filesystem->mimeType($params['path']); |
67
|
|
|
} catch (\Throwable $th) { |
68
|
|
|
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.')); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return Yii::$app->getResponse()->sendContentAsFile($content, $attachmentName, [ |
72
|
|
|
'mimeType' => $mimeType, |
73
|
|
|
'inline' => true, |
74
|
|
|
]); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|