Completed
Push — master ( a7cf71...06c6ea )
by Craig
06:43
created

AbstractRouteController::deleteAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Routes.
4
 *
5
 * @copyright Zikula contributors (Zikula)
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 * @author Zikula contributors <[email protected]>.
8
 * @link http://www.zikula.org
9
 * @link http://zikula.org
10
 * @version Generated by ModuleStudio 0.7.0 (http://modulestudio.de).
11
 */
12
13
namespace Zikula\RoutesModule\Controller\Base;
14
15
use Zikula\RoutesModule\Entity\RouteEntity;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
18
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
19
use Symfony\Component\HttpFoundation\RedirectResponse;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
22
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
23
use FormUtil;
24
use ModUtil;
25
use RuntimeException;
26
use System;
27
use Zikula\Component\SortableColumns\Column;
28
use Zikula\Component\SortableColumns\SortableColumns;
29
use Zikula\Core\Controller\AbstractController;
30
use Zikula\Core\Response\PlainResponse;
31
32
/**
33
 * Route controller base class.
34
 */
35
abstract class AbstractRouteController extends AbstractController
36
{
37
    /**
38
     * This is the default action handling the main admin area called without defining arguments.
39
     * @Cache(expires="+7 days", public=true)
40
     *
41
     * @param Request  $request      Current request instance
42
     *
43
     * @return mixed Output
44
     *
45
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
46
     */
47
    public function adminIndexAction(Request $request)
48
    {
49
        return $this->indexInternal($request, true);
50
    }
51
52
    /**
53
     * This is the default action handling the main area called without defining arguments.
54
     * @Cache(expires="+7 days", public=true)
55
     *
56
     * @param Request  $request      Current request instance
57
     *
58
     * @return mixed Output
59
     *
60
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
61
     */
62
    public function indexAction(Request $request)
63
    {
64
        return $this->indexInternal($request, false);
65
    }
66
67
    /**
68
     * This method includes the common implementation code for adminIndex() and index().
69
     */
70
    protected function indexInternal(Request $request, $isAdmin = false)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
71
    {
72
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
73
74
        // parameter specifying which type of objects we are treating
75
        $objectType = 'route';
76
        $utilArgs = ['controller' => 'route', 'action' => 'main'];
0 ignored issues
show
Unused Code introduced by
$utilArgs 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...
77
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
78
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
79
            throw new AccessDeniedException();
80
        }
81
82
        if ($isAdmin) {
83
84
            return $this->redirectToRoute('zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view');
85
        }
86
        
87
        if (!$isAdmin) {
88
            
89
            return $this->redirectToRoute('zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view');
90
        }
91
        
92
        $templateParameters = [
93
            'routeArea' => $isAdmin ? 'admin' : ''
94
        ];
95
96
        // return index template
97
        return $this->render('@ZikulaRoutesModule/Route/index.html.twig', $templateParameters);
98
    }
99
    /**
100
     * This action provides an item list overview in the admin area.
101
     * @Cache(expires="+2 hours", public=false)
102
     *
103
     * @param Request  $request      Current request instance
104
     * @param string  $sort         Sorting field
105
     * @param string  $sortdir      Sorting direction
106
     * @param int     $pos          Current pager position
107
     * @param int     $num          Amount of entries to display
108
     *
109
     * @return mixed Output
110
     *
111
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
112
     */
113
    public function adminViewAction(Request $request, $sort, $sortdir, $pos, $num)
114
    {
115
        return $this->viewInternal($request, $sort, $sortdir, $pos, $num, true);
116
    }
117
118
    /**
119
     * This action provides an item list overview.
120
     * @Cache(expires="+2 hours", public=false)
121
     *
122
     * @param Request  $request      Current request instance
123
     * @param string  $sort         Sorting field
124
     * @param string  $sortdir      Sorting direction
125
     * @param int     $pos          Current pager position
126
     * @param int     $num          Amount of entries to display
127
     *
128
     * @return mixed Output
129
     *
130
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
131
     */
132
    public function viewAction(Request $request, $sort, $sortdir, $pos, $num)
133
    {
134
        return $this->viewInternal($request, $sort, $sortdir, $pos, $num, false);
135
    }
136
137
    /**
138
     * This method includes the common implementation code for adminView() and view().
139
     */
140
    protected function viewInternal(Request $request, $sort, $sortdir, $pos, $num, $isAdmin = false)
141
    {
142
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
143
144
        // parameter specifying which type of objects we are treating
145
        $objectType = 'route';
146
        $utilArgs = ['controller' => 'route', 'action' => 'view'];
147
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
148
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
149
            throw new AccessDeniedException();
150
        }
151
        $repository = $this->get('zikula_routes_module.' . $objectType . '_factory')->getRepository();
152
        $repository->setRequest($request);
153
        $viewHelper = $this->get('zikula_routes_module.view_helper');
154
        $templateParameters = [
155
            'routeArea' => $isAdmin ? 'admin' : ''
156
        ];
157
        $selectionHelper = $this->get('zikula_routes_module.selection_helper');
158
159
        // convenience vars to make code clearer
160
        $currentUrlArgs = [];
161
        $where = '';
162
163
        $showOwnEntries = $request->query->getInt('own', $this->getVar('showOnlyOwnEntries', 0));
164
        $showAllEntries = $request->query->getInt('all', 0);
165
        
166
        $templateParameters['own'] = $showAllEntries;
167
        $templateParameters['all'] = $showOwnEntries;
168
        if ($showAllEntries == 1) {
169
            $currentUrlArgs['all'] = 1;
170
        }
171
        if ($showOwnEntries == 1) {
172
            $currentUrlArgs['own'] = 1;
173
        }
174
        
175
        $additionalParameters = $repository->getAdditionalTemplateParameters('controllerAction', $utilArgs);
176
177
        $resultsPerPage = 0;
178
        if ($showAllEntries != 1) {
179
            // the number of items displayed on a page for pagination
180
            $resultsPerPage = $num;
181
            if ($resultsPerPage == 0) {
182
                $resultsPerPage = $this->getVar($objectType . 'EntriesPerPage', 10);
183
            }
184
        }
185
186
        // parameter for used sorting field
187
        if (empty($sort) || !in_array($sort, $repository->getAllowedSortingFields())) {
188
            $sort = $repository->getDefaultSortingField();
189
            $request->query->set('sort', $sort);
190
            // set default sorting in route parameters (e.g. for the pager)
191
            $routeParams = $request->attributes->get('_route_params');
192
            $routeParams['sort'] = $sort;
193
            $request->attributes->set('_route_params', $routeParams);
194
        }
195
196
        // parameter for used sort order
197
        $sortdir = strtolower($sortdir);
198
199
        $sortableColumns = new SortableColumns($this->get('router'), 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view', 'sort', 'sortdir');
200
        $sortableColumns->addColumns([
201
            new Column('routeType'),
202
            new Column('replacedRouteName'),
203
            new Column('bundle'),
204
            new Column('controller'),
205
            new Column('action'),
206
            new Column('path'),
207
            new Column('host'),
208
            new Column('schemes'),
209
            new Column('methods'),
210
            new Column('prependBundlePrefix'),
211
            new Column('translatable'),
212
            new Column('translationPrefix'),
213
            new Column('condition'),
214
            new Column('description'),
215
            new Column('sort'),
216
            new Column('group'),
217
            new Column('createdUserId'),
218
            new Column('createdDate'),
219
            new Column('updatedUserId'),
220
            new Column('updatedDate'),
221
        ]);
222
        
223
        $additionalUrlParameters = [
224
            'all' => $showAllEntries,
225
            'own' => $showOwnEntries,
226
            'num' => $resultsPerPage
227
        ];
228
        foreach ($additionalParameters as $parameterName => $parameterValue) {
229
            if (false !== stripos($parameterName, 'thumbRuntimeOptions')) {
230
                continue;
231
            }
232
            $additionalUrlParameters[$parameterName] = $parameterValue;
233
        }
234
        
235
        $templateParameters['sort'] = $sort;
236
        $templateParameters['sortdir'] = $sortdir;
237
        $templateParameters['num'] = $resultsPerPage;
238
        
239
        $quickNavForm = $this->createForm('Zikula\RoutesModule\Form\Type\QuickNavigation\\' . ucfirst($objectType) . 'QuickNavType', $templateParameters);
240
        if ($quickNavForm->handleRequest($request) && $quickNavForm->isSubmitted()) {
241
            $quickNavData = $quickNavForm->getData();
242
            foreach ($quickNavData as $fieldName => $fieldValue) {
243
                if ($fieldName == 'routeArea') {
244
                    continue;
245
                }
246
                if ($fieldName == 'all') {
247
                    $showAllEntries = $additionalUrlParameters['all'] = $templateParameters['all'] = $fieldValue;
248
                } elseif ($fieldName == 'own') {
249
                    $showOwnEntries = $additionalUrlParameters['own'] = $templateParameters['own'] = $fieldValue;
0 ignored issues
show
Unused Code introduced by
$showOwnEntries 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...
250
                } elseif ($fieldName == 'num') {
251
                    $resultsPerPage = $additionalUrlParameters['num'] = $fieldValue;
252
                } else {
253
                    // set filter as query argument, fetched inside repository
254
                    $request->query->set($fieldName, $fieldValue);
255
                }
256
            }
257
        }
258
        $sortableColumns->setOrderBy($sortableColumns->getColumn($sort), strtoupper($sortdir));
259
        $sortableColumns->setAdditionalUrlParameters($additionalUrlParameters);
260
261
        if ($showAllEntries == 1) {
262
            // retrieve item list without pagination
263
            $entities = $selectionHelper->getEntities($objectType, [], $where, $sort . ' ' . $sortdir);
264
        } else {
265
            // the current offset which is used to calculate the pagination
266
            $currentPage = $pos;
267
268
            // retrieve item list with pagination
269
            list($entities, $objectCount) = $selectionHelper->getEntitiesPaginated($objectType, $where, $sort . ' ' . $sortdir, $currentPage, $resultsPerPage);
270
271
            $templateParameters['currentPage'] = $currentPage;
272
            $templateParameters['pager'] = ['numitems' => $objectCount, 'itemsperpage' => $resultsPerPage];
273
        }
274
275
        foreach ($entities as $k => $entity) {
276
            $entity->initWorkflow();
277
        }
278
279
        $templateParameters['items'] = $entities;
280
        $templateParameters['sort'] = $sort;
281
        $templateParameters['sortdir'] = $sortdir;
282
        $templateParameters['num'] = $resultsPerPage;
283
        $templateParameters = array_merge($templateParameters, $additionalParameters);
284
        
285
        $templateParameters['sort'] = $sortableColumns->generateSortableColumns();
286
        $templateParameters['quickNavForm'] = $quickNavForm->createView();
287
        
288
        $templateParameters['showAllEntries'] = $templateParameters['all'];
289
        $templateParameters['showOwnEntries'] = $templateParameters['own'];
290
        
291
        $modelHelper = $this->get('zikula_routes_module.model_helper');
292
        $templateParameters['canBeCreated'] = $modelHelper->canBeCreated($objectType);
293
294
        // fetch and return the appropriate template
295
        return $viewHelper->processTemplate($this->get('twig'), $objectType, 'view', $request, $templateParameters);
296
    }
297
    /**
298
     * This action provides a item detail view in the admin area.
299
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
300
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
301
     *
302
     * @param Request  $request      Current request instance
303
     * @param RouteEntity $route      Treated route instance
304
     *
305
     * @return mixed Output
306
     *
307
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
308
     * @throws NotFoundHttpException Thrown by param converter if item to be displayed isn't found
309
     */
310
    public function adminDisplayAction(Request $request, RouteEntity $route)
311
    {
312
        return $this->displayInternal($request, $route, true);
313
    }
314
315
    /**
316
     * This action provides a item detail view.
317
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
318
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
319
     *
320
     * @param Request  $request      Current request instance
321
     * @param RouteEntity $route      Treated route instance
322
     *
323
     * @return mixed Output
324
     *
325
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
326
     * @throws NotFoundHttpException Thrown by param converter if item to be displayed isn't found
327
     */
328
    public function displayAction(Request $request, RouteEntity $route)
329
    {
330
        return $this->displayInternal($request, $route, false);
331
    }
332
333
    /**
334
     * This method includes the common implementation code for adminDisplay() and display().
335
     */
336
    protected function displayInternal(Request $request, RouteEntity $route, $isAdmin = false)
337
    {
338
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
339
340
        // parameter specifying which type of objects we are treating
341
        $objectType = 'route';
342
        $utilArgs = ['controller' => 'route', 'action' => 'display'];
343
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
344
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
345
            throw new AccessDeniedException();
346
        }
347
        $repository = $this->get('zikula_routes_module.' . $objectType . '_factory')->getRepository();
348
        $repository->setRequest($request);
349
350
        $entity = $route;
351
352
353
        $entity->initWorkflow();
354
355
        // create identifier for permission check
356
        $instanceId = $entity->createCompositeIdentifier();
357
358
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', $instanceId . '::', $permLevel)) {
359
            throw new AccessDeniedException();
360
        }
