Media::scenarios()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
/**
3
 * @link http://www.writesdown.com/
4
 * @copyright Copyright (c) 2015 WritesDown
5
 * @license http://www.writesdown.com/license/
6
 */
7
8
namespace common\models;
9
10
use common\components\Json;
11
use Yii;
12
use yii\behaviors\SluggableBehavior;
13
use yii\db\ActiveRecord;
14
use yii\helpers\ArrayHelper;
15
use yii\helpers\Html;
16
17
/**
18
 * This is the model class for table "{{%media}}".
19
 *
20
 * @property integer $id
21
 * @property integer $author
22
 * @property integer $post_id
23
 * @property string $title
24
 * @property string $excerpt
25
 * @property string $content
26
 * @property string $password
27
 * @property string $date
28
 * @property string $modified
29
 * @property string $slug
30
 * @property string $mime_type
31
 * @property string $comment_status
32
 * @property integer $comment_count
33
 *
34
 * @property string $url
35
 * @property string $uploadUrl
36
 *
37
 * @property Post $mediaPost
38
 * @property User $mediaAuthor
39
 * @property MediaComment[] $mediaComments
40
 * @property MediaMeta[] $mediaMeta
41
 *
42
 * @author Agiel K. Saputra <[email protected]>
43
 * @since 0.1.0
44
 */
