Completed
Push — master ( 9b439e...de8363 )
by Igor
03:05
created

File::setStorage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1
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
 * This is the model class 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
     */
51
    public static function tableName()
52
    {
53
        return 'file';
54
    }
55
56
    /**
57
     * @inheritdoc
58
     * @codeCoverageIgnore
59
     */
60
    public function attributeLabels()
61
    {
62
        return [
63
            'id' => Yii::t('filemanager-yii2', 'ID'),
64
            'user_id' => Yii::t('filemanager-yii2', 'User'),
65
            'owner_id' => Yii::t('filemanager-yii2', 'Owner'),
66
            'owner_type' => Yii::t('filemanager-yii2', 'Owner type'),
67
            'title' => Yii::t('filemanager-yii2', 'Title'),
68
            'name' => Yii::t('filemanager-yii2', 'Name'),
69
            'size' => Yii::t('filemanager-yii2', 'Size'),
70
            'extension' => Yii::t('filemanager-yii2', 'Extension'),
71
            'mime' => Yii::t('filemanager-yii2', 'Mime'),
72
            'date_create' => Yii::t('filemanager-yii2', 'Date create'),
73
            'date_update' => Yii::t('filemanager-yii2', 'Date update'),
74
            'ip' => Yii::t('filemanager-yii2', 'IP'),
75
            'position' => Yii::t('filemanager-yii2', 'Position'),
76
        ];
77
    }
78
79
    /**
80
     * @inheritdoc
81
     */
82 38
    public function behaviors()
83
    {
84
        return [
85
            [
86 38
                'class' => TimestampBehavior::className(),
87 38
                'createdAtAttribute' => 'date_create',
88 38
                'updatedAtAttribute' => 'date_update',
89 38
                'value' => new \yii\db\Expression('NOW()'),
90 38
            ],
91 38
        ];
92
    }
93
94
    /**
95
     * @inheritdoc
96
     * @codeCoverageIgnore
97
     */
98
    public function events()
99
    {
100
        return [
101
            \yii\db\ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
102
        ];
103
    }
104
105 35
    public function beforeSave($insert)
106
    {
107 35
        if (parent::beforeSave($insert)) {
108 35
            if ($insert) {
109 35
                if (!file_exists($this->path)) {
110 1
                    return false;
111
                }
112 34
                if (!Yii::$app instanceof \yii\console\Application) {
113
                    $this->user_id = Yii::$app->user->isGuest ? 0 : Yii::$app->user->id; // @codeCoverageIgnore
114
                    $this->ip = ip2long(Yii::$app->request->getUserIP()); // @codeCoverageIgnore
115
                } // @codeCoverageIgnore
116
117 34
                $pathInfo = pathinfo($this->path);
118
119 34
                $this->size = filesize($this->path);
120 34
                $this->mime = FileHelper::getMimeType($this->path);
121 34
                $this->title = $pathInfo['filename'];
122 34
                $this->extension = current(FileHelper::getExtensionsByMimeType($this->mime));
123 34
                $this->name = $this->generateName();
124 34
            }
125
126 34
            return true;
127
        }
128
129
        return false; // @codeCoverageIgnore
130
    }
131
132 35
    public function setStorage(Storage $storage)
133
    {
134 35
        $this->storage = $storage;
135 35
        $this->storage->setFile($this);
136
137 35
        return $this;
138
    }
139
140 36
    public function getStorage()
141
    {
142 36
        if ($this->storage === null) {
143 1
            throw new InvalidParamException('The storage is not initialized');
144
        }
145
146 35
        return $this->storage;
147
    }
148
149
    /**
150
     * Generate a name
151
     *
152
     * @return string
153
     */
154 34
    public function generateName()
155
    {
156 34
        $name = date('YmdHis') . substr(md5(microtime() . uniqid()), 0, 10);
157 34
        return $name . '.' . $this->extension;
158
    }
159
160
    /**
161
     * Is it protected?
162
     *
163
     * @return bool
164
     */
165 35
    public function isProtected()
166
    {
167 35
        return (bool)$this->protected;
168
    }
