ChooserController::createTypeFormView()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
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
    private const TYPE_ALL = 'all';
24
25
    /**
26
     * @Route("/chooser", name="KunstmaanMediaBundle_chooser")
27
     *
28
     * @param Request $request
29
     *
30
     * @return RedirectResponse
31
     */
32
    public function chooserIndexAction(Request $request)
33
    {
34
        $em = $this->getDoctrine()->getManager();
35
        $session = $request->getSession();
36
        $folderId = false;
37
38
        $type = $request->get('type', self::TYPE_ALL);
39
        $cKEditorFuncNum = $request->get('CKEditorFuncNum');
40
        $linkChooser = $request->get('linkChooser');
41
42
        // Go to the last visited folder
43
        if ($session->get('last-media-folder')) {
44
            try {
45
                $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...
46
                $folderId = $session->get('last-media-folder');
47
            } catch (EntityNotFoundException $e) {
48
                $folderId = false;
49
            }
50
        }
51
52
        if (!$folderId) {
53
            // Redirect to the first top folder
54
            /* @var Folder $firstFolder */
55
            $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...
56
            $folderId = $firstFolder->getId();
57
        }
58
59
        $params = array(
60
            'folderId' => $folderId,
61
            'type' => $type,
62
            'CKEditorFuncNum' => $cKEditorFuncNum,
63
            'linkChooser' => $linkChooser,
64
        );
65
66
        return $this->redirect($this->generateUrl('KunstmaanMediaBundle_chooser_show_folder', $params));
67
    }
68
69
    /**
70
     * @param Request $request
71
     * @param int     $folderId The folder id
72
     *
73
     * @Route("/chooser/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_chooser_show_folder")
74
     * @Template("@KunstmaanMedia/Chooser/chooserShowFolder.html.twig")
75
     *
76
     * @return array
77
     */
78
    public function chooserShowFolderAction(Request $request, $folderId)
79
    {
80
        $em = $this->getDoctrine()->getManager();
81
        $session = $request->getSession();
82
83
        $type = $request->get('type');
84
        $cKEditorFuncNum = $request->get('CKEditorFuncNum');
85
        $linkChooser = $request->get('linkChooser');
86
87
        // Remember the last visited folder in the session
88
        $session->set('last-media-folder', $folderId);
89
90
        // Check when user switches between thumb -and list view
91
        $viewMode = $request->query->get('viewMode');
92
        if ($viewMode && $viewMode == 'list-view') {
93
            $session->set('media-list-view', true);
94
        } elseif ($viewMode && $viewMode == 'thumb-view') {
95
            $session->remove('media-list-view');
96
        }
97
98
        /* @var MediaManager $mediaHandler */
99
        $mediaHandler = $this->get('kunstmaan_media.media_manager');
100
101
        /* @var Folder $folder */
102
        $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...
103
104
        /** @var AbstractMediaHandler $handler */
105
        $handler = null;
106
        if ($type && $type !== self::TYPE_ALL) {
107
            $handler = $mediaHandler->getHandlerForType($type);
108
        }
109
110
        /* @var MediaManager $mediaManager */
111
        $mediaManager = $this->get('kunstmaan_media.media_manager');
112
113
        $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...
114
        $adminList = $this->get('kunstmaan_adminlist.factory')->createList($adminListConfigurator);
115
        $adminList->bindRequest($request);
116
117
        $sub = new Folder();
118
        $sub->setParent($folder);
119
        $subForm = $this->createForm(FolderType::class, $sub, array('folder' => $sub));
120
121
        $linkChooserLink = null;
122
        if (!empty($linkChooser)) {
123
            $params = array();
124
            if (!empty($cKEditorFuncNum)) {
125
                $params['CKEditorFuncNum'] = $cKEditorFuncNum;
126
                $routeName = 'KunstmaanNodeBundle_ckselecturl';
127
            } else {
128
                $routeName = 'KunstmaanNodeBundle_selecturl';
129
            }
130
            $linkChooserLink = $this->generateUrl($routeName, $params);
131
        }
132
133
        $viewVariabels = array(
134
            'cKEditorFuncNum' => $cKEditorFuncNum,
135
            'linkChooser' => $linkChooser,
136
            'linkChooserLink' => $linkChooserLink,
137
            'mediamanager' => $mediaManager,
138
            'foldermanager' => $this->get('kunstmaan_media.folder_manager'),
139
            'handler' => $handler,
140
            'type' => $type,
141
            'folder' => $folder,
142
            'adminlist' => $adminList,
143
            'subform' => $subForm->createView(),
144
        );
145
146
        /* generate all forms */
147
        $forms = array();
148
149
        foreach ($mediaManager->getFolderAddActions()  as $addAction) {
150
            $forms[$addAction['type']] = $this->createTypeFormView($mediaHandler, $addAction['type']);
151
        }
152
153
        $viewVariabels['forms'] = $forms;
154
155
        return $viewVariabels;
156
    }
157
158
    /**
159
     * @param MediaManager $mediaManager
160
     * @param string       $type
161
     *
162
     * @return \Symfony\Component\Form\FormView
163
     */
164
    private function createTypeFormView(MediaManager $mediaManager, $type)
165
    {
166
        $handler = $mediaManager->getHandlerForType($type);
167
        $media = new Media();
168
        $helper = $handler->getFormHelper($media);
169
170
        return $this->createForm($handler->getFormType(), $helper, $handler->getFormTypeOptions())->createView();
171
    }
172
}
173