Completed
Push — master ( c5eccd...ec8b64 )
by Evgenii
04:45
created

GetPreviewAction::sendPreview()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 12
c 1
b 0
f 1
dl 0
loc 16
rs 9.8666
cc 2
nc 2
nop 1
1
<?php
2
3
namespace floor12\files\actions;
4
5
use floor12\files\logic\ImagePreviewer;
6
use floor12\files\models\File;
7
use Yii;
8
use yii\web\NotFoundHttpException;
9
use yii\web\Response;
10
11
12
class GetPreviewAction extends \yii\base\Action
13
{
14
    const HEADER_CACHE_TIME = 60 * 60 * 24 * 15;
15
16
    /** @var int */
17
    protected $width;
18
    /** @var File */
19
    protected $model;
20
21
    /**
22
     * @param $hash
23
     * @param null $width
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $width is correct as it would always require null to be passed?
Loading history...
24
     * @param null $webp
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $webp is correct as it would always require null to be passed?
Loading history...
25
     * @throws NotFoundHttpException
26
     * @throws \yii\base\InvalidConfigException
27
     * @throws \yii\web\RangeNotSatisfiableHttpException
28
     */
29
    public function run($hash, $width = null, $webp = null)
0 ignored issues
show
Unused Code introduced by
The parameter $webp is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

29
    public function run($hash, $width = null, /** @scrutinizer ignore-unused */ $webp = null)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
30
    {
31
32
        $this->loadAndCheckModel($hash);
33
        $this->width = $width;
34
35
        if ($width) {
0 ignored issues
show
introduced by
$width is of type null, thus it always evaluated to false.
Loading history...
36
            $this->sendPreview($width);
37
        } else {
38
            $this->sendAsIs();
39
        }
40
    }
41
42
    /**
43
     * @param string $hash
44
     * @throws NotFoundHttpException
45
     */
46
    private function loadAndCheckModel(string $hash): void
47
    {
48
        $this->model = File::findOne(['hash' => $hash]);
49
        if (!$this->model)
50
            throw new NotFoundHttpException("Запрашиваемый файл не найден");
51
52
        if (!$this->model->isImage() && !$this->model->isVideo())
53
            throw new NotFoundHttpException("Запрашиваемый файл не является изображением");
54
55
        if (!file_exists($this->model->rootPath))
56
            throw new NotFoundHttpException('Запрашиваемый файл не найден на диске.');
57
    }
58
59
    /**
60
     * @param $width
61
     * @throws NotFoundHttpException
62
     * @throws \yii\base\InvalidConfigException
63
     */
64
    protected function sendPreview($width)
65
    {
66
        $filename = Yii::createObject(ImagePreviewer::class, [$this->model, $width, $webp])->getUrl();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $webp seems to be never defined.
Loading history...
67
68
        if (!file_exists($filename))
69
            throw new NotFoundHttpException('Запрашиваемый файл не найден на диске.');
70
71
        $response = Yii::$app->response;
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::app->response can also be of type yii\web\Response. However, the property $response is declared as type yii\console\Response. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
72
        $response->format = Response::FORMAT_RAW;
73
        $coontentType = mime_content_type($filename);
74
        $this->setHeaders($response, $coontentType, md5($this->model->created));
75
        $stream = fopen($filename, 'rb');
76
        Yii::$app->response->sendStreamAsFile($stream, $this->model->title, [
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $handle of yii\web\Response::sendStreamAsFile() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

76
        Yii::$app->response->sendStreamAsFile(/** @scrutinizer ignore-type */ $stream, $this->model->title, [
Loading history...
77
            'inline' => true,
78
            'mimeType' => $this->model->content_type,
79
            'filesize' => $this->model->size
80
        ]);
81
    }
82
83
    /**
84
     * @param string $coontentType
85
     * @param string $etag
86
     */
87
    private function setHeaders($response, string $coontentType, string $etag): void
88
    {
89
        $response->headers->set('Last-Modified', date("c", $this->model->created));
90
        $response->headers->set('Cache-Control', 'public, max-age=' . self::HEADER_CACHE_TIME);
91
        $response->headers->set('Content-Type', $coontentType . '; charset=utf-8');
92
        $response->headers->set('ETag', $etag);
93
    }
94
95
    /**
96
     * @throws \yii\web\RangeNotSatisfiableHttpException
97
     */
98
    protected function sendAsIs()
99
    {
100
        $stream = fopen($this->model->rootPath, 'rb');
101
        Yii::$app->response->sendStreamAsFile($stream, $this->model->title, [
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $handle of yii\web\Response::sendStreamAsFile() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

101
        Yii::$app->response->sendStreamAsFile(/** @scrutinizer ignore-type */ $stream, $this->model->title, [
Loading history...
102
            'inline' => true,
103
            'mimeType' => $this->model->content_type,
104
            'filesize' => $this->model->size
105
        ]);
106
    }
107
}
108