Completed
Push — master ( b8f763...47a15d )
by Craig
14:22 queued 07:28
created

AbstractRouteController::reloadInternal()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 19
Code Lines 9

Duplication

Lines 19
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 6
nop 2
dl 19
loc 19
rs 9.2
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.2 (http://modulestudio.de).
11
 */
12
13
namespace Zikula\RoutesModule\Controller\Base;
14
15
use RuntimeException;
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 Zikula\Component\SortableColumns\Column;
24
use Zikula\Component\SortableColumns\SortableColumns;
25
use Zikula\Core\Controller\AbstractController;
26
use Zikula\RoutesModule\Entity\RouteEntity;
27
28
/**
29
 * Route controller base class.
30
 */
31
abstract class AbstractRouteController extends AbstractController
32
{
33
    /**
34
     * This is the default action handling the main admin area called without defining arguments.
35
     * @Cache(expires="+7 days", public=true)
36
     *
37
     * @param Request $request Current request instance
38
     *
39
     * @return Response Output
40
     *
41
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
42
     */
43
    public function adminIndexAction(Request $request)
44
    {
45
        return $this->indexInternal($request, true);
46
    }
47
48
    /**
49
     * This is the default action handling the main area called without defining arguments.
50
     * @Cache(expires="+7 days", public=true)
51
     *
52
     * @param Request $request Current request instance
53
     *
54
     * @return Response Output
55
     *
56
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
57
     */
58
    public function indexAction(Request $request)
59
    {
60
        return $this->indexInternal($request, false);
61
    }
62
63
    /**
64
     * This method includes the common implementation code for adminIndex() and index().
65
     */
66
    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...
67
    {
68
        $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...
69
70
        // parameter specifying which type of objects we are treating
71
        $objectType = 'route';
72
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
73
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
74
            throw new AccessDeniedException();
75
        }
76
        $templateParameters = [
77
            'routeArea' => $isAdmin ? 'admin' : ''
78
        ];
79
        
80
        return $this->redirectToRoute('zikularoutesmodule_route_' . $templateParameters['routeArea'] . 'view');
81
        
82
        // return index template
83
        return $this->render('@ZikulaRoutesModule/Route/index.html.twig', $templateParameters);
0 ignored issues
show
Unused Code introduced by
// return index template..., $templateParameters); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
84
    }
85
    /**
86
     * This action provides an item list overview in the admin area.
87
     * @Cache(expires="+2 hours", public=false)
88
     *
89
     * @param Request $request Current request instance
90
     * @param string $sort         Sorting field
91
     * @param string $sortdir      Sorting direction
92
     * @param int    $pos          Current pager position
93
     * @param int    $num          Amount of entries to display
94
     *
95
     * @return Response Output
96
     *
97
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
98
     */
99
    public function adminViewAction(Request $request, $sort, $sortdir, $pos, $num)
100
    {
101
        return $this->viewInternal($request, $sort, $sortdir, $pos, $num, true);
102
    }
103
104
    /**
105
     * This action provides an item list overview.
106
     * @Cache(expires="+2 hours", public=false)
107
     *
108
     * @param Request $request Current request instance
109
     * @param string $sort         Sorting field
110
     * @param string $sortdir      Sorting direction
111
     * @param int    $pos          Current pager position
112
     * @param int    $num          Amount of entries to display
113
     *
114
     * @return Response Output
115
     *
116
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
117
     */
118
    public function viewAction(Request $request, $sort, $sortdir, $pos, $num)
119
    {
120
        return $this->viewInternal($request, $sort, $sortdir, $pos, $num, false);
121
    }
122
123
    /**
124
     * This method includes the common implementation code for adminView() and view().
125
     */
126
    protected function viewInternal(Request $request, $sort, $sortdir, $pos, $num, $isAdmin = false)
0 ignored issues
show
Unused Code introduced by
The parameter $pos 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...
Unused Code introduced by
The parameter $num 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...
127
    {
128
        $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...
129
130
        // parameter specifying which type of objects we are treating
131
        $objectType = 'route';
132
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
133
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
134
            throw new AccessDeniedException();
135
        }
136
        $templateParameters = [
137
            'routeArea' => $isAdmin ? 'admin' : ''
138
        ];
139
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
140
        $viewHelper = $this->get('zikula_routes_module.view_helper');
141
        
142
        // parameter for used sort order
143
        $sortdir = strtolower($sortdir);
144
        $request->query->set('sort', $sort);
145
        $request->query->set('sortdir', $sortdir);
146
        
147
        $sortableColumns = new SortableColumns($this->get('router'), 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view', 'sort', 'sortdir');
148
        
149
        $sortableColumns->addColumns([
150
            new Column('routeType'),
151
            new Column('replacedRouteName'),
152
            new Column('bundle'),
153
            new Column('controller'),
154
            new Column('action'),
155
            new Column('path'),
156
            new Column('host'),
157
            new Column('schemes'),
158
            new Column('methods'),
159
            new Column('prependBundlePrefix'),
160
            new Column('translatable'),
161
            new Column('translationPrefix'),
162
            new Column('condition'),
163
            new Column('description'),
164
            new Column('sort'),
165
            new Column('group'),
166
            new Column('createdBy'),
167
            new Column('createdDate'),
168
            new Column('updatedBy'),
169
            new Column('updatedDate'),
170
        ]);
171
        
172
        $templateParameters = $controllerHelper->processViewActionParameters($objectType, $sortableColumns, $templateParameters);
173
        
174
        foreach ($templateParameters['items'] as $k => $entity) {
175
            $entity->initWorkflow();
176
        }
177
        
178
        // fetch and return the appropriate template
179
        return $viewHelper->processTemplate($objectType, 'view', $templateParameters);
180
    }
181
    /**
182
     * This action provides a item detail view in the admin area.
183
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
184
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
185
     *
186
     * @param Request $request Current request instance
187
     * @param RouteEntity $route Treated route instance
188
     *
189
     * @return Response Output
190
     *
191
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
192
     * @throws NotFoundHttpException Thrown by param converter if item to be displayed isn't found
193
     */
194
    public function adminDisplayAction(Request $request, RouteEntity $route)
195
    {
196
        return $this->displayInternal($request, $route, true);
197
    }
198
199
    /**
200
     * This action provides a item detail view.
201
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
202
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
203
     *
204
     * @param Request $request Current request instance
205
     * @param RouteEntity $route Treated route instance
206
     *
207
     * @return Response Output
208
     *
209
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
210
     * @throws NotFoundHttpException Thrown by param converter if item to be displayed isn't found
211
     */
212
    public function displayAction(Request $request, RouteEntity $route)
213
    {
214
        return $this->displayInternal($request, $route, false);
215
    }
216
217
    /**
218
     * This method includes the common implementation code for adminDisplay() and display().
219
     */
220
    protected function displayInternal(Request $request, RouteEntity $route, $isAdmin = false)
221
    {
222
        $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...
223
224
        // parameter specifying which type of objects we are treating
225
        $objectType = 'route';
226
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
227
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
228
            throw new AccessDeniedException();
229
        }
230
        // create identifier for permission check
231
        $instanceId = $route->createCompositeIdentifier();
232
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', $instanceId . '::', $permLevel)) {
233
            throw new AccessDeniedException();
234
        }
