MediaBrowserController::findModel()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
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 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
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 backend\controllers;
9
10
use common\components\Json;
11
use common\components\MediaUploadHandler;
12
use common\models\Media;
13
use common\models\Post;
14
use Yii;
15
use yii\filters\AccessControl;
16
use yii\filters\VerbFilter;
17
use yii\helpers\ArrayHelper;
18
use yii\helpers\Html;
19
use yii\web\Controller;
20
use yii\web\NotFoundHttpException;
21
22
/**
23
 * Class MediaBrowserController, controlling the actions for for Media model in Media Browser.
24
 *
25
 * @author Agiel K. Saputra <[email protected]>
26
 * @since 0.3.0
27
 */
28
class MediaBrowserController extends Controller
29
{
30
    /**
31
     * @inheritdoc
32
     */
33 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...
34
    {
35
        return [
36
            'access' => [
37
                'class' => AccessControl::className(),
38
                'rules' => [
39
                    [
40
                        'actions' => ['index', 'get-json', 'get-paging', 'editor-insert', 'field-insert'],
41
                        'allow' => true,
42
                        'roles' => ['author'],
43
                    ],
44
                ],
45
            ],
46
            'verbs' => [
47
                'class' => VerbFilter::className(),
48
                'actions' => [
49
                    'editor-insert' => ['post'],
50
                    'field-insert' => ['post'],
51
                ],
52
            ],
53
        ];
54
    }
55
56
    /**
57
     * Displays files browser for editor and field.
58
     *
59
     * @param int|null $post
60
     * @return string
61
     * @throws NotFoundHttpException
62
     */
63
    public function actionIndex($post = null)
64
    {
65
        $this->layout = "blank";
66
        $model = new Media(['scenario' => 'upload']);
67
68
        if (isset($post) && !$post = $this->findPost($post)->id) {
69
            throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
70
        }
71
72
        return $this->render('index', [
73
            'post' => $post,
74
            'model' => $model,
75
        ]);
76
    }
77
78
    /**
79
     * Get JSON data from Media.
80
     *
81
     * @param int|null $id
82
     */
83
    public function actionGetJson($id = null)
84
    {
85
        $uploadHandler = new MediaUploadHandler(null, MediaUploadHandler::NOT_PRINT_RESPONSE);
86
        $uploadHandler->get($id);
87
    }
88
89
90
    /**
91
     * Insert file to editor.
92
     *
93
     * @return string
94
     */
95
    public function actionEditorInsert()
96
    {
97
        $result = '';
98
99
        foreach (Yii::$app->request->post('Media') as $media) {
100
            $type = ArrayHelper::getValue($media, 'type');
101
            if ($type === 'image') {
102
                $result .= $this->getMediaImage($media);
103
            } elseif ($type === 'video') {
104
                $result .= $this->getMediaVideo($media);
105
            } elseif ($type === 'audio') {
106
                $result .= $this->getMediaAudio($media);
107
            } else {
108
                $result .= $this->getMediaFile($media);
109
            }
110
        }
111
112
        return $result;
113
    }
114
115
    /**
116
     * Insert URL of media to input field.
117
     *
118
     * @return string
119
     */
120
    public function actionFieldInsert()
121
    {
122
        $files = [];
123
124
        foreach (Yii::$app->request->post('Media') as $media) {
125
            $mediaUploadHandler = new MediaUploadHandler(null, false);
126
            $file = $mediaUploadHandler->get(
127
                ArrayHelper::getValue($media, 'id'),
128
                $mediaUploadHandler::NOT_PRINT_RESPONSE
129
            );
130
            $files[] = ArrayHelper::getValue($file, 'file');
0 ignored issues
show
Bug introduced by
It seems like $file defined by $mediaUploadHandler->get...er::NOT_PRINT_RESPONSE) on line 126 can also be of type null; however, yii\helpers\BaseArrayHelper::getValue() does only seem to accept array|object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
131
        }
132
133
        return Json::encode($files);
134
    }
135
136
    /**
137
     * Finds the Media model based on its primary key value.
138
     * If the model is not found, a 404 HTTP exception will be thrown.
139
     *
140
     * @param integer $id
141
     * @return Media the loaded model
142
     * @throws NotFoundHttpException if the model cannot be found
143
     */
144
    protected function findModel($id)
145
    {
146
        if (($model = Media::findOne($id)) !== null) {
147
            return $model;
148
        }
149
150
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
151
    }
152
153
    /**
154
     * Finds the Post model based on its primary key value.
155
     * If the model is not found, a 404 HTTP exception will be thrown.
156
     *
157
     * @param integer $id
158
     * @return Post the loaded model
159
     * @throws NotFoundHttpException if the model cannot be found
160
     */
161
    protected function findPost($id)
162
    {
163
        if (($model = Post::findOne($id)) !== null) {
164
            return $model;
165
        }
166
167
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
168
    }
