Passed
Push — master ( 708038...0efc49 )
by Evgenii
04:54
created

FileCreateFromInstance::__construct()   C

Complexity

Conditions 12
Paths 20

Size

Total Lines 48
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 28
c 2
b 0
f 1
dl 0
loc 48
rs 6.9666
cc 12
nc 20
nop 4

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: floor12
5
 * Date: 01.01.2018
6
 * Time: 12:56
7
 */
8
9
namespace floor12\files\logic;
10
11
use floor12\files\models\File;
12
use floor12\files\models\FileType;
13
use Yii;
14
use yii\base\ErrorException;
15
use yii\web\BadRequestHttpException;
16
use yii\web\IdentityInterface;
17
use yii\web\UploadedFile;
18
19
/**
20
 * Class FileCreateFromInstance
21
 * @package floor12\files\logic
22
 */
23
class FileCreateFromInstance
24
{
25
    private $_model;
26
    private $_owner;
27
    private $_attribute;
28
    private $_instance;
29
    private $_fullPath;
30
    private $_onlyUploaded;
31
32
    public function __construct(UploadedFile $file, array $data, IdentityInterface $identity = null, $onlyUploaded = true)
33
    {
34
35
        $this->_onlyUploaded = $onlyUploaded;
36
37
        if (!isset($data['attribute']) || !$data['attribute'] || !isset($data['modelClass']) || !$data['modelClass'])
38
            throw new BadRequestHttpException("Attribute or class name not set.");
39
40
        // Загружаем полученные данные
41
        $this->_instance = $file;
42
        $this->_attribute = $data['attribute'];
43
44
        if (!file_exists($this->_instance->tempName))
45
            throw new ErrorException("Tmp file not found on disk.");
46
47
        // Инициализируем класс владельца файла для валидаций и ставим сценарий
48
        $this->_owner = new $data['modelClass'];
49
50
        if (isset($data['scenario']))
51
            $this->_owner->setScenario($data['scenario']);
52
53
54
        if (isset($this->_owner->behaviors['files']->attributes[$this->_attribute]['validator'])) {
55
            foreach ($this->_owner->behaviors['files']->attributes[$this->_attribute]['validator'] as $validator) {
56
                if (!$validator->validate($this->_instance, $error))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $error seems to be never defined.
Loading history...
57
                    throw new BadRequestHttpException($error);
58
            }
59
60
        }
61
62
        // Создаем модель нового файла и заполняем первоначальными данными
63
        $this->_model = new File();
64
        $this->_model->created = time();
65
        $this->_model->field = $this->_attribute;
66
        $this->_model->class = $data['modelClass'];
67
68
        $this->_model->filename = new PathGenerator(Yii::$app->getModule('files')->storageFullPath) . '.' . $this->_instance->extension;
69
        $this->_model->title = $this->_instance->name;
70
        $this->_model->content_type = $this->_instance->type;
71
        $this->_model->size = $this->_instance->size;
72
        $this->_model->type = $this->detectType();
0 ignored issues
show
Documentation Bug introduced by
The property $type was declared of type integer, but $this->detectType() is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
73
        if ($identity)
74
            $this->_model->user_id = $identity->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface yii\web\IdentityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
75
        if ($this->_model->type == FileType::VIDEO)
76
            $this->_model->video_status = 0;
77
78
        //Генерируем полный новый адрес сохранения файла
79
        $this->_fullPath = Yii::$app->getModule('files')->storageFullPath . DIRECTORY_SEPARATOR . $this->_model->filename;
0 ignored issues
show
Bug introduced by
Are you sure Yii::app->getModule('files')->storageFullPath of type mixed|null|object can be used in concatenation? ( Ignorable by Annotation )

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

79
        $this->_fullPath = /** @scrutinizer ignore-type */ Yii::$app->getModule('files')->storageFullPath . DIRECTORY_SEPARATOR . $this->_model->filename;
Loading history...
80
    }
81
82
    /**
83
     * @return string
84
     */
85
    public function detectType()
86
    {
87
        $contentTypeArray = explode('/', $this->_model->content_type);
88
        if ($contentTypeArray[0] == 'image')
89
            return FileType::IMAGE;
90
        if ($contentTypeArray[0] == 'video')
91
            return FileType::VIDEO;
92
        return FileType::FILE;
93
    }
94
95
    /**
96
     * @return File
97
     */
98
99
    public function execute()
100
    {
101
        $path = Yii::$app->getModule('files')->storageFullPath . $this->_model->filename;
0 ignored issues
show
Bug introduced by
Are you sure Yii::app->getModule('files')->storageFullPath of type mixed|null|object can be used in concatenation? ( Ignorable by Annotation )

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

101
        $path = /** @scrutinizer ignore-type */ Yii::$app->getModule('files')->storageFullPath . $this->_model->filename;
Loading history...
Unused Code introduced by
The assignment to $path is dead and can be removed.
Loading history...
102
103
        if ($this->_model->save()) {
104
            if (!$this->_onlyUploaded)
105
                copy($this->_instance->tempName, $this->_fullPath);
106
            else
107
                $this->_instance->saveAs($this->_fullPath, false);
108
        }
109
110
        if ($this->_model->type == FileType::IMAGE) {
111
            $this->resizeAfterUpload();
112
        }
113
114
        return $this->_model;
115
    }
116
117
118
    protected function resizeAfterUpload()
119
    {
120
        $maxWidth = $this->_owner->behaviors['files']->attributes[$this->_attribute]['maxWidth'] ?? 0;
121
        $maxHeight = $this->_owner->behaviors['files']->attributes[$this->_attribute]['maxHeight'] ?? 0;
122
123
        if ($maxWidth && $maxHeight) {
124
            $resizer = new FileResize($this->_model, $maxWidth, $maxHeight);
125
            $resizer->execute();
126
        }
127
128
    }
129
}