235
        
236
        $route->initWorkflow();
237
        $templateParameters = [
238
            'routeArea' => $isAdmin ? 'admin' : '',
239
            $objectType => $route
240
        ];
241
        
242
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
243
        $templateParameters = $controllerHelper->processDisplayActionParameters($objectType, $templateParameters);
244
        
245
        // fetch and return the appropriate template
246
        $response = $this->get('zikula_routes_module.view_helper')->processTemplate($objectType, 'display', $templateParameters);
247
        
248
        $format = $request->getRequestFormat();
249
        if ($format == 'ics') {
250
            $fileName = $objectType . '_' . (property_exists($route, 'slug') ? $route['slug'] : $route->getTitleFromDisplayPattern()) . '.ics';
251
            $response->headers->set('Content-Disposition', 'attachment; filename=' . $fileName);
252
        }
253
254
        return $response;
255
    }
256
    /**
257
     * This action provides a handling of edit requests in the admin area.
258
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
259
     *
260
     * @param Request $request Current request instance
261
     *
262
     * @return Response Output
263
     *
264
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
265
     * @throws NotFoundHttpException Thrown by form handler if item to be edited isn't found
266
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
267
     */
268
    public function adminEditAction(Request $request)
269
    {
270
        return $this->editInternal($request, true);
271
    }
