Passed
Push — master ( 107eb8...9e7413 )
by Aleksandr
02:36
created

Uploader::process()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 6
nop 0
dl 0
loc 20
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace carono\yii2file;
4
5
use Yii;
6
use yii\base\Component;
7
use yii\base\Security;
8
use yii\db\ActiveRecord;
9
use yii\db\Expression;
10
use yii\helpers\ArrayHelper;
11
use yii\helpers\FileHelper;
12
use yii\web\UploadedFile;
13
14
/**
15
 * Class FileUpload
16
 *
17
 * @package carono\components
18
 * @property string $fullName
19
 */
20
class Uploader extends Component
21
{
22
    /**
23
     * @var FileUploadTrait
24
     */
25
    public $modelClass;
26
    public $data;
27
    public $file;
28
    public $name;
29
    public $slug;
30
    public $uid;
31
    public $delete = true;
32
    public $folder;
33
34
    protected $fileName;
35
    protected $filePath;
36
37
    /**
38
     * @param $name
39
     * @return $this
40
     */
41
    public function name($name)
42
    {
43
        $this->name = $name;
44
        return $this;
45
    }
46
47
    /**
48
     * @param $data
49
     * @return $this
50
     */
51
    public function data($data)
52
    {
53
        $this->data = $data;
54
        return $this;
55
    }
56
57
    /**
58
     * @param $path
59
     * @return $this
60
     */
61
    public function folder($path)
62
    {
63
        $this->folder = $path;
64
        return $this;
65
    }
66
67
    /**
68
     * @param bool $deleteOnFinish
69
     * @return $this
70
     */
71
    public function delete($deleteOnFinish = true)
72
    {
73
        $this->delete = $deleteOnFinish;
74
        return $this;
75
    }
76
77
    /**
78
     * @return null|string
79
     */
80
    protected function getSession()
81
    {
82
        if (isset(Yii::$app->session)) {
83
            $session = Yii::$app->session->getIsActive() ? Yii::$app->session->getId() : null;
84
        } else {
85
            $session = null;
86
        }
87
        return $session;
88
    }
89
90
    /**
91
     * @return mixed
92
     */
93
    public function getFileName()
94
    {
95
        return $this->name ?: $this->fileName;
96
    }
97
98
    /**
99
     * @return string
100
     */
101
    protected function getFileNameWithOutExtension()
102
    {
103
        return basename($this->getFileName(), '.' . $this->getFileExtension());
104
    }
105
106
    /**
107
     * @return string
108
     */
109
    protected function getMimeType()
110
    {
111
        return FileHelper::getMimeType($this->filePath);
112
    }
113
114
    /**
115
     * @return mixed|string
116
     */
117
    protected function getFileExtension()
118
    {
119
        if (!$extension = strtolower(pathinfo($this->fileName, PATHINFO_EXTENSION))) {
120
            $extension = ArrayHelper::getValue(FileHelper::getExtensionsByMimeType($this->getMimeType()), 0);
121
        }
122
        return $extension;
123
    }
124
125
    /**
126
     * @return int|null|string
127
     */
128
    public function getUserId()
129
    {
130
        if (isset(Yii::$app->user)) {
131
            $userId = Yii::$app->user->getId();
132
        } else {
133
            $userId = null;
134
        }
135
        return $userId;
136
    }
137
138
    /**
139
     * @param $source
140
     * @param $destination
141
     * @throws \Exception
142
     */
143
    public function copy($source, $destination)
144
    {
145
        if (is_uploaded_file($source) && !move_uploaded_file($source, $destination)) {
146
            throw new \Exception('Unknown upload error');
147
        } elseif ($this->delete ? !rename($source, $destination) : !copy($source, $destination)) {
148
            throw new \Exception('Failed to write file to disk');
149
        }
150
    }
151
152
    /**
153
     * @return string
154
     */
155
    public function getUid()
156
    {
157
        return $this->uid = $this->uid ?: $this->formUid();
158
    }
159
160
    /**
161
     * @return string
162
     */
163
    public function getNewFileAlias()
164
    {
165
        return static::formAliasPath($this->getUid(), $this->folder);
166
    }
167
168
    /**
169
     * @param ActiveRecord $model
170
     * @param $attributes
171
     */
172
    public function loadAttributes($model, $attributes)
173
    {
174
        $model->setAttributes($attributes);
175
    }
176
177
    public function formAttributes()
178
    {
179
        $this->processFilePath($this->file);
180
        return [
181
            'session' => $this->getSession(),
182
            'name' => $this->getFileNameWithOutExtension(),
183
            'extension' => $this->getFileExtension(),
184
            'user_id' => $this->getUserId(),
185
            'uid' => $this->getUid(),
186
            'data' => !is_null($this->data) ? json_encode($this->data) : null,
187
            'mime_type' => $this->getMimeType(),
188
            'md5' => md5_file($this->filePath),
189
            'folder' => static::formAliasPath($this->getUid(), $this->folder),
190
            'slug' => $this->slug,
191
            'size' => filesize($this->filePath)
192
        ];
193
    }
194
195
    /**
196
     * @return FileUploadTrait|null
197
     * @throws \Exception
198
     */
199
    public function process()
200
    {
201
        /**
202
         * @var FileUploadTrait $model
203
         */
204
        $model = new $this->modelClass();
205
        $this->loadAttributes($model, $this->formAttributes());
0 ignored issues
show
Bug introduced by
$model of type carono\yii2file\FileUploadTrait is incompatible with the type yii\db\ActiveRecord expected by parameter $model of carono\yii2file\Uploader::loadAttributes(). ( Ignorable by Annotation )

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

205
        $this->loadAttributes(/** @scrutinizer ignore-type */ $model, $this->formAttributes());
Loading history...
206
        $newFilePath = $model->getRealFilePath();
207
        if (!is_dir($realFolder = dirname($newFilePath))) {
208
            mkdir($realFolder, 0777, true);
209
        }
210
        if (!file_exists($this->filePath)) {
211
            throw new \Exception('File not loaded or not exist');
212
        }
213
        $this->copy($this->filePath, $newFilePath);
214
        if ($model->save()) {
0 ignored issues
show
Bug introduced by
It seems like save() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

214
        if ($model->/** @scrutinizer ignore-call */ save()) {
Loading history...
215
            return $model;
216
        } else {
217
            $model->deleteFile();
218
            return null;
219
        }
220
    }
221
222
    /**
223
     * @param $file
224
     */
225
    protected function processFilePath($file)
226
    {
227
        if (strpos($file, 'http') === 0) {
228
            $tmp = Yii::getAlias('@runtime') . DIRECTORY_SEPARATOR . uniqid("fu");
229
            file_put_contents($tmp, file_get_contents($file));
230
            $this->filePath = $tmp;
231
            $this->fileName = basename($file);
232
        } elseif (is_string($file)) {
233
            $this->filePath = Yii::getAlias($file);
234
            $this->fileName = basename($this->filePath);
235
        } elseif ($file instanceof UploadedFile) {
236
            $this->filePath = $file->tempName;
237
            $this->fileName = $file->name;
238
        }
239
    }
240
241
    /**
242
     * @param $slug
243
     * @return $this
244
     */
245
    public function slug($slug)
246
    {
247
        $this->slug = $slug;
248
        return $this;
249
    }
250
251
    /**
252
     * @return string
253
     */
254
    protected function generateUid()
255
    {
256
        $sec = new Security();
257
        return md5($sec->generateRandomString(64));
258
    }
259
260
    /**
261
     * @return string
262
     */
263
    protected function formUid()
264
    {
265
        $class = $this->modelClass;
266
        do {
267
            $uPath = $this->generateUid();
268
        } while ($class::find()->where(["uid" => $uPath])->exists());
269
        return $uPath;
270
    }
271
272
    /**
273
     * @param $path
274
     * @param null|string $aliasPrefix
275
     * @return string
276
     */
277
    public static function formAliasPath($path, $aliasPrefix = null)
278
    {
279
        $p = $aliasPrefix ? [$aliasPrefix] : [];
280
        for ($i = 0; $i < 3; $i++) {
281
            $p[] = $path[$i];
282
        }
283
        return join('/', $p);
284
    }
285
}