Completed
Push — master ( 6c15b7...f5f8be )
by Sander
12:00
created

MediaController   C

Complexity

Total Complexity 57

Size/Duplication

Total Lines 504
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 0
Metric Value
wmc 57
lcom 1
cbo 14
dl 0
loc 504
rs 5.04
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A showAction() 0 44 4
A deleteAction() 0 32 4
A bulkUploadAction() 0 9 1
F bulkUploadSubmitAction() 0 131 27
A returnJsonError() 0 13 1
A dropAction() 0 33 5
A createAction() 0 4 1
B createAndRedirect() 0 60 5
A createModalAction() 0 22 3
A moveMedia() 0 22 3
A bulkMoveAction() 0 37 3

How to fix   Complexity   

Complex Class

Complex classes like MediaController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MediaController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Kunstmaan\MediaBundle\Controller;
4
5
use Exception;
6
use Kunstmaan\AdminBundle\FlashMessages\FlashTypes;
7
use Kunstmaan\MediaBundle\Entity\Folder;
8
use Kunstmaan\MediaBundle\Entity\Media;
9
use Kunstmaan\MediaBundle\Form\BulkMoveMediaType;
10
use Kunstmaan\MediaBundle\Helper\MediaManager;
11
use Symfony\Component\Routing\Annotation\Route;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
13
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
14
use Symfony\Component\HttpFoundation\File\File;
15
use Symfony\Component\HttpFoundation\JsonResponse;
16
use Symfony\Component\HttpFoundation\RedirectResponse;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
20
/**
21
 * MediaController
22
 */