272
273
    /**
274
     * This action provides a handling of edit requests.
275
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
276
     *
277
     * @param Request $request Current request instance
278
     *
279
     * @return Response Output
280
     *
281
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
282
     * @throws NotFoundHttpException Thrown by form handler if item to be edited isn't found
283
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
284
     */
285
    public function editAction(Request $request)
286
    {
287
        return $this->editInternal($request, false);
288
    }
289
290
    /**
291
     * This method includes the common implementation code for adminEdit() and edit().
292
     */
293
    protected function editInternal(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...
294
    {
295
        $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...
296
297
        // parameter specifying which type of objects we are treating
298
        $objectType = 'route';
299
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_EDIT;
300
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
301
            throw new AccessDeniedException();
302
        }
303
        $templateParameters = [
304
            'routeArea' => $isAdmin ? 'admin' : ''
305
        ];
306
        
307
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
308
        $templateParameters = $controllerHelper->processEditActionParameters($objectType, $templateParameters);
309
        
310
        // delegate form processing to the form handler
311
        $formHandler = $this->get('zikula_routes_module.form.handler.route');
312
        $result = $formHandler->processForm($templateParameters);
313
        if ($result instanceof RedirectResponse) {
314
            return $result;
315
        }
316
        
317
        $templateParameters = $formHandler->getTemplateParameters();
318
319
        // fetch and return the appropriate template
320
        return $this->get('zikula_routes_module.view_helper')->processTemplate($objectType, 'edit', $templateParameters);
321
    }
322
    /**
323
     * This action provides a handling of simple delete requests in the admin area.
324
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
325
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
326
     *
327
     * @param Request $request Current request instance
328
     * @param RouteEntity $route Treated route instance
329
     *
330
     * @return Response Output
331
     *
332
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
333
     * @throws NotFoundHttpException Thrown by param converter if item to be deleted isn't found
334
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
335
     */
336
    public function adminDeleteAction(Request $request, RouteEntity $route)
337
    {
338
        return $this->deleteInternal($request, $route, true);
339
    }
340
341
    /**
342
     * This action provides a handling of simple delete requests.
343
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options={"id" = "id", "repository_method" = "selectById"})
344
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
345
     *
346
     * @param Request $request Current request instance
347
     * @param RouteEntity $route Treated route instance
348
     *
349
     * @return Response Output
350
     *
351
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
352
     * @throws NotFoundHttpException Thrown by param converter if item to be deleted isn't found
353
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
354
     */
355
    public function deleteAction(Request $request, RouteEntity $route)
356
    {
357
        return $this->deleteInternal($request, $route, false);
358
    }
359
360
    /**
361
     * This method includes the common implementation code for adminDelete() and delete().
362
     */
363
    protected function deleteInternal(Request $request, RouteEntity $route, $isAdmin = false)
364
    {
365
        $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...
366
367
        // parameter specifying which type of objects we are treating
368
        $objectType = 'route';
369
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_DELETE;
370
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
371
            throw new AccessDeniedException();
372
        }
373
        $logger = $this->get('logger');
374
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $this->get('zikula_users_module.current_user')->get('uname'), 'entity' => 'route', 'id' => $route->createCompositeIdentifier()];
375
        
376
        $route->initWorkflow();
377
        
378
        // determine available workflow actions
379
        $workflowHelper = $this->get('zikula_routes_module.workflow_helper');
380
        $actions = $workflowHelper->getActionsForObject($route);
381
        if (false === $actions || !is_array($actions)) {
382
            $this->addFlash('error', $this->__('Error! Could not determine workflow actions.'));
383
            $logger->error('{app}: User {user} tried to delete the {entity} with id {id}, but failed to determine available workflow actions.', $logArgs);
384
            throw new \RuntimeException($this->__('Error! Could not determine workflow actions.'));
385
        }
386
        
387
        // redirect to the list of routes
