Completed
Push — master ( 82c5ce...eed948 )
by Igor
02:14
created

File::attributeLabels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 4
Bugs 0 Features 2
Metric Value
c 4
b 0
f 2
dl 0
loc 18
ccs 0
cts 0
cp 0
rs 9.4285
cc 1
eloc 15
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * @link https://github.com/rkit/filemanager-yii2
5
 * @copyright Copyright (c) 2015 Igor Romanov
6
 * @license [MIT](http://opensource.org/licenses/MIT)
7
 */
8
9
namespace rkit\filemanager\models;
10
11
use Yii;
12
use yii\base\InvalidParamException;
13
use yii\behaviors\TimestampBehavior;
14
use yii\helpers\FileHelper;
15
use rkit\filemanager\Storage;
16
17
/**
18
 * ActiveRecord for table "file"
19
 *
20
 * @property integer $id
21
 * @property integer $user_id
22
 * @property integer $owner_id
23
 * @property integer $owner_type
24
 * @property string $title
25
 * @property string $name
26
 * @property integer $size
27
 * @property string $extension
28
 * @property string $mime
29
 * @property string $date_create
30
 * @property string $date_update
31
 * @property integer $ip
32
 * @property integer $tmp
33
 * @property integer $position
34
 * @property integer $protected
35
 */
36
class File extends \yii\db\ActiveRecord
37
{
38
    /**
39
     * @var string
40
     */
41
    public $path;
42
    /**
43
     * @var Storage
44
     */
45
    private $storage;
46
47
    /**
48
     * @inheritdoc
49
     * @codeCoverageIgnore
50
     * @internal
51
     */
52
    public static function tableName()
53
    {
54
        return 'file';
55
    }
56
57
    /**
58
     * @inheritdoc
59
     * @codeCoverageIgnore
60
     * @internal
61
     */
62
    public function attributeLabels()
63
    {
64
        return [
65
            'id' => Yii::t('filemanager-yii2', 'ID'),
66
            'user_id' => Yii::t('filemanager-yii2', 'User'),
67
            'owner_id' => Yii::t('filemanager-yii2', 'Owner'),
68
            'owner_type' => Yii::t('filemanager-yii2', 'Owner type'),
69
            'title' => Yii::t('filemanager-yii2', 'Title'),
70
            'name' => Yii::t('filemanager-yii2', 'Name'),
71
            'size' => Yii::t('filemanager-yii2', 'Size'),
72
            'extension' => Yii::t('filemanager-yii2', 'Extension'),
73
            'mime' => Yii::t('filemanager-yii2', 'Mime'),
74
            'date_create' => Yii::t('filemanager-yii2', 'Date create'),
75
            'date_update' => Yii::t('filemanager-yii2', 'Date update'),
76
            'ip' => Yii::t('filemanager-yii2', 'IP'),
77
            'position' => Yii::t('filemanager-yii2', 'Position'),
78
        ];
79
    }
80
81
    /**
82
     * @inheritdoc
83
     * @internal
84
     */
85 37
    public function behaviors()
86
    {
87
        return [
88
            [
89 37
                'class' => TimestampBehavior::className(),
90 37
                'createdAtAttribute' => 'date_create',
91 37
                'updatedAtAttribute' => 'date_update',
92 37
                'value' => new \yii\db\Expression('NOW()'),
93 37
            ],
94 37
        ];
95
    }
96
97
    /**
98
     * @inheritdoc
99
     * @codeCoverageIgnore
100
     * @internal
101
     */
102
    public function events()
103
    {
104
        return [
105
            \yii\db\ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
106
        ];
107
    }
108
109
    /**
110
     * @internal
111
     */
112 34
    public function beforeSave($insert)
113
    {
114 34
        if (parent::beforeSave($insert)) {
115 34
            if ($insert) {
116 34
                if (!file_exists($this->path)) {
117 1
                    return false;
118
                }
119
120 33
                $this->fillUserInfo();
121 33
                $this->fillMetaInfo();
122
123 33
                if ($this->owner_id === null) {
124 33
                    $this->owner_id = 0;
125 33
                }
126 33
            }
127
128 33
            return true;
129
        }
130
131
        return false; // @codeCoverageIgnore
132
    }
133
134 33
    private function fillUserInfo()
135
    {
136 33
        if (!Yii::$app instanceof \yii\console\Application) {
137
            $this->user_id = Yii::$app->user->isGuest ? 0 : Yii::$app->user->id; // @codeCoverageIgnore
138
            $this->ip = ip2long(Yii::$app->request->getUserIP()); // @codeCoverageIgnore
139
        } // @codeCoverageIgnore
140 33
    }
141
142 33
    private function fillMetaInfo()
143
    {
144 33
        $pathInfo = pathinfo($this->path);
145
146 33
        if ($this->title === null) {
147 6
            $this->title = $pathInfo['filename'];
148 6
        }
149
150 33
        $this->size = filesize($this->path);
151 33
        $this->mime = FileHelper::getMimeType($this->path);
152 33
        $this->extension = $this->getExtensionByMimeType($this->mime);
153 33
        $this->name = $this->generateName();
154 33
    }
155
156 33
    private function getExtensionByMimeType($mimeType)
157
    {
158 33
        $extensions = FileHelper::getExtensionsByMimeType($mimeType);
159 33
        $pathInfo = pathinfo($this->path);
160 33
        $titleInfo = pathinfo($this->title);
161
162 33
        if (isset($pathInfo['extension'])) {
163 31
            $extension = $pathInfo['extension'];
164 33
        } elseif (isset($titleInfo['extension'])) {
165 1
            $extension = $titleInfo['extension'];
166 1
        } else {
167 1
            $extension = explode('/', $mimeType);
168 1
            $extension = end($extension);
169
        }
170
171 33
        if (array_search($extension, $extensions) !== false) {
172 32
            return $extension;
173
        }
174
175 1
        return current($extensions);
176
    }
177
178
    /**
179
     * Set a storage
180
     *
181
     * @param Storage $storage The Strorage for the file
182
     * @return string
183
     */
184 34
    public function setStorage(Storage $storage)
185
    {
186 34
        $this->storage = $storage;
187 34
        $this->storage->setFile($this);
188
189 34
        return $this;
190
    }
191
192
    /**
193
     * Get a storage
194
     *
195
     * @return string
196
     * @throws InvalidParamException
197
     */
198 35
    public function getStorage()
199
    {
200 35
        if ($this->storage === null) {
201 1
            throw new InvalidParamException('The storage is not initialized');
202
        }
203
204 34
        return $this->storage;
205
    }
206
207
    /**
208
     * Generate a name
209
     *
210
     * @return string
211
     */
212 33
    public function generateName()
213
    {
214 33
        $name = date('YmdHis') . substr(md5(microtime() . uniqid()), 0, 10);
215 33
        return $name . '.' . $this->extension;
216
    }
217
218
    /**
219
     * Checks whether the file is protected
220
     *
221
     * @return bool
222
     */
223 34
    public function isProtected()
224
    {
225 34
        return (bool)$this->protected;
226
    }
227
228
    /**
229
     * Checks whether the file is unprotected
230
     *
231
     * @return bool
232
     */
233 3
    public function isUnprotected()
234
    {
235 3
        return (bool)$this->protected === false;
236
    }
237
238
    /**
239
     * Checks whether the file is temp
240
     *
241
     * @return bool
242
     */
243 12
    public function isTmp()
244
    {
245 12
        return (bool)$this->tmp;
246
    }
247
248
    /**
249
     * Get date create of file in format `Ym`
250
     *
251
     * @return string
252
     */
253 33
    public function getDateOfFile()
254
    {
255 33
        if ($this->isNewRecord || is_object($this->date_create)) {
256 33
            return date('Ym');
257
        } else {
258 22
            return date_format(date_create($this->date_create), 'Ym');
259
        }
260
    }
261
262
    /**
263
     * Checks whether the owner of the file
264
     *
265
     * @param int $ownerId The id of the owner
266
     * @param int $ownerType The type of the owner
267
     * @return bool
268
     */
269 20
    public function isOwner($ownerId, $ownerType)
270
    {
271 20
        $ownerType = $this->owner_type === $ownerType;
272 20
        $ownerId = $this->owner_id === $ownerId;
273 20
        $user = $this->user_id === Yii::$app->user->id || $this->user_id === 0;
274
275 20
        return (!$this->tmp && $ownerType && $ownerId) || ($this->tmp && $ownerType && $user);
276
    }
277
278
    /**
279
     * Find all by owner
280
     *
281
     * @param int $ownerId The id of the owner
282
     * @param int $ownerType The type of the owner
283
     * @return array
284
     */
285 18
    public static function findAllByOwner($ownerId, $ownerType)
286
    {
287 18
        return static::find()
288 18
            ->where(['owner_id' => $ownerId, 'owner_type' => $ownerType])
289 18
            ->orderBy('position ASC')
290 18
            ->all();
291
    }
292
293
    /**
294
     * Find one by owner
295
     *
296
     * @param int $ownerId The id of the owner
297
     * @param int $ownerType The type of the owner
298
     * @return File|null
299
     */
300 1
    public static function findOneByOwner($ownerId, $ownerType)
301
    {
302 1
        return static::find()
303 1
            ->where(['owner_id' => $ownerId, 'owner_type' => $ownerType])
304 1
            ->one();
305
    }
306
307
    /**
308
     * Delete by owner
309
     *
310
     * @param Storage $storage The storage of the file
311
     * @param int $ownerId The id of the owner
312
     * @param int $ownerType The type of the owner
313
     */
314 3
    public function deleteByOwner($storage, $ownerId, $ownerType)
315
    {
316 3
        $files = self::findAllByOwner($ownerId, $ownerType);
317
318 3
        foreach ($files as $file) {
319 3
            $file->setStorage($storage);
320 3
            $file->delete();
321 3
        }
322 3
    }
323
324
    /**
325
     * Deleting a file from the db and from the file system
326
     * @internal
327
     *
328
     * @return bool
329
     */
330 7
    public function beforeDelete()
331
    {
332 7
        $this->getStorage()->delete();
333 7
        return true;
334
    }
335
}
336