361
362
        $viewHelper = $this->get('zikula_routes_module.view_helper');
363
        $templateParameters = [
364
            'routeArea' => $isAdmin ? 'admin' : ''
365
        ];
366
        $templateParameters[$objectType] = $entity;
367
        $templateParameters = array_merge($templateParameters, $repository->getAdditionalTemplateParameters('controllerAction', $utilArgs));
368
369
        // fetch and return the appropriate template
370
        $response = $viewHelper->processTemplate($this->get('twig'), $objectType, 'display', $request, $templateParameters);
371
372
        $format = $request->getRequestFormat();
373
        if ($format == 'ics') {
374
            $fileName = $objectType . '_' . (property_exists($entity, 'slug') ? $entity['slug'] : $entity->getTitleFromDisplayPattern()) . '.ics';
375
            $response->headers->set('Content-Disposition', 'attachment; filename=' . $fileName);
376
        }
377
378
        return $response;
379
    }
380
    /**
381
     * This action provides a handling of edit requests in the admin area.
382
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
383
     *
384
     * @param Request  $request      Current request instance
385
     *
386
     * @return mixed Output
387
     *
388
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
389
     * @throws NotFoundHttpException Thrown by form handler if item to be edited isn't found
390
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
391
     */
392
    public function adminEditAction(Request $request)
