Completed
Push — master ( 48cc3d...5640fa )
by Craig
12:32 queued 05:19
created

AbstractRouteController::adminEditAction()   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 1
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.4 (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\Bundle\FormExtensionBundle\Form\Type\DeletionType;
24
use Zikula\Component\SortableColumns\Column;
25
use Zikula\Component\SortableColumns\SortableColumns;
26
use Zikula\Core\Controller\AbstractController;
27
use Zikula\RoutesModule\Entity\RouteEntity;
28
29
/**
30
 * Route controller base class.
31
 */
32
abstract class AbstractRouteController extends AbstractController
33
{
34
    /**
35
     * This is the default action handling the main admin area called without defining arguments.
36
     * @Cache(expires="+7 days", public=true)
37
     *
38
     * @param Request $request Current request instance
39
     *
40
     * @return Response Output
41
     *
42
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
43
     */
44
    public function adminIndexAction(Request $request)
45
    {
46
        return $this->indexInternal($request, true);
47
    }
48
49
    /**
50
     * This is the default action handling the main area called without defining arguments.
51
     * @Cache(expires="+7 days", public=true)
52
     *
53
     * @param Request $request Current request instance
54
     *
55
     * @return Response Output
56
     *
57
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
58
     */
59
    public function indexAction(Request $request)
60
    {
61
        return $this->indexInternal($request, false);
62
    }
63
64
    /**
65
     * This method includes the common implementation code for adminIndex() and index().
66
     */
67
    protected function indexInternal(Request $request, $isAdmin = false)
68
    {
69
        $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...
70
71
        // parameter specifying which type of objects we are treating
72
        $objectType = 'route';
73
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
74
        if (!$this->hasPermission('ZikulaRoutesModule:' . ucfirst($objectType) . ':', '::', $permLevel)) {
75
            throw new AccessDeniedException();
76
        }
77
        $templateParameters = [
78
            'routeArea' => $isAdmin ? 'admin' : ''
79
        ];
80
81
        return $this->redirectToRoute('zikularoutesmodule_route_' . $templateParameters['routeArea'] . 'view');
82
83
        // return index template
84
        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...
85
    }
86
    /**
87
     * This action provides an item list overview in the admin area.
88
     * @Cache(expires="+2 hours", public=false)
89
     *
90
     * @param Request $request Current request instance
91
     * @param string $sort         Sorting field
92
     * @param string $sortdir      Sorting direction
93
     * @param int    $pos          Current pager position
94
     * @param int    $num          Amount of entries to display
95
     *
96
     * @return Response Output
97
     *
98
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
99
     */
100
    public function adminViewAction(Request $request, $sort, $sortdir, $pos, $num)
101
    {
102
        return $this->viewInternal($request, $sort, $sortdir, $pos, $num, true);
103
    }
104
105
    /**
106
     * This action provides an item list overview.
107
     * @Cache(expires="+2 hours", public=false)
108
     *
109
     * @param Request $request Current request instance
110
     * @param string $sort         Sorting field
111
     * @param string $sortdir      Sorting direction
112
     * @param int    $pos          Current pager position
113
     * @param int    $num          Amount of entries to display
114
     *
115
     * @return Response Output
116
     *
117
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
118
     */
119
    public function viewAction(Request $request, $sort, $sortdir, $pos, $num)
120
    {
121
        return $this->viewInternal($request, $sort, $sortdir, $pos, $num, false);
122
    }
123
124
    /**
125
     * This method includes the common implementation code for adminView() and view().
126
     */
127
    protected function viewInternal(Request $request, $sort, $sortdir, $pos, $num, $isAdmin = false)
128
    {
129
        $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...
130
131
        // parameter specifying which type of objects we are treating
132
        $objectType = 'route';
133
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
134
        if (!$this->hasPermission('ZikulaRoutesModule:' . ucfirst($objectType) . ':', '::', $permLevel)) {
135
            throw new AccessDeniedException();
136
        }
137
        $templateParameters = [
138
            'routeArea' => $isAdmin ? 'admin' : ''
139
        ];
140
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
141
        $viewHelper = $this->get('zikula_routes_module.view_helper');
142
143
        // parameter for used sort order
144
        $sortdir = strtolower($sortdir);
145
        $request->query->set('sort', $sort);
146
        $request->query->set('sortdir', $sortdir);
147
148
        $sortableColumns = new SortableColumns($this->get('router'), 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view', 'sort', 'sortdir');
149
150
        $sortableColumns->addColumns([
151
            new Column('routeType'),
152
            new Column('replacedRouteName'),
153
            new Column('bundle'),
154
            new Column('controller'),
155
            new Column('action'),
156
            new Column('path'),
157
            new Column('host'),
158
            new Column('schemes'),
159
            new Column('methods'),
160
            new Column('prependBundlePrefix'),
161
            new Column('translatable'),
162
            new Column('translationPrefix'),
163
            new Column('condition'),
164
            new Column('description'),
165
            new Column('sort'),
166
            new Column('group'),
167
            new Column('createdBy'),
168
            new Column('createdDate'),
169
            new Column('updatedBy'),
170
            new Column('updatedDate'),
171
        ]);
172
173
        $templateParameters = $controllerHelper->processViewActionParameters($objectType, $sortableColumns, $templateParameters);
174
        
175
        
176
        // fetch and return the appropriate template
177
        return $viewHelper->processTemplate($objectType, 'view', $templateParameters);
178
    }
179
    /**
180
     * This action provides a item detail view in the admin area.
181
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options = {"id" = "id", "repository_method" = "selectById"})
182
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
183
     *
184
     * @param Request $request Current request instance
185
     * @param RouteEntity $route Treated route instance
186
     *
187
     * @return Response Output
188
     *
189
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
190
     * @throws NotFoundHttpException Thrown by param converter if route to be displayed isn't found
191
     */
192
    public function adminDisplayAction(Request $request, RouteEntity $route)
193
    {
194
        return $this->displayInternal($request, $route, true);
195
    }
196
197
    /**
198
     * This action provides a item detail view.
199
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options = {"id" = "id", "repository_method" = "selectById"})
200
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
201
     *
202
     * @param Request $request Current request instance
203
     * @param RouteEntity $route Treated route instance
204
     *
205
     * @return Response Output
206
     *
207
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
208
     * @throws NotFoundHttpException Thrown by param converter if route to be displayed isn't found
209
     */
210
    public function displayAction(Request $request, RouteEntity $route)
211
    {
212
        return $this->displayInternal($request, $route, false);
213
    }
214
215
    /**
216
     * This method includes the common implementation code for adminDisplay() and display().
217
     */
218
    protected function displayInternal(Request $request, RouteEntity $route, $isAdmin = false)
219
    {
220
        $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...
221
222
        // parameter specifying which type of objects we are treating
223
        $objectType = 'route';
224
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
225
        if (!$this->hasPermission('ZikulaRoutesModule:' . ucfirst($objectType) . ':', '::', $permLevel)) {
226
            throw new AccessDeniedException();
227
        }
228
        // create identifier for permission check
229
        $instanceId = $route->createCompositeIdentifier();
230
        if (!$this->hasPermission('ZikulaRoutesModule:' . ucfirst($objectType) . ':', $instanceId . '::', $permLevel)) {
231
            throw new AccessDeniedException();
232
        }
233
        
234
        $templateParameters = [
235
            'routeArea' => $isAdmin ? 'admin' : '',
236
            $objectType => $route
237
        ];
238
239
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
240
        $templateParameters = $controllerHelper->processDisplayActionParameters($objectType, $templateParameters);
241
242
        // fetch and return the appropriate template
243
        $response = $this->get('zikula_routes_module.view_helper')->processTemplate($objectType, 'display', $templateParameters);
244
245
        $format = $request->getRequestFormat();
246
        if ($format == 'ics') {
247
            $fileName = $objectType . '_' . (property_exists($route, 'slug') ? $route['slug'] : $route->getTitleFromDisplayPattern()) . '.ics';
248
            $response->headers->set('Content-Disposition', 'attachment; filename=' . $fileName);
249
        }
250
251
        return $response;
252
    }
253
    /**
254
     * This action provides a handling of edit requests in the admin area.
255
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
256
     *
257
     * @param Request $request Current request instance
258
     *
259
     * @return Response Output
260
     *
261
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
262
     * @throws NotFoundHttpException Thrown by form handler if route to be edited isn't found
263
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
264
     */
265
    public function adminEditAction(Request $request)
266
    {
267
        return $this->editInternal($request, true);
268
    }
269
270
    /**
271
     * This action provides a handling of edit requests.
272
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
273
     *
274
     * @param Request $request Current request instance
275
     *
276
     * @return Response Output
277
     *
278
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
279
     * @throws NotFoundHttpException Thrown by form handler if route to be edited isn't found
280
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
281
     */
282
    public function editAction(Request $request)
283
    {
284
        return $this->editInternal($request, false);
285
    }
286
287
    /**
288
     * This method includes the common implementation code for adminEdit() and edit().
289
     */
290
    protected function editInternal(Request $request, $isAdmin = false)
291
    {
292
        $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...
293
294
        // parameter specifying which type of objects we are treating
295
        $objectType = 'route';
296
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_EDIT;
297
        if (!$this->hasPermission('ZikulaRoutesModule:' . ucfirst($objectType) . ':', '::', $permLevel)) {
298
            throw new AccessDeniedException();
299
        }
300
        $templateParameters = [
301
            'routeArea' => $isAdmin ? 'admin' : ''
302
        ];
303
304
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
305
        $templateParameters = $controllerHelper->processEditActionParameters($objectType, $templateParameters);
306
307
        // delegate form processing to the form handler
308
        $formHandler = $this->get('zikula_routes_module.form.handler.route');
309
        $result = $formHandler->processForm($templateParameters);
310
        if ($result instanceof RedirectResponse) {
1 ignored issue
show
Bug introduced by
The class Symfony\Component\HttpFoundation\RedirectResponse does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
311
            return $result;
312
        }
313
314
        $templateParameters = $formHandler->getTemplateParameters();
315
316
        // fetch and return the appropriate template
317
        return $this->get('zikula_routes_module.view_helper')->processTemplate($objectType, 'edit', $templateParameters);
318
    }
319
    /**
320
     * This action provides a handling of simple delete requests in the admin area.
321
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options = {"id" = "id", "repository_method" = "selectById"})
322
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
323
     *
324
     * @param Request $request Current request instance
325
     * @param RouteEntity $route Treated route instance
326
     *
327
     * @return Response Output
328
     *
329
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
330
     * @throws NotFoundHttpException Thrown by param converter if route to be deleted isn't found
331
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
332
     */
333
    public function adminDeleteAction(Request $request, RouteEntity $route)
334
    {
335
        return $this->deleteInternal($request, $route, true);
336
    }
337
338
    /**
339
     * This action provides a handling of simple delete requests.
340
     * @ParamConverter("route", class="ZikulaRoutesModule:RouteEntity", options = {"id" = "id", "repository_method" = "selectById"})
341
     * @Cache(lastModified="route.getUpdatedDate()", ETag="'Route' ~ route.getid() ~ route.getUpdatedDate().format('U')")
342
     *
343
     * @param Request $request Current request instance
344
     * @param RouteEntity $route Treated route instance
345
     *
346
     * @return Response Output
347
     *
348
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
349
     * @throws NotFoundHttpException Thrown by param converter if route to be deleted isn't found
350
     * @throws RuntimeException      Thrown if another critical error occurs (e.g. workflow actions not available)
351
     */
352
    public function deleteAction(Request $request, RouteEntity $route)
353
    {
354
        return $this->deleteInternal($request, $route, false);
355
    }
356
357
    /**
358
     * This method includes the common implementation code for adminDelete() and delete().
359
     */
360
    protected function deleteInternal(Request $request, RouteEntity $route, $isAdmin = false)
361
    {
362
        $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...
363
364
        // parameter specifying which type of objects we are treating
365
        $objectType = 'route';
366
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_DELETE;
367
        if (!$this->hasPermission('ZikulaRoutesModule:' . ucfirst($objectType) . ':', '::', $permLevel)) {
368
            throw new AccessDeniedException();
369
        }
370
        $logger = $this->get('logger');
371
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $this->get('zikula_users_module.current_user')->get('uname'), 'entity' => 'route', 'id' => $route->createCompositeIdentifier()];
372
        
373
        // determine available workflow actions
374
        $workflowHelper = $this->get('zikula_routes_module.workflow_helper');
375
        $actions = $workflowHelper->getActionsForObject($route);
376
        if (false === $actions || !is_array($actions)) {
377
            $this->addFlash('error', $this->__('Error! Could not determine workflow actions.'));
378
            $logger->error('{app}: User {user} tried to delete the {entity} with id {id}, but failed to determine available workflow actions.', $logArgs);
379
            throw new \RuntimeException($this->__('Error! Could not determine workflow actions.'));
380
        }
381
382
        // redirect to the list of routes
383
        $redirectRoute = 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view';
384
385
        // check whether deletion is allowed
386
        $deleteActionId = 'delete';
387
        $deleteAllowed = false;
388
        foreach ($actions as $actionId => $action) {
389
            if ($actionId != $deleteActionId) {
390
                continue;
391
            }
392
            $deleteAllowed = true;
393
            break;
394
        }
395
        if (!$deleteAllowed) {
396
            $this->addFlash('error', $this->__('Error! It is not allowed to delete this route.'));
397
            $logger->error('{app}: User {user} tried to delete the {entity} with id {id}, but this action was not allowed.', $logArgs);
398
399
            return $this->redirectToRoute($redirectRoute);
400
        }
401
402
        $form = $this->createForm(DeletionType::class, $route);
403
404
        if ($form->handleRequest($request)->isValid()) {
405
            if ($form->get('delete')->isClicked()) {
406
                // execute the workflow action
407
                $success = $workflowHelper->executeAction($route, $deleteActionId);
408
                if ($success) {
409
                    $this->addFlash('status', $this->__('Done! Item deleted.'));
410
                    $logger->notice('{app}: User {user} deleted the {entity} with id {id}.', $logArgs);
411
                }
412
413
                return $this->redirectToRoute($redirectRoute);
414
            } elseif ($form->get('cancel')->isClicked()) {
415
                $this->addFlash('status', $this->__('Operation cancelled.'));
416
417
                return $this->redirectToRoute($redirectRoute);
418
            }
419
        }
420
421
        $templateParameters = [
422
            'routeArea' => $isAdmin ? 'admin' : '',
423
            'deleteForm' => $form->createView(),
424
            $objectType => $route
425
        ];
426
427
        $controllerHelper = $this->get('zikula_routes_module.controller_helper');
428
        $templateParameters = $controllerHelper->processDeleteActionParameters($objectType, $templateParameters);
429
430
        // fetch and return the appropriate template
431
        return $this->get('zikula_routes_module.view_helper')->processTemplate($objectType, 'delete', $templateParameters);
432
    }
433
434
    /**
435
     * Process status changes for multiple items.
436
     *
437
     * This function processes the items selected in the admin view page.
438
     * Multiple items may have their state changed or be deleted.
439
     *
440
     * @param Request $request Current request instance
441
     *
442
     * @return RedirectResponse
443
     *
444
     * @throws RuntimeException Thrown if executing the workflow action fails
445
     */
446
    public function adminHandleSelectedEntriesAction(Request $request)
447
    {
448
        return $this->handleSelectedEntriesActionInternal($request, true);
449
    }
450
451
    /**
452
     * Process status changes for multiple items.
453
     *
454
     * This function processes the items selected in the admin view page.
455
     * Multiple items may have their state changed or be deleted.
456
     *
457
     * @param Request $request Current request instance
458
     *
459
     * @return RedirectResponse
460
     *
461
     * @throws RuntimeException Thrown if executing the workflow action fails
462
     */
463
    public function handleSelectedEntriesAction(Request $request)
464
    {
465
        return $this->handleSelectedEntriesActionInternal($request, false);
466
    }
467
468
    /**
469
     * This method includes the common implementation code for adminHandleSelectedEntriesAction() and handleSelectedEntriesAction().
470
     *
471
     * @param Request $request Current request instance
472
     * @param Boolean $isAdmin Whether the admin area is used or not
473
     */
474
    protected function handleSelectedEntriesActionInternal(Request $request, $isAdmin = false)
475
    {
476
        $objectType = 'route';
477
478
        // Get parameters
479
        $action = $request->request->get('action', null);
480
        $items = $request->request->get('items', null);
481
482
        $action = strtolower($action);
483
484
        $selectionHelper = $this->get('zikula_routes_module.selection_helper');
485
        $workflowHelper = $this->get('zikula_routes_module.workflow_helper');
486
        $logger = $this->get('logger');
487
        $userName = $this->get('zikula_users_module.current_user')->get('uname');
488
489
        // process each item
490
        foreach ($items as $itemid) {
491
            // check if item exists, and get record instance
492
            $entity = $selectionHelper->getEntity($objectType, $itemid, false);
493
            if (null === $entity) {
494
                continue;
495
            }
496
        
497
            // check if $action can be applied to this entity (may depend on it's current workflow state)
498
            $allowedActions = $workflowHelper->getActionsForObject($entity);
499
            $actionIds = array_keys($allowedActions);
500
            if (!in_array($action, $actionIds)) {
501
                // action not allowed, skip this object
502
                continue;
503
            }
504
505
            $success = false;
506
            try {
507
                // execute the workflow action
508
                $success = $workflowHelper->executeAction($entity, $action);
509
            } catch(\Exception $e) {
510
                $this->addFlash('error', $this->__f('Sorry, but an error occured during the %action% action.', ['%action%' => $action]) . '  ' . $e->getMessage());
511
                $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()]);
512
            }
513
514
            if (!$success) {
515
                continue;
516
            }
517
518
            if ($action == 'delete') {
519
                $this->addFlash('status', $this->__('Done! Item deleted.'));
520
                $logger->notice('{app}: User {user} deleted the {entity} with id {id}.', ['app' => 'ZikulaRoutesModule', 'user' => $userName, 'entity' => 'route', 'id' => $itemid]);
521
            } else {
522
                $this->addFlash('status', $this->__('Done! Item updated.'));
523
                $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]);
524
            }
525
        }
526
527
        return $this->redirectToRoute('zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'index');
528
    }
529
}
530