388
        $redirectRoute = 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view';
389
        
390
        // check whether deletion is allowed
391
        $deleteActionId = 'delete';
392
        $deleteAllowed = false;
393
        foreach ($actions as $actionId => $action) {
394
            if ($actionId != $deleteActionId) {
395
                continue;
396
            }
397
            $deleteAllowed = true;
398
            break;
399
        }
400
        if (!$deleteAllowed) {
401
            $this->addFlash('error', $this->__('Error! It is not allowed to delete this route.'));
402
            $logger->error('{app}: User {user} tried to delete the {entity} with id {id}, but this action was not allowed.', $logArgs);
403
404
            return $this->redirectToRoute($redirectRoute);
405
        }
406
        
407
        $form = $this->createForm('Zikula\RoutesModule\Form\DeleteEntityType', $route);
408
        
409
        if ($form->handleRequest($request)->isValid()) {
410
            if ($form->get('delete')->isClicked()) {
0 ignored issues
show
Bug introduced by
The method isClicked() does not seem to exist on object<Symfony\Component\Form\Form>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
411
                // execute the workflow action
412
                $success = $workflowHelper->executeAction($route, $deleteActionId);
413
                if ($success) {
414
                    $this->addFlash('status', $this->__('Done! Item deleted.'));
415
                    $logger->notice('{app}: User {user} deleted the {entity} with id {id}.', $logArgs);
416
                }
417
418
                return $this->redirectToRoute($redirectRoute);
419
            } elseif ($form->get('cancel')->isClicked()) {
0 ignored issues
show
Bug introduced by
The method isClicked() does not seem to exist on object<Symfony\Component\Form\Form>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
420
                $this->addFlash('status', $this->__('Operation cancelled.'));
421
422
                return $this->redirectToRoute($redirectRoute);
423
            }
424
        }
425
        
426
        $templateParameters = [
427
            'routeArea' => $isAdmin ? 'admin' : '',
428
            'deleteForm' => $form->createView(),
429
            $objectType => $route
430
        ];
431
        
432
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
433
        $templateParameters = $controllerHelper->processDeleteActionParameters($objectType, $templateParameters);
434
        
435
        // fetch and return the appropriate template
436
        return $this->get('zikula_routes_module.view_helper')->processTemplate($objectType, 'delete', $templateParameters);
437
    }
438
    /**
439
     * This is a custom action in the admin area.
440
     *
441
     * @param Request $request Current request instance
442
     *
443
     * @return Response Output
444
     *
445
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
446
     */
447
    public function adminReloadAction(Request $request)
448
    {
449
        return $this->reloadInternal($request, true);
450
    }
451
452
    /**
453
     * This is a custom action.
454
     *
455
     * @param Request $request Current request instance
456
     *
457
     * @return Response Output
458
     *
459
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
460
     */
461
    public function reloadAction(Request $request)
462
    {
463
        return $this->reloadInternal($request, false);
464
    }
465
466
    /**
467
     * This method includes the common implementation code for adminReload() and reload().
468
     */
469 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...
470
    {
471
        $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...
472
473
        // parameter specifying which type of objects we are treating
474
        $objectType = 'route';
475
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
476
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
477
            throw new AccessDeniedException();
478
        }
479
        /** TODO: custom logic */
480
481
        $templateParameters = [
482
            'routeArea' => $isAdmin ? 'admin' : ''
483
        ];
484
485
        // return template
486
        return $this->render('@ZikulaRoutesModule/Route/reload.html.twig', $templateParameters);
487
    }
488
    /**
489
     * This is a custom action in the admin area.
490
     *
491
     * @param Request $request Current request instance
492
     *
493
     * @return Response Output
494
     *
495
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
496
     */
497
    public function adminRenewAction(Request $request)
498
    {
499
        return $this->renewInternal($request, true);
500
    }
501
502
    /**
503
     * This is a custom action.
504
     *
505
     * @param Request $request Current request instance
506
     *
507
     * @return Response Output
508
     *
509
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
510
     */
511
    public function renewAction(Request $request)
512
    {
513
        return $this->renewInternal($request, false);
514
    }
515
516
    /**
517
     * This method includes the common implementation code for adminRenew() and renew().
518
     */
