Completed
Push — master ( 6d6774...64f3ed )
by Jeroen
11:23 queued 05:13
created

ChooserController   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 150
Duplicated Lines 3.33 %

Coupling/Cohesion

Components 1
Dependencies 12

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 12
dl 5
loc 150
ccs 0
cts 92
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A chooserIndexAction() 0 36 4
C chooserShowFolderAction() 5 79 9
A createTypeFormView() 0 8 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Kunstmaan\MediaBundle\Controller;
4
5
use Doctrine\ORM\EntityNotFoundException;
6
use Kunstmaan\MediaBundle\AdminList\MediaAdminListConfigurator;
7
use Kunstmaan\MediaBundle\Entity\Folder;
8
use Kunstmaan\MediaBundle\Entity\Media;
9
use Kunstmaan\MediaBundle\Form\FolderType;
10
use Kunstmaan\MediaBundle\Helper\Media\AbstractMediaHandler;
11
use Kunstmaan\MediaBundle\Helper\MediaManager;
12
use Symfony\Component\Routing\Annotation\Route;
13
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
14
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
15
use Symfony\Component\HttpFoundation\RedirectResponse;
16
use Symfony\Component\HttpFoundation\Request;
17
18
/**
19
 * ChooserController.
20
 */
21
class ChooserController extends Controller
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...e\Controller\Controller has been deprecated with message: since Symfony 4.2, use "Symfony\Bundle\FrameworkBundle\Controller\AbstractController" instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
22
{
23
    /**
24
     * @Route("/chooser", name="KunstmaanMediaBundle_chooser")
25
     *
26
     * @param Request $request
27
     *
28
     * @return RedirectResponse
29
     */
30
    public function chooserIndexAction(Request $request)
31
    {
32
        $em = $this->getDoctrine()->getManager();
33
        $session = $request->getSession();
34
        $folderId = false;
35
36
        $type = $request->get('type', 'all');
37
        $cKEditorFuncNum = $request->get('CKEditorFuncNum');
38
        $linkChooser = $request->get('linkChooser');
39
40
        // Go to the last visited folder
41
        if ($session->get('last-media-folder')) {
42
            try {
43
                $em->getRepository(Folder::class)->getFolder($session->get('last-media-folder'));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method getFolder() does only exist in the following implementations of said interface: Kunstmaan\MediaBundle\Repository\FolderRepository.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
44
                $folderId = $session->get('last-media-folder');
45
            } catch (EntityNotFoundException $e) {
46
                $folderId = false;
47
            }
48
        }
49
50
        if (!$folderId) {
51
            // Redirect to the first top folder
52
            /* @var Folder $firstFolder */
53
            $firstFolder = $em->getRepository(Folder::class)->getFirstTopFolder();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method getFirstTopFolder() does only exist in the following implementations of said interface: Kunstmaan\MediaBundle\Repository\FolderRepository.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
54
            $folderId = $firstFolder->getId();
55
        }
56
57
        $params = array(
58
            'folderId' => $folderId,
59
            'type' => $type,
60
            'CKEditorFuncNum' => $cKEditorFuncNum,
61
            'linkChooser' => $linkChooser,
62
        );
63
64
        return $this->redirect($this->generateUrl('KunstmaanMediaBundle_chooser_show_folder', $params));
65
    }
66
67
    /**
68
     * @param Request $request
69
     * @param int     $folderId The folder id
70
     *
71
     * @Route("/chooser/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_chooser_show_folder")
72
     * @Template("@KunstmaanMedia/Chooser/chooserShowFolder.html.twig")
73
     *
74
     * @return array
75
     */
76
    public function chooserShowFolderAction(Request $request, $folderId)
77
    {
78
        $em = $this->getDoctrine()->getManager();
79
        $session = $request->getSession();
80
81
        $type = $request->get('type');
82
        $cKEditorFuncNum = $request->get('CKEditorFuncNum');
83
        $linkChooser = $request->get('linkChooser');
84
85
        // Remember the last visited folder in the session
86
        $session->set('last-media-folder', $folderId);
87
88
        // Check when user switches between thumb -and list view
89
        $viewMode = $request->query->get('viewMode');
90 View Code Duplication
        if ($viewMode && $viewMode == 'list-view') {
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...
91
            $session->set('media-list-view', true);
92
        } elseif ($viewMode && $viewMode == 'thumb-view') {
93
            $session->remove('media-list-view');
94
        }
95
96
        /* @var MediaManager $mediaHandler */
97
        $mediaHandler = $this->get('kunstmaan_media.media_manager');
98
99
        /* @var Folder $folder */
100
        $folder = $em->getRepository(Folder::class)->getFolder($folderId);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method getFolder() does only exist in the following implementations of said interface: Kunstmaan\MediaBundle\Repository\FolderRepository.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
101
102
        /** @var AbstractMediaHandler $handler */
103
        $handler = null;
104
        if ($type) {
105
            $handler = $mediaHandler->getHandlerForType($type);
106
        }
107
108
        /* @var MediaManager $mediaManager */
109
        $mediaManager = $this->get('kunstmaan_media.media_manager');
110
111
        $adminListConfigurator = new MediaAdminListConfigurator($em, $mediaManager, $folder, $request);
0 ignored issues
show
Compatibility introduced by
$em of type object<Doctrine\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ORM\EntityManager>. It seems like you assume a concrete implementation of the interface Doctrine\Persistence\ObjectManager to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
112
        $adminList = $this->get('kunstmaan_adminlist.factory')->createList($adminListConfigurator);
113
        $adminList->bindRequest($request);
114
115
        $sub = new Folder();
116
        $sub->setParent($folder);
117
        $subForm = $this->createForm(FolderType::class, $sub, array('folder' => $sub));
118
119
        $linkChooserLink = null;
120
        if (!empty($linkChooser)) {
121
            $params = array();
122
            if (!empty($cKEditorFuncNum)) {
123
                $params['CKEditorFuncNum'] = $cKEditorFuncNum;
124
                $routeName = 'KunstmaanNodeBundle_ckselecturl';
125
            } else {
126
                $routeName = 'KunstmaanNodeBundle_selecturl';
127
            }
128
            $linkChooserLink = $this->generateUrl($routeName, $params);
129
        }
130
131
        $viewVariabels = array(
132
            'cKEditorFuncNum' => $cKEditorFuncNum,
133
            'linkChooser' => $linkChooser,
134
            'linkChooserLink' => $linkChooserLink,
135
            'mediamanager' => $mediaManager,
136
            'foldermanager' => $this->get('kunstmaan_media.folder_manager'),
137
            'handler' => $handler,
138
            'type' => $type,
139
            'folder' => $folder,
140
            'adminlist' => $adminList,
141
            'subform' => $subForm->createView(),
142
        );
143
144
        /* generate all forms */
145
        $forms = array();
146
147
        foreach ($mediaManager->getFolderAddActions()  as $addAction) {
148
            $forms[$addAction['type']] = $this->createTypeFormView($mediaHandler, $addAction['type']);
149
        }
150
151
        $viewVariabels['forms'] = $forms;
152
153
        return $viewVariabels;
154
    }
155
156
    /**
157
     * @param MediaManager $mediaManager
158
     * @param string       $type
159
     *
160
     * @return \Symfony\Component\Form\FormView
161
     */
162
    private function createTypeFormView(MediaManager $mediaManager, $type)
163
    {
164
        $handler = $mediaManager->getHandlerForType($type);
165
        $media = new Media();
166
        $helper = $handler->getFormHelper($media);
167
168
        return $this->createForm($handler->getFormType(), $helper, $handler->getFormTypeOptions())->createView();
169
    }
170
}
171