393
    {
394
        return $this->editInternal($request, true);
395
    }
396
397
    /**
398
     * This action provides a handling of edit requests.
399
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
400
     *
401
     * @param Request  $request      Current request instance
402
     *
403
     * @return mixed Output
404
     *
405
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
406
     * @throws NotFoundHttpException Thrown by form handler if item to be edited isn't found
407
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
408
     */
409
    public function editAction(Request $request)
410
    {
411
        return $this->editInternal($request, false);
412
    }
413
414
    /**
415
     * This method includes the common implementation code for adminEdit() and edit().
416
     */
417
    protected function editInternal(Request $request, $isAdmin = false)
418
    {
419
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
420
421
        // parameter specifying which type of objects we are treating
422
        $objectType = 'route';
423
        $utilArgs = ['controller' => 'route', 'action' => 'edit'];
424
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_EDIT;
425
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
426
            throw new AccessDeniedException();
427
        }
428
        $repository = $this->get('zikula_routes_module.' . $objectType . '_factory')->getRepository();
429
430
        $templateParameters = [
431
            'routeArea' => $isAdmin ? 'admin' : ''
432
        ];
433
        $templateParameters = array_merge($templateParameters, $repository->getAdditionalTemplateParameters('controllerAction', $utilArgs));
434
435
        // delegate form processing to the form handler
