Completed
Push — master ( 8152db...56e446 )
by Igor
04:29
created

File::beforeSave()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
ccs 5
cts 5
cp 1
rs 8.8571
cc 5
eloc 8
nc 5
nop 1
crap 5
1
<?php
2
3
namespace app\models;
4
5
use Yii;
6
use yii\behaviors\TimestampBehavior;
7
8
/**
9
 * ActiveRecord for table "file"
10
 *
11
 * @property integer $id
12
 * @property integer $user_id
13
 * @property string $title
14
 * @property string $name
15
 * @property string $date_create
16
 * @property string $date_update
17
 * @property integer $ip
18
 */
19
class File extends \yii\db\ActiveRecord
20
{
21
    /**
22
     * @inheritdoc
23
     * @codeCoverageIgnore
24
     * @internal
25
     */
26
    public static function tableName()
27
    {
28
        return 'file';
29
    }
30
31
    /**
32
     * @inheritdoc
33
     * @internal
34
     */
35 8
    public function behaviors()
36
    {
37
        return [
38
            [
39 8
                'class' => TimestampBehavior::className(),
40 8
                'createdAtAttribute' => 'date_create',
41 8
                'updatedAtAttribute' => 'date_update',
42 8
                'value' => new \yii\db\Expression('NOW()'),
43
            ],
44
        ];
45
    }
46
47
    /**
48
     * @internal
49
     */
50 8
    public function beforeSave($insert)
51
    {
52 8
        if (parent::beforeSave($insert)) {
53 8
            if ($insert) {
54 8
                if (!Yii::$app instanceof \yii\console\Application) {
55
                    $this->user_id = Yii::$app->user->isGuest ? 0 : Yii::$app->user->id; // @codeCoverageIgnore
56
                    $this->ip = ip2long(Yii::$app->request->getUserIP()); // @codeCoverageIgnore
57
                } // @codeCoverageIgnore
58
            }
59 8
            return true;
60
        }
61
        return false; // @codeCoverageIgnore
62
    }
63
64
    /**
65
     * Generate a new name
66
     *
67
     * @param string $extension The file extension
68
     * @return string
69
     */
70 8
    public function generateName($extension)
71
    {
72 8
        $name = date('YmdHis') . substr(md5(microtime() . uniqid()), 0, 10);
73 8
        $this->name = $name . '.' . $extension;
74 8
    }
75
}
76