169
170
    /**
171
     * Generate image tag for media.
172
     *
173
     * @param array $media
174
     * @return string
175
     * @throws \yii\web\NotFoundHttpException
176
     */
177
    protected function getMediaImage($media)
178
    {
179
        $result = '';
180
        $model = $this->findModel(ArrayHelper::getValue($media, 'id'));
181
        $meta = $model->getMeta('metadata');
0 ignored issues
show
Bug introduced by
The method getMeta cannot be called on $model (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
182
        $image = $model->getThumbnail(ArrayHelper::getValue($media, 'version'), [
0 ignored issues
show
Bug introduced by
The method getThumbnail cannot be called on $model (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
183
                'data-id' => $model->id,
184
                'class' => 'media-image media-' . $model->id . ' ' . ArrayHelper::getValue($media, 'align', 'none'),
185
            ]) . "\n";
186
187
        if ($model->excerpt) {
188
            $result .= Html::beginTag('div', [
189
                    'class' => ArrayHelper::getValue($media, 'align', 'none') . ' media-caption',
190
                    'style' => 'width: ' . $meta['versions'][$media['version']]['width'] . 'px',
191
                ]) . "\n";
192
        }
193
194
        if ($linkValue = ArrayHelper::getValue($media, 'link_value')) {
195
            $result .= Html::beginTag('a', [
196
                    'href' => $linkValue,
197
                    'class' => ArrayHelper::getValue($media, 'align', 'none'),
198
                ]) . "\n";
199
        }
200
201
        $result .= $image;
202
203
        if ($linkValue = ArrayHelper::getValue($media, 'link_value')) {
0 ignored issues
show
Unused Code introduced by
$linkValue is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
204
            $result .= Html::endTag('a') . "\n";
205
        }
206
207
        if ($model->excerpt) {
208
            $result .= Html::tag('div', $model->excerpt, ['class' => 'media-caption-text']) . "\n";
209
            $result .= Html::endTag('div') . "\n";
210
        }
211
212
        return $result;
213
    }
214
215
    /**
216
     * Generate video tag for editor and use HTML5.
217
     *
218
     * @param array $media
219
     * @return string
220
     * @throws \yii\web\NotFoundHttpException
221
     */
222 View Code Duplication
    protected function getMediaVideo($media)
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...
223
    {
224
        $model = $this->findModel(ArrayHelper::getValue($media, 'id'));
225
        $meta = $model->getMeta('metadata');
0 ignored issues
show
Bug introduced by
The method getMeta cannot be called on $model (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
226
        $result = Html::beginTag('video', [
227
                'controls' => true,
228
                'class' => 'media-video media-' . $model->id,
229
            ]) . "\n";
230
        $result .= Html::tag('source', '', [
231
                'src' => $model->getUploadUrl() . ArrayHelper::getValue($meta, 'versions.full.url'),
0 ignored issues
show
Bug introduced by
The method getUploadUrl cannot be called on $model (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
232
                'type' => $model->mime_type,
233
            ]) . "\n";
234
        $result .= 'Your browser does not support the <code>video</code> element.' . "\n";
235
        $result .= Html::endTag('video') . "\n";
236
237
        return $result;
238
    }
239
240
    /**
241
     * Generate audio tag for editor and use HTML5.
242
     *
243
     * @param array $media
244
     * @return string
245
     * @throws \yii\web\NotFoundHttpException
246
     */
247 View Code Duplication
    protected function getMediaAudio($media)
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...
248
    {
249
        $model = $this->findModel(ArrayHelper::getValue($media, 'id'));
250
        $meta = $model->getMeta('metadata');
0 ignored issues
show
Bug introduced by
The method getMeta cannot be called on $model (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
251
        $result = Html::beginTag('audio', [
252
                'controls' => true,
253
                'class' => 'media-audio media-' . $model->id,
254
            ]) . "\n";
255
        $result .= Html::tag('source', '', [
256
                'src' => $model->getUploadUrl() . ArrayHelper::getValue($meta, 'versions.full.url'),
0 ignored issues
show
Bug introduced by
The method getUploadUrl cannot be called on $model (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
257
                'type' => $model->mime_type,
258
            ]) . "\n";
259
        $result .= 'Your browser does not support the <code>video</code> element.' . "\n";
260
        $result .= Html::endTag('audio') . "\n";
261
262
        return $result;
263
    }
264
265
    /**
266
     * Generate link to media file for editor.
267
     *
268
     * @param array $media
269
     * @return string
270
     * @throws \yii\web\NotFoundHttpException
271
     */
272 View Code Duplication
    protected function getMediaFile($media)
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...
273
    {
274
        $model = $this->findModel(ArrayHelper::getValue($media, 'id'));
275
276
        return Html::a(
277
            $model->title,
278
            ArrayHelper::getValue($media, 'link_value'),
279
            ['class' => 'media-file media-' . $model->id]
280
        );
281
    }
282
}
283