436
        $formHandler = $this->get('zikula_routes_module.form.handler.route');
437
        $result = $formHandler->processForm($templateParameters);
438
        if ($result instanceof RedirectResponse) {
439
            return $result;
440
        }
441
        
442
        $viewHelper = $this->get('zikula_routes_module.view_helper');
443
        $templateParameters = $formHandler->getTemplateParameters();
444
445
        // fetch and return the appropriate template
446
        return $viewHelper->processTemplate($this->get('twig'), $objectType, 'edit', $request, $templateParameters);
447
    }
448
    /**
449
     * This action provides a handling of simple delete requests in the admin area.
450
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
451
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
452
     *
453
     * @param Request  $request      Current request instance
454
     * @param RouteEntity $route      Treated route instance
455
     *
456
     * @return mixed Output
457
     *
458
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
459
     * @throws NotFoundHttpException Thrown by param converter if item to be deleted isn't found
460
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
461
     */
462
    public function adminDeleteAction(Request $request, RouteEntity $route)
463
    {
464
        return $this->deleteInternal($request, $route, true);
465
    }
466
467
    /**
468
     * This action provides a handling of simple delete requests.
469
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
470
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
471
     *
472
     * @param Request  $request      Current request instance
473
     * @param RouteEntity $route      Treated route instance
474
     *
475
     * @return mixed Output
476
     *
477
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
478
     * @throws NotFoundHttpException Thrown by param converter if item to be deleted isn't found
479
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
480
     */