23
class MediaController extends Controller
24
{
25
    /**
26
     * @param Request $request
27
     * @param int     $mediaId
28
     *
29
     * @Route("/{mediaId}", requirements={"mediaId" = "\d+"}, name="KunstmaanMediaBundle_media_show")
30
     *
31
     * @return Response
32
     */
33
    public function showAction(Request $request, $mediaId)
34
    {
35
        $em = $this->getDoctrine()->getManager();
36
37
        /* @var Media $media */
38
        $media = $em->getRepository('KunstmaanMediaBundle:Media')->getMedia($mediaId);
39
        $folder = $media->getFolder();
40
41
        /* @var MediaManager $mediaManager */
42
        $mediaManager = $this->get('kunstmaan_media.media_manager');
43
        $handler = $mediaManager->getHandler($media);
44
        $helper = $handler->getFormHelper($media);
45
46
        $form = $this->createForm($handler->getFormType(), $helper, $handler->getFormTypeOptions());
47
48
        if ($request->isMethod('POST')) {
49
            $form->handleRequest($request);
50
            if ($form->isSubmitted() && $form->isValid()) {
51
                $media = $helper->getMedia();
52
                $em->getRepository('KunstmaanMediaBundle:Media')->save($media);
53
54
                return new RedirectResponse(
55
                    $this->generateUrl(
56
                        'KunstmaanMediaBundle_media_show',
57
                        ['mediaId' => $media->getId()]
58
                    )
59
                );
60
            }
61
        }
62
        $showTemplate = $mediaManager->getHandler($media)->getShowTemplate($media);
63
64
        return $this->render(
65
            $showTemplate,
66
            [
67
                'handler' => $handler,
68
                'foldermanager' => $this->get('kunstmaan_media.folder_manager'),
69
                'mediamanager' => $this->get('kunstmaan_media.media_manager'),
70
                'editform' => $form->createView(),
71
                'media' => $media,
72
                'helper' => $helper,
73
                'folder' => $folder,
74
            ]
75
        );
76
    }
77
78
    /**
79
     * @param Request $request
80
     * @param int     $mediaId
81
     *
82
     * @Route("/delete/{mediaId}", requirements={"mediaId" = "\d+"}, name="KunstmaanMediaBundle_media_delete")
83
     *
84
     * @return RedirectResponse
85
     */
86
    public function deleteAction(Request $request, $mediaId)
87
    {
88
        $em = $this->getDoctrine()->getManager();
89
90
        /* @var Media $media */
91
        $media = $em->getRepository('KunstmaanMediaBundle:Media')->getMedia($mediaId);
92
        $medianame = $media->getName();
93
        $folder = $media->getFolder();
94
95
        $em->getRepository('KunstmaanMediaBundle:Media')->delete($media);
96
97
        $this->addFlash(
98
            FlashTypes::SUCCESS,
99
            $this->get('translator')->trans(
100
                'kuma_admin.media.flash.deleted_success.%medianame%',
101
                [
102
                    '%medianame%' => $medianame,
103
                ]
104
            )
105
        );
106
107
        // If the redirect url is passed via the url we use it
108
        $redirectUrl = $request->query->get('redirectUrl');
109
        if (empty($redirectUrl) || (\strpos($redirectUrl, $request->getSchemeAndHttpHost()) !== 0 && \strpos($redirectUrl, '/') !== 0)) {
110
            $redirectUrl = $this->generateUrl(
111
                'KunstmaanMediaBundle_folder_show',
112
                ['folderId' => $folder->getId()]
113
            );
114
        }
115
116
        return new RedirectResponse($redirectUrl);
117
    }
118
119
    /**
120
     * @param int $folderId
121
     *
122
     * @Route("bulkupload/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_media_bulk_upload")
123
     * @Template("@KunstmaanMedia/Media/bulkUpload.html.twig")
124
     *
125
     * @return array|RedirectResponse
126
     */
127
    public function bulkUploadAction($folderId)
128
    {
129
        $em = $this->getDoctrine()->getManager();
130
131
        /* @var Folder $folder */
132
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
133
134
        return ['folder' => $folder];
135
    }
136
137
    /**
138
     * @param Request $request
139
     * @param int     $folderId
140
     *
141
     * @Route("bulkuploadsubmit/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_media_bulk_upload_submit")
142
     *
143
     * @return JsonResponse
144
     */
145
    public function bulkUploadSubmitAction(Request $request, $folderId)
146
    {
147
        // Settings
148
        if (\ini_get('upload_tmp_dir')) {
149
            $tempDir = \ini_get('upload_tmp_dir');
150
        } else {
151
            $tempDir = \sys_get_temp_dir();
152
        }
153
        $targetDir = \rtrim($tempDir, '/').DIRECTORY_SEPARATOR.'plupload';
154
        $cleanupTargetDir = true; // Remove old files
155
        $maxFileAge = 5 * 60 * 60; // Temp file age in seconds
156
157
        // Create target dir
158
        if (!\file_exists($targetDir)) {
159
            @\mkdir($targetDir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
160
        }
161
162
        // Get a file name
163
        if ($request->request->has('name')) {
164
            $fileName = $request->request->get('name');
165
        } elseif (0 !== $request->files->count()) {
166
            $fileName = $request->files->get('file')['name'];
167
        } else {
168
            $fileName = \uniqid('file_', false);
169
        }
170
        $filePath = $targetDir.DIRECTORY_SEPARATOR.$fileName;
171
172
        $chunk = 0;
173
        $chunks = 0;
174
        // Chunking might be enabled
175
        if ($request->request->has('chunk')) {
176
            $chunk = $request->request->getInt('chunk');
177
        }
178
        if ($request->request->has('chunks')) {
179
            $chunks = $request->request->getInt('chunks');
180
        }
181
182
        // Remove old temp files
183
        if ($cleanupTargetDir) {
184
            if (!\is_dir($targetDir) || !$dir = \opendir($targetDir)) {
185
                return $this->returnJsonError('100', 'Failed to open temp directory.');
186
            }
187
188
            while (($file = \readdir($dir)) !== false) {
189
                $tmpFilePath = $targetDir.DIRECTORY_SEPARATOR.$file;
190
191
                // If temp file is current file proceed to the next
192
                if ($tmpFilePath === "{$filePath}.part") {
193
                    continue;
194
                }
195
196
                // Remove temp file if it is older than the max age and is not the current file
197
                if (\preg_match('/\.part$/', $file) && (\filemtime($tmpFilePath) < \time() - $maxFileAge)) {
198
                    $success = @\unlink($tmpFilePath);
199
                    if ($success !== true) {
200
                        return $this->returnJsonError('106', 'Could not remove temp file: '.$filePath);
201
                    }
202
                }
203
            }
204
            \closedir($dir);
205
        }
206
207
        // Open temp file
208
        if (!$out = @\fopen("{$filePath}.part", $chunks ? 'ab' : 'wb')) {
209
            return $this->returnJsonError('102', 'Failed to open output stream.');
210
        }
211
212
        if (0 !== $request->files->count()) {
213
            $_file = $request->files->get('file');
214
            if ($_file->getError() > 0 || !\is_uploaded_file($_file->getRealPath())) {
215
                return $this->returnJsonError('103', 'Failed to move uploaded file.');
216
            }
217
218
            // Read binary input stream and append it to temp file
219
            if (!$input = @\fopen($_file->getRealPath(), 'rb')) {
220
                return $this->returnJsonError('101', 'Failed to open input stream.');
221
            }
222
        } else {
223
            if (!$input = @\fopen('php://input', 'rb')) {
224
                return $this->returnJsonError('101', 'Failed to open input stream.');
225
            }
226
        }
227
228
        while ($buff = \fread($input, 4096)) {
229
            \fwrite($out, $buff);
230
        }
231
232
        @\fclose($out);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
233
        @\fclose($input);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
234
235
        // Check if file has been uploaded
236
        if (!$chunks || $chunk === $chunks - 1) {
237
            // Strip the temp .part suffix off
238
            \rename("{$filePath}.part", $filePath);
239
        }
240
241
        $em = $this->getDoctrine()->getManager();
242
        /* @var Folder $folder */
243
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
244
        $file = new File($filePath);
245
246
        try {
247
            /* @var Media $media */
248
            $media = $this->get('kunstmaan_media.media_manager')->getHandler($file)->createNew($file);
249
            $media->setFolder($folder);
250
            $em->getRepository(Media::class)->save($media);
251
        } catch (Exception $e) {
252
            return $this->returnJsonError('104', 'Failed performing save on media-manager');
253
        }
254
255
        $success = \unlink($filePath);
256
        if ($success !== true) {
257
            return $this->returnJsonError('105', 'Could not remove temp file: '.$filePath);
258
        }
259
260
        // Send headers making sure that the file is not cached (as it happens for example on iOS devices)
261
        $response = new JsonResponse(
262
            [
263
                'jsonrpc' => '2.0',
264
                'result' => '',
265
                'id' => 'id',
266
            ], JsonResponse::HTTP_OK, [
267
                'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
268
                'Last-Modified' => \gmdate('D, d M Y H:i:s').' GMT',
269
                'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
270
                'Pragma' => 'no-cache',
271
            ]
272
        );
273
274
        return $response;
275
    }
276
277
    private function returnJsonError($code, $message)
278
    {
279
        return new JsonResponse(
280
            [
281
                'jsonrpc' => '2.0',
282
                'error ' => [
283
                    'code' => $code,
284
                    'message' => $message,
285
                ],
286
                'id' => 'id',
287
            ]
288
        );
289
    }
290
291
    /**
292
     * @param Request $request
293
     * @param int     $folderId
294
     *
295
     * @Route("drop/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_media_drop_upload", methods={"GET", "POST"})
296
     *
297
     * @return JsonResponse
298
     */
299
    public function dropAction(Request $request, $folderId)
300
    {
301
        $em = $this->getDoctrine()->getManager();
302
303
        /* @var Folder $folder */
304
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
305
306
        $drop = null;
0 ignored issues
show
Unused Code introduced by
$drop 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...
307
308
        if ($request->files->has('files') && $request->files->get('files')['error'] === 0) {
309
            $drop = $request->files->get('files');
310
        } else {
311
            if ($request->files->get('file')) {
312
                $drop = $request->files->get('file');
313
            } else {
314
                $drop = $request->get('text');
315
            }
316
        }
317
        $media = $this->get('kunstmaan_media.media_manager')->createNew($drop);
318
        if ($media) {
319
            $media->setFolder($folder);
320
            $em->getRepository('KunstmaanMediaBundle:Media')->save($media);
321
322
            return new JsonResponse(['status' => $this->get('translator')->trans('kuma_admin.media.flash.drop_success')]);
323
        }
324
325
        $request->getSession()->getFlashBag()->add(
326
            FlashTypes::DANGER,
327
            $this->get('translator')->trans('kuma_admin.media.flash.drop_unrecognized')
328
        );
329
330
        return new JsonResponse(['status' => $this->get('translator')->trans('kuma_admin.media.flash.drop_unrecognized')]);
331
    }
332
333
    /**
334
     * @param Request $request
335
     * @param int     $folderId The folder id
336
     * @param string  $type     The type
337
     *
338
     * @Route("create/{folderId}/{type}", requirements={"folderId" = "\d+", "type" = ".+"}, name="KunstmaanMediaBundle_media_create", methods={"GET", "POST"})
339
     * @Template("@KunstmaanMedia/Media/create.html.twig")
340
     *
341
     * @return array|RedirectResponse
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use RedirectResponse|array<s...t\Form\FormView|Folder>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
342
     */
343
    public function createAction(Request $request, $folderId, $type)
344
    {
345
        return $this->createAndRedirect($request, $folderId, $type, 'KunstmaanMediaBundle_folder_show');
346
    }
347
348
    /**
349
     * @param Request $request
350
     * @param int     $folderId    The folder Id
351
     * @param string  $type        The type
352
     * @param string  $redirectUrl The url where we want to redirect to on success
353
     * @param array   $extraParams The extra parameters that will be passed wen redirecting
354
     *
355
     * @return array|RedirectResponse
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use RedirectResponse|array<s...t\Form\FormView|Folder>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
356
     */
357
    private function createAndRedirect(Request $request, $folderId, $type, $redirectUrl, $extraParams = [], $isInModal = false)
358
    {
359
        $em = $this->getDoctrine()->getManager();
360
361
        /* @var Folder $folder */
362
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
363
364
        /* @var MediaManager $mediaManager */
365
        $mediaManager = $this->get('kunstmaan_media.media_manager');
366
        $handler = $mediaManager->getHandlerForType($type);
367
        $media = new Media();
368
        $helper = $handler->getFormHelper($media);
369
370
        $form = $this->createForm($handler->getFormType(), $helper, $handler->getFormTypeOptions());
371
372
        if ($request->isMethod('POST')) {
373
            $params = ['folderId' => $folder->getId()];
374
            $params = \array_merge($params, $extraParams);
375
376
            $form->handleRequest($request);
377
378
            if ($form->isSubmitted() && $form->isValid()) {
379
                $media = $helper->getMedia();
380
                $media->setFolder($folder);
381
                $em->getRepository('KunstmaanMediaBundle:Media')->save($media);
382
383
                $this->addFlash(
384
                    FlashTypes::SUCCESS,
385
                    $this->get('translator')->trans(
386
                        'media.flash.created',
387
                        [
388
                            '%medianame%' => $media->getName(),
389
                        ]
390
                    )
391
                );
392
393
                return new RedirectResponse($this->generateUrl($redirectUrl, $params));
394
            }
395
396
            if ($isInModal) {
397
                $this->addFlash(
398
                    FlashTypes::ERROR,
399
                    $this->get('translator')->trans(
400
                        'media.flash.not_created',
401
                        [
402
                            '%mediaerrors%' => $form->getErrors(true, true),
403
                        ]
404
                    )
405
                );
406
407
                return new RedirectResponse($this->generateUrl($redirectUrl, $params));
408
            }
409
        }
410
411
        return [
412
            'type' => $type,
413
            'form' => $form->createView(),
414
            'folder' => $folder,
415
        ];
416
    }
417
418
    /**
419
     * @param Request $request
420
     * @param int     $folderId The folder id
421
     * @param string  $type     The type
422
     *
423
     * @Route("create/modal/{folderId}/{type}", requirements={"folderId" = "\d+", "type" = ".+"}, name="KunstmaanMediaBundle_media_modal_create", methods={"POST"})
424
     *
425
     * @return array|RedirectResponse
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use RedirectResponse|array<s...t\Form\FormView|Folder>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
426
     */
427
    public function createModalAction(Request $request, $folderId, $type)
428
    {
429
        $cKEditorFuncNum = $request->get('CKEditorFuncNum');
430
        $linkChooser = $request->get('linkChooser');
431
432
        $extraParams = [];
433
        if (!empty($cKEditorFuncNum)) {
434
            $extraParams['CKEditorFuncNum'] = $cKEditorFuncNum;
435
        }
436
        if (!empty($linkChooser)) {
437
            $extraParams['linkChooser'] = $linkChooser;
438
        }
439
440
        return $this->createAndRedirect(
441
            $request,
442
            $folderId,
443
            $type,
444
            'KunstmaanMediaBundle_chooser_show_folder',
445
            $extraParams,
446
            true
447
        );
448
    }
449
450
    /**
451
     * @param Request $request
452
     *
453
     * @Route("move/", name="KunstmaanMediaBundle_media_move", methods={"POST"})
454
     *
455
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be JsonResponse?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
456
     */
457
    public function moveMedia(Request $request)
458
    {
459
        @trigger_error(sprintf('The "%s" controller action is deprecated in KunstmaanMediaBundle 5.1 and will be removed in KunstmaanMediaBundle 6.0.', __METHOD__), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
460
461
        $mediaId = $request->request->get('mediaId');
462
        $folderId = $request->request->get('folderId');
463
464
        if (empty($mediaId) || empty($folderId)) {
465
            return new JsonResponse(['error' => ['title' => 'Missing media id or folder id']], 400);
466
        }
467
468
        $em = $this->getDoctrine()->getManager();
469
        $mediaRepo = $em->getRepository('KunstmaanMediaBundle:Media');
470
471
        $media = $mediaRepo->getMedia($mediaId);
472
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
473
474
        $media->setFolder($folder);
475
        $mediaRepo->save($media);
476
477
        return new JsonResponse();
478
    }
479
480
    /**
481
     * @Route("/bulk-move", name="KunstmaanMediaBundle_media_bulk_move")
482
     *
483
     * @param Request $request
484
     *
485
     * @return JsonResponse|Response
486
     *
487
     * @throws \Doctrine\DBAL\DBALException
488
     */
489
    public function bulkMoveAction(Request $request)
490
    {
491
        $em = $this->getDoctrine()->getManager();
492
        $mediaRepo = $em->getRepository('KunstmaanMediaBundle:Media');
493
        $form = $this->createForm(BulkMoveMediaType::class);
494
495
        $form->handleRequest($request);
496
497
        if ($form->isSubmitted() && $form->isValid()) {
498
            /** @var Folder $folder */
499
            $folder = $form->getData()['folder'];
500
            $mediaIds = explode(',', $form->getData()['media']);
501
502
            $mediaRepo->createQueryBuilder('m')
503
                ->update()
504
                ->set('m.folder', $folder->getId())
505
                ->where('m.id in (:mediaIds)')
506
                ->setParameter('mediaIds', $mediaIds)
507
                ->getQuery()
508
                ->execute();
509
510
            $this->addFlash(FlashTypes::SUCCESS, $this->get('translator')->trans('media.folder.bulk_move.success.text'));
511
512
            return new JsonResponse(
513
                [
514
                    'Success' => 'The media is moved',
515
                ]
516
            );
517
        }
518
519
        return $this->render(
520
            '@KunstmaanMedia/Folder/bulk-move-modal_form.html.twig',
521
            [
522
                'form' => $form->createView(),
523
            ]
524
        );
525
    }
526
}
527