169
170
    /**
171
     * Is it unprotected?
172
     *
173
     * @return bool
174
     */
175 5
    public function isUnprotected()
176
    {
177 5
        return (bool)$this->protected === false;
178
    }
179
180
    /**
181
     * Is it tmp a file?
182
     *
183
     * @return bool
184
     */
185 6
    public function isTmp()
186
    {
187 6
        return (bool)$this->tmp;
188
    }
189
190
    /**
191
     * Get date create of file in format `Ym`
192
     *
193
     * @return string
194
     */
195 34
    public function getDateOfFile()
196
    {
197 34
        if ($this->isNewRecord || is_object($this->date_create)) {
198 34
            return date('Ym');
199
        } else {
200 28
            return date_format(date_create($this->date_create), 'Ym');
201
        }
202
    }
203
204
    /**
205
     * Check owner
206
     *
207
     * @param int $ownerId
208
     * @param int $ownerType
209
     * @return bool
210
     */
211 26
    public function isOwner($ownerId, $ownerType)
212
    {
213 26
        $ownerType = $this->owner_type === $ownerType;
214 26
        $ownerId = $this->owner_id === $ownerId;
215 26
        $user = $this->user_id === Yii::$app->user->id || $this->user_id === 0;
216
217 26
        return (!$this->tmp && $ownerType && $ownerId) || ($this->tmp && $ownerType && $user);
218
    }
219
220
    /**
221
     * Create a file
222
     *
223
     * @param string $path
224
     * @param int $ownerId
225
     * @param int $ownerType
226
     * @param bool $temporary
227
     * @param bool $protected
228
     * @return File|bool
229
     */
230 35
    public static function create($path, $ownerId, $ownerType, $temporary, $protected)
231
    {
232 35
        $file = new File();
233 35
        $file->path = $path;
234 35
        $file->tmp = $temporary;
235 35
        $file->owner_id = $ownerId;
236 35
        $file->owner_type = $ownerType;
237 35
        $file->protected = $protected;
238
239 35
        if ($file->save()) {
240 34
            return $file;
241
        }
242
243 1
        return false;
244
    }
245
246
    /**
247
     * Find all by owner
248
     *
249
     * @param int $ownerId
250
     * @param int $ownerType
251
     * @return array
252
     */
253 26
    public static function findAllByOwner($ownerId, $ownerType)
254
    {
255 26
        return static::find()
256 26
            ->where(['owner_id' => $ownerId, 'owner_type' => $ownerType])
257 26
            ->orderBy('position ASC')
258 26
            ->all();
259
    }
260
261
    /**
262
     * Find one by owner
263
     *
264
     * @param int $ownerId
265
     * @param int $ownerType
266
     * @return File
267
     */
268 1
    public static function findOneByOwner($ownerId, $ownerType)
269
    {
270 1
        return static::find()
0 ignored issues
show
Bug Compatibility introduced by
The expression static::find()->where(ar...=> $ownerType))->one(); of type yii\db\ActiveRecord|array|null adds the type array to the return on line 270 which is incompatible with the return type documented by rkit\filemanager\models\File::findOneByOwner of type rkit\filemanager\models\File|null.
Loading history...
271 1
            ->where(['owner_id' => $ownerId, 'owner_type' => $ownerType])
272 1
            ->one();
273
    }
274
275
    /**
276
     * Delete by owner
277
     *
278
     * @param Storage $storage
279
     * @param int $ownerId
280
     * @param int $ownerType
281
     */
282 4
    public function deleteByOwner($storage, $ownerId, $ownerType)
283
    {
284 4
        $files = self::findAllByOwner($ownerId, $ownerType);
285
286 4
        foreach ($files as $file) {
287 4
            $file->setStorage($storage);
288 4
            $file->delete();
289 4
        }
290 4
    }
291
292
    /**
293
     * Deleting a file from the db and from the file system
294
     *
295
     * @return bool
296
     */
297 11
    public function beforeDelete()
298
    {
299 11
        $this->getStorage()->delete();
300 11
        return true;
301
    }
302
}
303