481
    public function deleteAction(Request $request, RouteEntity $route)
482
    {
483
        return $this->deleteInternal($request, $route, false);
484
    }
485
486
    /**
487
     * This method includes the common implementation code for adminDelete() and delete().
488
     */
489
    protected function deleteInternal(Request $request, RouteEntity $route, $isAdmin = false)
490
    {
491
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
492
493
        // parameter specifying which type of objects we are treating
494
        $objectType = 'route';
495
        $utilArgs = ['controller' => 'route', 'action' => 'delete'];
496
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_DELETE;
497
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
498
            throw new AccessDeniedException();
499
        }
500
        $entity = $route;
501
502
        $logger = $this->get('logger');
503
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $this->get('zikula_users_module.current_user')->get('uname'), 'entity' => 'route', 'id' => $entity->createCompositeIdentifier()];
504
505
        $entity->initWorkflow();
506
507
        // determine available workflow actions
508
        $workflowHelper = $this->get('zikula_routes_module.workflow_helper');
509
        $actions = $workflowHelper->getActionsForObject($entity);
510
        if (false === $actions || !is_array($actions)) {
511
            $this->addFlash('error', $this->__('Error! Could not determine workflow actions.'));
512
            $logger->error('{app}: User {user} tried to delete the {entity} with id {id}, but failed to determine available workflow actions.', $logArgs);
513
            throw new \RuntimeException($this->__('Error! Could not determine workflow actions.'));
514
        }
515
        
516
        if ($isAdmin) {
517
            // redirect to the list of routes
518
            $redirectRoute = 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view';
519
        } else {
520
            // redirect to the list of routes
521
            $redirectRoute = 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view';
522
        }
523
        
524
        // check whether deletion is allowed
525
        $deleteActionId = 'delete';
526
        $deleteAllowed = false;
527
        foreach ($actions as $actionId => $action) {
528
            if ($actionId != $deleteActionId) {
529
                continue;
530
            }
531
            $deleteAllowed = true;
532
            break;
533
        }
534
        if (!$deleteAllowed) {
535
            $this->addFlash('error', $this->__('Error! It is not allowed to delete this route.'));
536
            $logger->error('{app}: User {user} tried to delete the {entity} with id {id}, but this action was not allowed.', $logArgs);
537
538
            return $this->redirectToRoute($redirectRoute);
539
        }
540
541
        $form = $this->createForm('Zikula\RoutesModule\Form\DeleteEntityType', $entity);
