Passed
Push — main ( 378ff3...fca707 )
by Sugeng
03:34
created

LocalAction::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace diecoding\flysystem\actions;
4
5
use diecoding\flysystem\LocalComponent;
6
use Yii;
7
use yii\base\Action;
8
use yii\helpers\Json;
9
use yii\web\NotFoundHttpException;
10
11
/**
12
 * LocalAction for handle LocalComponent.
13
 *
14
 * To use LocalAction, you need to do the following steps:
15
 *
16
 * First, declare an action of LocalAction 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\LocalAction::class,
25
 *             'component' => 'fs',
26
 *         ],
27
 *     ];
28
 * }
29
 * ```
30
 * 
31
 * @package diecoding\flysystem\actions
32
 * 
33
 * @link      https://sugengsulistiyawan.my.id/
34
 * @author    Sugeng Sulistiyawan <[email protected]>
35
 * @copyright Copyright (c) 2023
36
 */
37
class LocalAction extends Action
38
{
39
    /**
40
     * @var string flysystem component
41
     */
42
    public $component = 'fs';
43
44
    /**
45
     * @var mixed|LocalComponent
46
     */
47
    protected $filesystem;
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function init()
53
    {
54
        $this->filesystem = Yii::$app->get($this->component);
55
    }
56
57
    /**
58
     * Runs the action.
59
     *
60
     * @param string|null $data
61
     * @return mixed result content
62
     * @throws NotFoundHttpException if data not valid
63
     */
64
    public function run($data = null)
65
    {
66
        try {
67
            $params = Json::decode($this->filesystem->decrypt($data));
68
69
            $now     = time();
70
            $path    = (string) $params['path'];
71
            $expires = (int) $params['expires'];
72
            $config  = (array) $params['config'];
73
74
            if ($path === '' || $expires <= 0 || $expires < $now) {
75
                throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
76
            }
77
        } catch (\Throwable $th) {
78
            throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
79
        }
80
81
        return Yii::$app->getResponse()->sendFile($path, $config['attachmentName'], [
82
            'inline' => true,
83
        ]);
84
    }
85
}
86