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

MediaBundle/Controller/FolderController.php (4 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\MediaBundle\Controller;
4
5
use Doctrine\ORM\EntityManager;
6
use Kunstmaan\AdminBundle\FlashMessages\FlashTypes;
7
use Kunstmaan\MediaBundle\AdminList\MediaAdminListConfigurator;
8
use Kunstmaan\MediaBundle\Entity\Folder;
9
use Kunstmaan\MediaBundle\Form\FolderType;
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\Form\Extension\Core\Type\CheckboxType;
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
 * FolderController.
22
 */
23
class FolderController extends Controller
24
{
25
    /**
26
     * @param Request $request
27
     * @param int     $folderId The folder id
28
     *
29
     * @Route("/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_folder_show")
30
     * @Template("@KunstmaanMedia/Folder/show.html.twig")
31
     *
32
     * @return array
33
     */
34
    public function showAction(Request $request, $folderId)
35
    {
36
        /** @var EntityManager $em */
37
        $em = $this->getDoctrine()->getManager();
38
        $session = $request->getSession();
39
40
        // Check when user switches between thumb -and list view
41
        $viewMode = $request->query->get('viewMode');
42 View Code Duplication
        if ($viewMode && $viewMode == 'list-view') {
43
            $session->set('media-list-view', true);
44
        } elseif ($viewMode && $viewMode == 'thumb-view') {
45
            $session->remove('media-list-view');
46
        }
47
48
        /* @var MediaManager $mediaManager */
49
        $mediaManager = $this->get('kunstmaan_media.media_manager');
50
51
        /* @var Folder $folder */
52
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
53
54
        $adminListConfigurator = new MediaAdminListConfigurator($em, $mediaManager, $folder, $request);
55
        $adminList = $this->get('kunstmaan_adminlist.factory')->createList($adminListConfigurator);
56
        $adminList->bindRequest($request);
57
58
        $sub = new Folder();
59
        $sub->setParent($folder);
60
        $subForm = $this->createForm(FolderType::class, $sub, array('folder' => $sub));
61
62
        $emptyForm = $this->createEmptyForm();
63
64
        $editForm = $this->createForm(FolderType::class, $folder, array('folder' => $folder));
65
66
        if ($request->isMethod('POST')) {
67
            $editForm->handleRequest($request);
68
            if ($editForm->isValid()) {
69
                $em->getRepository('KunstmaanMediaBundle:Folder')->save($folder);
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method save() does only exist in the following implementations of said interface: Kunstmaan\MediaBundle\Repository\FolderRepository, Kunstmaan\MediaBundle\Repository\MediaRepository.

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...
70
71
                $this->addFlash(
72
                    FlashTypes::SUCCESS,
73
                    $this->get('translator')->trans('media.folder.show.success.text', array(
74
                        '%folder%' => $folder->getName(),
75
                    ))
76
                );
77
78
                return new RedirectResponse(
79
                    $this->generateUrl(
80
                        'KunstmaanMediaBundle_folder_show',
81
                        array('folderId' => $folderId)
82
                    )
83
                );
84
            }
85
        }
86
87
        return array(
88
            'foldermanager' => $this->get('kunstmaan_media.folder_manager'),
89
            'mediamanager' => $this->get('kunstmaan_media.media_manager'),
90
            'subform' => $subForm->createView(),
91
            'emptyform' => $emptyForm->createView(),
92
            'editform' => $editForm->createView(),
93
            'folder' => $folder,
94
            'adminlist' => $adminList,
95
            'type' => null,
96
        );
97
    }
98
99
    /**
100
     * @param Request $request
101
     * @param int     $folderId
102
     *
103
     * @Route("/delete/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_folder_delete")
104
     *
105
     * @return RedirectResponse
106
     */
107
    public function deleteAction(Request $request, $folderId)
108
    {
109
        /** @var EntityManager $em */
110
        $em = $this->getDoctrine()->getManager();
111
112
        /* @var Folder $folder */
113
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
114
        $folderName = $folder->getName();
115
        $parentFolder = $folder->getParent();
116
117
        if (\is_null($parentFolder)) {
118
            $this->addFlash(
119
                FlashTypes::DANGER,
120
                $this->get('translator')->trans('media.folder.delete.failure.text', array(
121
                    '%folder%' => $folderName,
122
                ))
123
            );
124
        } else {
125
            $em->getRepository('KunstmaanMediaBundle:Folder')->delete($folder);
126
            $this->addFlash(
127
                FlashTypes::SUCCESS,
128
                $this->get('translator')->trans('media.folder.delete.success.text', array(
129
                    '%folder%' => $folderName,
130
                ))
131
            );
132
            $folderId = $parentFolder->getId();
133
        }
134
        if (strpos($request->server->get('HTTP_REFERER', ''), 'chooser')) {
135
            $redirect = 'KunstmaanMediaBundle_chooser_show_folder';
136
        } else {
137
            $redirect = 'KunstmaanMediaBundle_folder_show';
138
        }
139
140
        $type = $this->get('request_stack')->getCurrentRequest()->get('type');
141
142
        return new RedirectResponse(
143
            $this->generateUrl($redirect,
144
                array(
145
                    'folderId' => $folderId,
146
                    'type' => $type,
147
                )
148
            )
149
        );
150
    }
151
152
    /**
153
     * @param Request $request
154
     * @param int     $folderId
155
     *
156
     * @Route("/subcreate/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_folder_sub_create", methods={"GET", "POST"})
157
     *
158
     * @return Response
159
     */
160
    public function subCreateAction(Request $request, $folderId)
161
    {
162
        /** @var EntityManager $em */
163
        $em = $this->getDoctrine()->getManager();
164
165
        /* @var Folder $parent */
166
        $parent = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
0 ignored issues
show
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...
167
        $folder = new Folder();
168
        $folder->setParent($parent);
169
        $form = $this->createForm(FolderType::class, $folder);
170 View Code Duplication
        if ($request->isMethod('POST')) {
171
            $form->handleRequest($request);
172
            if ($form->isSubmitted() && $form->isValid()) {
173
                $em->getRepository('KunstmaanMediaBundle:Folder')->save($folder);
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method save() does only exist in the following implementations of said interface: Kunstmaan\MediaBundle\Repository\FolderRepository, Kunstmaan\MediaBundle\Repository\MediaRepository.

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...
174
                $this->addFlash(
175
                    FlashTypes::SUCCESS,
176
                    $this->get('translator')->trans('media.folder.addsub.success.text', array(
177
                        '%folder%' => $folder->getName(),
178
                    ))
179
                );
180
                if (strpos($request->server->get('HTTP_REFERER', ''), 'chooser') !== false) {
181
                    $redirect = 'KunstmaanMediaBundle_chooser_show_folder';
182
                } else {
183
                    $redirect = 'KunstmaanMediaBundle_folder_show';
184
                }
185
186
                $type = $request->get('type');
187
188
                return new RedirectResponse(
189
                    $this->generateUrl($redirect,
190
                        array(
191
                            'folderId' => $folder->getId(),
192
                            'type' => $type,
193
                        )
194
                    )
195
                );
196
            }
197
        }
198
199
        $galleries = $em->getRepository('KunstmaanMediaBundle:Folder')->getAllFolders();
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Doctrine\Persistence\ObjectRepository as the method getAllFolders() 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...
200
201
        return $this->render(
202
            '@KunstmaanMedia/Folder/addsub-modal.html.twig',
203
            array(
204
                'subform' => $form->createView(),
205
                'galleries' => $galleries,
206
                'folder' => $folder,
207
                'parent' => $parent,
208
            )
209
        );
210
    }
211
212
    /**
213
     * @param Request $request
214
     * @param int     $folderId
215
     *
216
     * @Route("/empty/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_folder_empty", methods={"GET", "POST"})
217
     *
218
     * @return Response
219
     */
220
    public function emptyAction(Request $request, $folderId)
221
    {
222
        /** @var EntityManager $em */
223
        $em = $this->getDoctrine()->getManager();
224
225
        /* @var Folder $folder */
226
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
227
228
        $form = $this->createEmptyForm();
229
230
        if ($request->isMethod('POST')) {
231
            $form->handleRequest($request);
232 View Code Duplication
            if ($form->isSubmitted() && $form->isValid()) {
233
                $data = $form->getData();
234
                $alsoDeleteFolders = $data['checked'];
235
236
                $em->getRepository('KunstmaanMediaBundle:Folder')->emptyFolder($folder, $alsoDeleteFolders);
237
238
                $this->addFlash(
239
                    FlashTypes::SUCCESS,
240
                    $this->get('translator')->trans('media.folder.empty.success.text', array(
241
                        '%folder%' => $folder->getName(),
242
                    ))
243
                );
244
                if (strpos($request->server->get('HTTP_REFERER', ''), 'chooser') !== false) {
245
                    $redirect = 'KunstmaanMediaBundle_chooser_show_folder';
246
                } else {
247
                    $redirect = 'KunstmaanMediaBundle_folder_show';
248
                }
249
250
                return new RedirectResponse(
251
                    $this->generateUrl($redirect,
252
                        array(
253
                            'folderId' => $folder->getId(),
254
                            'folder' => $folder,
255
                        )
256
                    )
257
                );
258
            }
259
        }
260
261
        return $this->render(
262
            '@KunstmaanMedia/Folder/empty-modal.html.twig',
263
            array(
264
                'form' => $form->createView(),
265
            )
266
        );
267
    }
268
269
    /**
270
     * @Route("/reorder", name="KunstmaanMediaBundle_folder_reorder")
271
     *
272
     * @param Request $request
273
     *
274
     * @return JsonResponse
275
     */
276
    public function reorderAction(Request $request)
277
    {
278
        $folders = array();
279
        $nodeIds = $request->get('nodes');
280
281
        $em = $this->getDoctrine()->getManager();
282
        $repository = $em->getRepository('KunstmaanMediaBundle:Folder');
283
284
        foreach ($nodeIds as $id) {
285
            /* @var Folder $folder */
286
            $folder = $repository->find($id);
287
            $folders[] = $folder;
288
        }
289
290
        foreach ($folders as $id => $folder) {
291
            $repository->moveDown($folder, true);
292
        }
293
294
        $em->flush();
295
296
        return new JsonResponse(
297
            array(
298
                'Success' => 'The node-translations for have got new weight values',
299
            )
300
        );
301
    }
302
303
    private function createEmptyForm()
304
    {
305
        $defaultData = array('checked' => false);
306
        $form = $this->createFormBuilder($defaultData)
307
            ->add('checked', CheckboxType::class, array('required' => false, 'label' => 'media.folder.empty.modal.checkbox'))
308
            ->getForm();
309
310
        return $form;
311
    }
312
}
313