542
543
        if ($form->handleRequest($request)->isValid()) {
544
            if ($form->get('delete')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

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...
545
                // execute the workflow action
546
                $success = $workflowHelper->executeAction($entity, $deleteActionId);
547
                if ($success) {
548
                    $this->addFlash('status', $this->__('Done! Item deleted.'));
549
                    $logger->notice('{app}: User {user} deleted the {entity} with id {id}.', $logArgs);
550
                }
551
552
                return $this->redirectToRoute($redirectRoute);
553
            } elseif ($form->get('cancel')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

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...
554
                $this->addFlash('status', $this->__('Operation cancelled.'));
555
556
                return $this->redirectToRoute($redirectRoute);
557
            }
558
        }
559
560
        $repository = $this->get('zikula_routes_module.' . $objectType . '_factory')->getRepository();
561
562
        $viewHelper = $this->get('zikula_routes_module.view_helper');
563
        $templateParameters = [
564
            'routeArea' => $isAdmin ? 'admin' : '',
565
            'deleteForm' => $form->createView()
566
        ];
567
568
        $templateParameters[$objectType] = $entity;
569
        $templateParameters = array_merge($templateParameters, $repository->getAdditionalTemplateParameters('controllerAction', $utilArgs));
570
571
        // fetch and return the appropriate template
572
        return $viewHelper->processTemplate($this->get('twig'), $objectType, 'delete', $request, $templateParameters);
573
    }
574
    /**
575
     * This is a custom action in the admin area.
576
     *
577
     * @param Request  $request      Current request instance
578
     *
579
     * @return mixed Output
580
     *
581
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
582
     */
583
    public function adminReloadAction(Request $request)
584
    {
585
        return $this->reloadInternal($request, true);
586
    }
587
588
    /**
589
     * This is a custom action.
590
     *
591
     * @param Request  $request      Current request instance
592
     *
593
     * @return mixed Output
594
     *
595
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
596
     */
597
    public function reloadAction(Request $request)
598
    {
599
        return $this->reloadInternal($request, false);
600
    }
601
602
    /**
603
     * This method includes the common implementation code for adminReload() and reload().
604
     */
605 View Code Duplication
    protected function reloadInternal(Request $request, $isAdmin = false)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
606
    {
607
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
608
609
        // parameter specifying which type of objects we are treating
610
        $objectType = 'route';
611
        $utilArgs = ['controller' => 'route', 'action' => 'reload'];
0 ignored issues
show
Unused Code introduced by
$utilArgs 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...
612
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
613
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
614
            throw new AccessDeniedException();
615
        }
616
        /** TODO: custom logic */
617
618
        $templateParameters = [
619
            'routeArea' => $isAdmin ? 'admin' : ''
620
        ];
621
622
        // return template
623
        return $this->render('@ZikulaRoutesModule/Route/reload.html.twig', $templateParameters);
624
    }
625
    /**
626
     * This is a custom action in the admin area.
627
     *
628
     * @param Request  $request      Current request instance
629
     *
630
     * @return mixed Output
631
     *
632
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
633
     */
634
    public function adminRenewAction(Request $request)
635
    {
636
        return $this->renewInternal($request, true);
637
    }
638
639
    /**
640
     * This is a custom action.
641
     *
642
     * @param Request  $request      Current request instance
643
     *
644
     * @return mixed Output
645
     *
646
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
647
     */
648
    public function renewAction(Request $request)
649
    {
650
        return $this->renewInternal($request, false);
651
    }
652
653
    /**
654
     * This method includes the common implementation code for adminRenew() and renew().
655
     */
656 View Code Duplication
    protected function renewInternal(Request $request, $isAdmin = false)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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...
657
    {
658
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
0 ignored issues
show
Unused Code introduced by
$controllerHelper 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...
659
660
        // parameter specifying which type of objects we are treating
661
        $objectType = 'route';
662
        $utilArgs = ['controller' => 'route', 'action' => 'renew'];
0 ignored issues
show
Unused Code introduced by
$utilArgs 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...
663
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
664
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
665
            throw new AccessDeniedException();
666
        }
667
        /** TODO: custom logic */
668
669
        $templateParameters = [
670
            'routeArea' => $isAdmin ? 'admin' : ''
671
        ];
672
673
        // return template
674
        return $this->render('@ZikulaRoutesModule/Route/renew.html.twig', $templateParameters);