519 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...
520
    {
521
        $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...
522
523
        // parameter specifying which type of objects we are treating
524
        $objectType = 'route';
525
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
526
        if (!$this->hasPermission($this->name . ':' . ucfirst($objectType) . ':', '::', $permLevel)) {
527
            throw new AccessDeniedException();
528
        }
529
        /** TODO: custom logic */
530
531
        $templateParameters = [
532
            'routeArea' => $isAdmin ? 'admin' : ''
533
        ];
534
535
        // return template
536
        return $this->render('@ZikulaRoutesModule/Route/renew.html.twig', $templateParameters);
537
    }
538
539
    /**
540
     * Process status changes for multiple items.
541
     *
542
     * This function processes the items selected in the admin view page.
543
     * Multiple items may have their state changed or be deleted.
544
     *
545
     * @param Request $request Current request instance
546
     *
547
     * @return bool true on sucess, false on failure
548
     *
549
     * @throws RuntimeException Thrown if executing the workflow action fails
550
     */
551
    public function adminHandleSelectedEntriesAction(Request $request)
552
    {
553
        return $this->handleSelectedEntriesActionInternal($request, true);
554
    }
555
    /**
556
     * Process status changes for multiple items.
557
     *
558
     * This function processes the items selected in the admin view page.
559
     * Multiple items may have their state changed or be deleted.
560
     *
561
     * @param Request $request Current request instance
562
     *
563
     * @return bool true on sucess, false on failure
564
     *
565
     * @throws RuntimeException Thrown if executing the workflow action fails
566
     */
567
    public function handleSelectedEntriesAction(Request $request)
568
    {
569
        return $this->handleSelectedEntriesActionInternal($request, false);
570
    }
571
572
    /**
573
     * This method includes the common implementation code for adminHandleSelectedEntriesAction() and handleSelectedEntriesAction().
574
     */
575
    protected function handleSelectedEntriesActionInternal(Request $request, $isAdmin = false)
576
    {
577
        $objectType = 'route';
578
579
        // Get parameters
580
        $action = $request->request->get('action', null);
581
        $items = $request->request->get('items', null);
582
583
        $action = strtolower($action);
584
        
585
        $selectionHelper = $this->get('zikula_routes_module.selection_helper');
586
        $workflowHelper = $this->get('zikula_routes_module.workflow_helper');
587
        $logger = $this->get('logger');
588
        $userName = $this->get('zikula_users_module.current_user')->get('uname');
589
590
        // process each item
591
        foreach ($items as $itemid) {
592
            // check if item exists, and get record instance
593
            $entity = $selectionHelper->getEntity($objectType, $itemid, false);
594
            if (null === $entity) {
595
                continue;
596
            }
597
            $entity->initWorkflow();
598
599
            // check if $action can be applied to this entity (may depend on it's current workflow state)
600
            $allowedActions = $workflowHelper->getActionsForObject($entity);
601
            $actionIds = array_keys($allowedActions);
602
            if (!in_array($action, $actionIds)) {
603
                // action not allowed, skip this object
604
                continue;
605
            }
606
607
            $success = false;
608
            try {
609
                if ($action != 'delete' && !$entity->validate()) {
610
                    continue;
611
                }
612
                // execute the workflow action
613
                $success = $workflowHelper->executeAction($entity, $action);
614
            } catch(\Exception $e) {
615
                $this->addFlash('error', $this->__f('Sorry, but an error occured during the %action% action.', ['%action%' => $action]) . '  ' . $e->getMessage());
616
                $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()]);
617
            }
618
619
            if (!$success) {
620
                continue;
621
            }
622
623
            if ($action == 'delete') {
624
                $this->addFlash('status', $this->__('Done! Item deleted.'));
625
                $logger->notice('{app}: User {user} deleted the {entity} with id {id}.', ['app' => 'ZikulaRoutesModule', 'user' => $userName, 'entity' => 'route', 'id' => $itemid]);
626
            } else {
627
                $this->addFlash('status', $this->__('Done! Item updated.'));
628
                $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]);
629
            }
630
        }
631
632
        return $this->redirectToRoute('zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'index');
633
    }
634
}
635