45
class Media extends ActiveRecord
46
{
47
    const COMMENT_STATUS_OPEN = 'open';
48
    const COMMENT_STATUS_CLOSE = 'close';
49
50
    public $username;
51
    public $post_title;
52
    /**
53
     * @var \yii\web\UploadedFile
54
     */
55
    public $file;
56
57
    /**
58
     * @inheritdoc
59
     */
60
    public static function tableName()
61
    {
62
        return '{{%media}}';
63
    }
64
65
    /**
66
     * @inheritdoc
67
     */
68 View Code Duplication
    public function behaviors()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
69
    {
70
        return [
71
            [
72
                'class' => SluggableBehavior::className(),
73
                'attribute' => 'title',
74
                'attributes' => [ActiveRecord::EVENT_BEFORE_INSERT => ['slug']],
75
            ],
76
        ];
77
    }
78
79
    /**
80
     * @inheritdoc
81
     */
82
    public function scenarios()
83
    {
84
        $scenarios = parent::scenarios();
85
        $scenarios['upload'] = ['file'];
86
87
        return $scenarios;
88
    }
89
90
    /**
91
     * @inheritdoc
92
     */
93
    public function rules()
94
    {
95
        return [
96
            [['title', 'mime_type'], 'required'],
97
            [['author', 'post_id', 'comment_count'], 'integer'],
98
            [['title', 'excerpt', 'content'], 'string'],
99
            [['password', 'slug'], 'string', 'max' => 255],
100
            ['mime_type', 'string', 'max' => 100],
101
            ['comment_status', 'string', 'max' => 20],
102
            [['date', 'modified', 'slug'], 'safe'],
103
            [
104
                'file',
105
                'file',
106
                'maxSize' => 1024 * 1024 * 25,
107
                'extensions' => 'jpg, jpeg, png, gif,'
108
                    . 'pdf, doc, docx, key, ppt, pptx, pps, ppsx, odt, xls, xlsx, zip,'
109
                    . 'mp3, m4a, ogg, wav,'
110
                    . 'mp4, m4v, mov, wmv, avi, mpg,ogv, 3gp, 3g2',
111
            ],
112
            ['file', 'required', 'on' => 'upload'],
113
        ];
114
    }
115
116
    /**
117
     * @inheritdoc
118
     */
119
    public function attributeLabels()
120
    {
121
        return [
122
            'id' => Yii::t('writesdown', 'ID'),
123
            'author' => Yii::t('writesdown', 'Author'),
124
            'post_id' => Yii::t('writesdown', 'Attached to'),
125
            'title' => Yii::t('writesdown', 'Title'),
126
            'excerpt' => Yii::t('writesdown', 'Caption'),
127
            'content' => Yii::t('writesdown', 'Description'),
128
            'password' => Yii::t('writesdown', 'Password'),
129
            'date' => Yii::t('writesdown', 'Uploaded'),
130
            'modified' => Yii::t('writesdown', 'Updated'),
131
            'slug' => Yii::t('writesdown', 'Slug'),
132
            'mime_type' => Yii::t('writesdown', 'Mime Type'),
133
            'comment_status' => Yii::t('writesdown', 'Comment Status'),
134
            'comment_count' => Yii::t('writesdown', 'Comment Count'),
135
            'username' => Yii::t('writesdown', 'Author'),
136
            'post_title' => Yii::t('writesdown', 'Post Title'),
137
        ];
138
    }
139
140
    /**
141
     * @return \yii\db\ActiveQuery
142
     */
143
    public function getMediaPost()
144
    {
145
        return $this->hasOne(Post::className(), ['id' => 'post_id']);
146
    }
147
148
    /**
149
     * @return \yii\db\ActiveQuery
150
     */
151
    public function getMediaAuthor()
152
    {
153
        return $this->hasOne(User::className(), ['id' => 'author']);
154
    }
155
156
    /**
157
     * @return \yii\db\ActiveQuery
158
     */
159
    public function getMediaComments()
160
    {
161
        return $this->hasMany(MediaComment::className(), ['media_id' => 'id']);
162
    }
163
164
    /**
165
     * @return \yii\db\ActiveQuery
166
     */
167
    public function getMediaMeta()
168
    {
169
        return $this->hasMany(MediaMeta::className(), ['media_id' => 'id']);
170
    }
171
172
    /**
173
     * Get comment status as array
174
     */
175 View Code Duplication
    public function getCommentStatuses()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
176
    {
177
        return [
178
            self::COMMENT_STATUS_OPEN => Yii::t('writesdown', 'Open'),
179
            self::COMMENT_STATUS_CLOSE => Yii::t('writesdown', 'Close'),
180
        ];
181
    }
182
183
    /**
184
     * Get meta for current media.
185
     *
186
     * @param string $name
187
     * @return mixed|null|string
188
     */
189 View Code Duplication
    public function getMeta($name)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
190
    {
191
        /* @var $model \common\models\MediaMeta */
192
        $model = MediaMeta::findOne(['name' => $name, 'media_id' => $this->id]);
193
194
        if ($model) {
195
            if (Json::isJson($model->value)) {
196
                return Json::decode($model->value);
197
            }
198
199
            return $model->value;
200
        }
201
202
        return null;
203
    }
204
205
    /**
206
     * Add new meta data for current media.
207
     *
208
     * @param string $name
209
     * @param string|array $value
210
     * @return bool
211
     */
212 View Code Duplication
    public function setMeta($name, $value)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
213
    {
214
        if (is_array($value) || is_object($value)) {
215
            $value = Json::encode($value);
216
        }
217
218
        if ($this->getMeta($name) !== null) {
219
            return $this->upMeta($name, $value);
220
        }
221
222
        $model = new MediaMeta([
223
            'media_id' => $this->id,
224
            'name' => $name,
225
            'value' => $value,
226
        ]);
227
228
        return $model->save();
229
    }
230
231
    /**
232
     * Update meta data for current media.
233
     *
234
     * @param string $name
235
     * @param string|array $value
236
     * @return bool
237
     */
238 View Code Duplication
    public function upMeta($name, $value)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
239
    {
240
        /* @var $model \common\models\MediaMeta */
241
        $model = MediaMeta::findOne(['name' => $name, 'media_id' => $this->id]);
242
243
        if (is_array($value) || is_object($value)) {
244
            $value = Json::encode($value);
245
        }
246
247
        $model->value = $value;
248
249
        return $model->save();
250
    }
251
252
    /**
253
     * Get permalink of current media
254
     *
255
     * @return string
256
     */
257
    public function getUrl()
258
    {
259
        return Yii::$app->urlManagerFront->createAbsoluteUrl(['/media/view', 'id' => $this->id]);
260
    }
261
262
    /**
263
     * Get upload URL.
264
     *
265
     * @return string
266
     */
267
    public static function getUploadUrl()
268
    {
269
        return Yii::$app->urlManagerFront->hostInfo . Yii::$app->urlManagerFront->baseUrl . '/uploads/';
270
    }
271
272
    /**
273
     * Get media image thumbnail. If the version is not found, full size will be returned.
274
     *
275
     * @param string $version Version of image thumbnail.
276
     * @param array $options Html::image options.
277
     * @return string
278
     */
279
    public function getThumbnail($version = 'thumbnail', $options = [])
280
    {
281
        $thumbnail = '';
282
        $metadata = $this->getMeta('metadata');
283
284
        if (preg_match("/^image/", $this->mime_type)) {
285
            if (isset($metadata['versions'][$version])) {
286
                $imageSrc = $metadata['versions'][$version]['url'];
287
                $imageWidth = $metadata['versions'][$version]['width'];
288
                $imageHeight = $metadata['versions'][$version]['height'];
289
            } else {
290
                $imageSrc = $metadata['versions']['full']['url'];
291
                $imageWidth = $metadata['versions']['full']['width'];
292
                $imageHeight = $metadata['versions']['full']['height'];
293
            }
294
295
            $thumbnail = Html::img($this->getUploadUrl() . $imageSrc, ArrayHelper::merge([
296
                'width' => $imageWidth,
297
                'height' => $imageHeight,
298
                'alt' => $this->title,
299
            ], $options));
300
        }
301
302
        return $thumbnail;
303
    }
304
305
    /**
306
     * Get permission to access model by current user.
307
     *
308
     * @return bool
309
     */
310
    public function getPermission()
311
    {
312 View Code Duplication
        if (!Yii::$app->user->can('editor') && $this->author !== Yii::$app->user->id) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
313
            return false;
314
        }
315
316
        return true;
317
    }
318
319
    /**
320
     * @inheritdoc
321
     */
322
    public function beforeSave($insert)
323
    {
324
        if (parent::beforeSave($insert)) {
325
            if ($this->isNewRecord) {
326
                $this->author = Yii::$app->user->id;
327
                $this->date = date('Y-m-d H:i:s');
328
                $this->comment_status = self::COMMENT_STATUS_OPEN;
329
                $this->comment_count = 0;
330
            }
331
            $this->modified = date('Y-m-d H:i:s');
332
333
            return true;
334
        }
335
336
        return false;
337
    }
338
}
339