675
    }
676
677
    /**
678
     * Process status changes for multiple items.
679
     *
680
     * This function processes the items selected in the admin view page.
681
     * Multiple items may have their state changed or be deleted.
682
     *
683
     * @param Request $request Current request instance
684
     *
685
     * @return bool true on sucess, false on failure
686
     *
687
     * @throws RuntimeException Thrown if executing the workflow action fails
688
     */
689
    public function adminHandleSelectedEntriesAction(Request $request)
690
    {
691
        return $this->handleSelectedEntriesActionInternal($request, true);
692
    }
693
    /**
694
     * Process status changes for multiple items.
695
     *
696
     * This function processes the items selected in the admin view page.
697
     * Multiple items may have their state changed or be deleted.
698
     *
699
     * @param Request $request Current request instance
700
     *
701
     * @return bool true on sucess, false on failure
702
     *
703
     * @throws RuntimeException Thrown if executing the workflow action fails
704
     */
705
    public function handleSelectedEntriesAction(Request $request)
706
    {
707
        return $this->handleSelectedEntriesActionInternal($request, false);
708
    }
709
710
    /**
711
     * This method includes the common implementation code for adminHandleSelectedEntriesAction() and handleSelectedEntriesAction().
712
     */
713
    protected function handleSelectedEntriesActionInternal(Request $request, $isAdmin = false)
714
    {
715
        $objectType = 'route';
716
717
        // Get parameters
718
        $action = $request->request->get('action', null);
719
        $items = $request->request->get('items', null);
720
721
        $action = strtolower($action);
722
723
        $workflowHelper = $this->get('zikula_routes_module.workflow_helper');
724
        $logger = $this->get('logger');
725
        $userName = $this->get('zikula_users_module.current_user')->get('uname');
726
727
        // process each item
728
        foreach ($items as $itemid) {
729
            // check if item exists, and get record instance
730
            $selectionHelper = $this->get('zikula_routes_module.selection_helper');
731
            $entity = $selectionHelper->getEntity($objectType, $itemid, false);
732
733
            $entity->initWorkflow();
734
735
            // check if $action can be applied to this entity (may depend on it's current workflow state)
736
            $allowedActions = $workflowHelper->getActionsForObject($entity);
737
            $actionIds = array_keys($allowedActions);
738
            if (!in_array($action, $actionIds)) {
739
                // action not allowed, skip this object
740
                continue;
741
            }
742
743
            $success = false;
744
            try {
745
                if ($action != 'delete' && !$entity->validate()) {
746
                    continue;
747
                }
748
                // execute the workflow action
749
                $success = $workflowHelper->executeAction($entity, $action);
750
            } catch(\Exception $e) {
751
                $this->addFlash('error', $this->__f('Sorry, but an error occured during the %s action.', ['%s' => $action]) . '  ' . $e->getMessage());
752
                $logger->error('{app}: User {user} tried to execute the {action} workflow action for the {entity} with id {id}, but failed. Error details: {errorMessage}.', ['app' => 'ZikulaRoutesModule', 'user' => $userName, 'action' => $action, 'entity' => 'route', 'id' => $itemid, 'errorMessage' => $e->getMessage()]);
753
            }
754
755
            if (!$success) {
756
                continue;
757
            }
758
759
            if ($action == 'delete') {
760
                $this->addFlash('status', $this->__('Done! Item deleted.'));
761
                $logger->notice('{app}: User {user} deleted the {entity} with id {id}.', ['app' => 'ZikulaRoutesModule', 'user' => $userName, 'entity' => 'route', 'id' => $itemid]);
762
            } else {
763
                $this->addFlash('status', $this->__('Done! Item updated.'));
764
                $logger->notice('{app}: User {user} executed the {action} workflow action for the {entity} with id {id}.', ['app' => 'ZikulaRoutesModule', 'user' => $userName, 'action' => $action, 'entity' => 'route', 'id' => $itemid]);
765
            }
766
        }
767
768
        return $this->redirectToRoute('zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'index');
769
    }
770
}
771