Completed
Push — master ( 155c91...41d5fe )
by Axel
05:02
created

handleSelectedEntriesActionInternal()   C

Complexity

Conditions 11
Paths 10

Size

Total Lines 101
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 59
nc 10
nop 6
dl 0
loc 101
rs 6.7478
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Routes.
5
 *
6
 * @copyright Zikula contributors (Zikula)
7
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
8
 * @author Zikula contributors <[email protected]>.
9
 *
10
 * @see https://ziku.la
11
 *
12
 * @version Generated by ModuleStudio 1.5.0 (https://modulestudio.de).
13
 */
14
15
declare(strict_types=1);
16
17
namespace Zikula\RoutesModule\Controller\Base;
18
19
use Exception;
20
use Psr\Log\LoggerInterface;
21
use RuntimeException;
22
use Symfony\Component\HttpFoundation\RedirectResponse;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\Response;
25
use Symfony\Component\Routing\RouterInterface;
26
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
27
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
28
use Zikula\Bundle\CoreBundle\Controller\AbstractController;
29
use Zikula\Component\SortableColumns\Column;
30
use Zikula\Component\SortableColumns\SortableColumns;
31
use Zikula\UsersModule\Api\ApiInterface\CurrentUserApiInterface;
32
use Zikula\RoutesModule\Entity\RouteEntity;
33
use Zikula\RoutesModule\Entity\Factory\EntityFactory;
34
use Zikula\RoutesModule\Form\Handler\Route\EditHandler;
35
use Zikula\RoutesModule\Helper\ControllerHelper;
36
use Zikula\RoutesModule\Helper\PermissionHelper;
37
use Zikula\RoutesModule\Helper\ViewHelper;
38
use Zikula\RoutesModule\Helper\WorkflowHelper;
39
40
/**
41
 * Route controller base class.
42
 */
43
abstract class AbstractRouteController extends AbstractController
44
{
45
    /**
46
     * This is the default action handling the main area called without defining arguments.
47
     *
48
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
49
     */
50
    protected function indexInternal(
51
        Request $request,
52
        PermissionHelper $permissionHelper,
53
        bool $isAdmin = false
54
    ): Response {
55
        $objectType = 'route';
56
        // permission check
57
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
58
        if (!$permissionHelper->hasComponentPermission($objectType, $permLevel)) {
59
            throw new AccessDeniedException();
60
        }
61
        
62
        $templateParameters = [
63
            'routeArea' => $isAdmin ? 'admin' : '',
64
        ];
65
        
66
        return $this->redirectToRoute('zikularoutesmodule_route_' . $templateParameters['routeArea'] . 'view');
67
    }
68
69
    /**
70
     * This action provides an item list overview.
71
     *
72
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
73
     * @throws Exception
74
     */
75
    protected function viewInternal(
76
        Request $request,
77
        RouterInterface $router,
78
        PermissionHelper $permissionHelper,
79
        ControllerHelper $controllerHelper,
80
        ViewHelper $viewHelper,
81
        string $sort,
82
        string $sortdir,
83
        int $page,
84
        int $num,
85
        bool $isAdmin = false
86
    ): Response {
87
        $objectType = 'route';
88
        // permission check
89
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
90
        if (!$permissionHelper->hasComponentPermission($objectType, $permLevel)) {
91
            throw new AccessDeniedException();
92
        }
93
        
94
        $templateParameters = [
95
            'routeArea' => $isAdmin ? 'admin' : '',
96
        ];
97
        
98
        $request->query->set('sort', $sort);
99
        $request->query->set('sortdir', $sortdir);
100
        $request->query->set('page', $page);
101
        
102
        $routeName = 'zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'view';
103
        $sortableColumns = new SortableColumns($router, $routeName, 'sort', 'sortdir');
104
        
105
        $sortableColumns->addColumns([
106
            new Column('bundle'),
107
            new Column('controller'),
108
            new Column('action'),
109
            new Column('path'),
110
            new Column('host'),
111
            new Column('schemes'),
112
            new Column('methods'),
113
            new Column('prependBundlePrefix'),
114
            new Column('translatable'),
115
            new Column('translationPrefix'),
116
            new Column('condition'),
117
            new Column('description'),
118
            new Column('sort'),
119
            new Column('createdBy'),
120
            new Column('createdDate'),
121
            new Column('updatedBy'),
122
            new Column('updatedDate'),
123
        ]);
124
        
125
        $templateParameters = $controllerHelper->processViewActionParameters(
126
            $objectType,
127
            $sortableColumns,
128
            $templateParameters
129
        );
130
        
131
        // filter by permissions
132
        $templateParameters['items'] = $permissionHelper->filterCollection(
133
            $templateParameters['items'],
134
            $permLevel
135
        );
136
        
137
        // fetch and return the appropriate template
138
        return $viewHelper->processTemplate($objectType, 'view', $templateParameters);
139
    }
140
141
    /**
142
     * This action provides a item detail view.
143
     *
144
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
145
     * @throws NotFoundHttpException Thrown if route to be displayed isn't found
146
     */
147
    protected function displayInternal(
148
        Request $request,
149
        PermissionHelper $permissionHelper,
150
        ControllerHelper $controllerHelper,
151
        ViewHelper $viewHelper,
152
        EntityFactory $entityFactory,
153
        ?RouteEntity $route = null,
154
        int $id = 0,
155
        bool $isAdmin = false
156
    ): Response {
157
        if (null === $route) {
158
            $route = $entityFactory->getRepository('route')->selectById($id);
159
        }
160
        if (null === $route) {
0 ignored issues
show
introduced by
The condition null === $route is always false.
Loading history...
161
            throw new NotFoundHttpException(
162
                'No such route found.'
163
            );
164
        }
165
        
166
        $objectType = 'route';
167
        // permission check
168
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
169
        if (!$permissionHelper->hasEntityPermission($route, $permLevel)) {
0 ignored issues
show
Bug introduced by
It seems like $route can also be of type array; however, parameter $entity of Zikula\RoutesModule\Help...::hasEntityPermission() does only seem to accept Zikula\Bundle\CoreBundle\Doctrine\EntityAccess, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

169
        if (!$permissionHelper->hasEntityPermission(/** @scrutinizer ignore-type */ $route, $permLevel)) {
Loading history...
170
            throw new AccessDeniedException();
171
        }
172
        
173
        $templateParameters = [
174
            'routeArea' => $isAdmin ? 'admin' : '',
175
            $objectType => $route,
176
        ];
177
        
178
        $templateParameters = $controllerHelper->processDisplayActionParameters(
179
            $objectType,
180
            $templateParameters
181
        );
182
        
183
        // fetch and return the appropriate template
184
        $response = $viewHelper->processTemplate($objectType, 'display', $templateParameters);
185
        
186
        return $response;
187
    }
188
189
    /**
190
     * This action provides a handling of edit requests.
191
     *
192
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
193
     * @throws RuntimeException Thrown if another critical error occurs (e.g. workflow actions not available)
194
     * @throws Exception
195
     */
196
    protected function editInternal(
197
        Request $request,
198
        PermissionHelper $permissionHelper,
199
        ControllerHelper $controllerHelper,
200
        ViewHelper $viewHelper,
201
        EditHandler $formHandler,
202
        bool $isAdmin = false
203
    ): Response {
204
        $objectType = 'route';
205
        // permission check
206
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_EDIT;
207
        if (!$permissionHelper->hasComponentPermission($objectType, $permLevel)) {
208
            throw new AccessDeniedException();
209
        }
210
        
211
        $templateParameters = [
212
            'routeArea' => $isAdmin ? 'admin' : '',
213
        ];
214
        
215
        // delegate form processing to the form handler
216
        $result = $formHandler->processForm($templateParameters);
217
        if ($result instanceof RedirectResponse) {
218
            return $result;
219
        }
220
        
221
        $templateParameters = $formHandler->getTemplateParameters();
222
        
223
        $templateParameters = $controllerHelper->processEditActionParameters(
224
            $objectType,
225
            $templateParameters
226
        );
227
        
228
        // fetch and return the appropriate template
229
        return $viewHelper->processTemplate($objectType, 'edit', $templateParameters);
230
    }
231
232
    
233
    
234
    /**
235
     * Process status changes for multiple items.
236
     *
237
     * This function processes the items selected in the admin view page.
238
     * Multiple items may have their state changed or be deleted.
239
     *
240
     * @throws RuntimeException Thrown if executing the workflow action fails
241
     */
242
    protected function handleSelectedEntriesInternal(
243
        Request $request,
244
        LoggerInterface $logger,
245
        EntityFactory $entityFactory,
246
        WorkflowHelper $workflowHelper,
247
        CurrentUserApiInterface $currentUserApi,
248
        bool $isAdmin = false
249
    ): RedirectResponse {
250
        $objectType = 'route';
251
        
252
        // get parameters
253
        $action = $request->request->get('action');
254
        $items = $request->request->get('items');
255
        if (!is_array($items) || !count($items)) {
256
            return $this->redirectToRoute('zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'index');
257
        }
258
        
259
        $action = mb_strtolower($action);
260
        
261
        $repository = $entityFactory->getRepository($objectType);
262
        $userName = $currentUserApi->get('uname');
263
        
264
        // process each item
265
        foreach ($items as $itemId) {
266
            // check if item exists, and get record instance
267
            $entity = $repository->selectById($itemId, false);
268
            if (null === $entity) {
269
                continue;
270
            }
271
        
272
            // check if $action can be applied to this entity (may depend on it's current workflow state)
273
            $allowedActions = $workflowHelper->getActionsForObject($entity);
0 ignored issues
show
Bug introduced by
It seems like $entity can also be of type array; however, parameter $entity of Zikula\RoutesModule\Help...::getActionsForObject() does only seem to accept Zikula\Bundle\CoreBundle\Doctrine\EntityAccess, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

273
            $allowedActions = $workflowHelper->getActionsForObject(/** @scrutinizer ignore-type */ $entity);
Loading history...
274
            $actionIds = array_keys($allowedActions);
275
            if (!in_array($action, $actionIds, true)) {
276
                // action not allowed, skip this object
277
                continue;
278
            }
279
        
280
            $success = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
281
            try {
282
                // execute the workflow action
283
                $success = $workflowHelper->executeAction($entity, $action);
0 ignored issues
show
Bug introduced by
It seems like $entity can also be of type array; however, parameter $entity of Zikula\RoutesModule\Help...Helper::executeAction() does only seem to accept Zikula\Bundle\CoreBundle\Doctrine\EntityAccess, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

283
                $success = $workflowHelper->executeAction(/** @scrutinizer ignore-type */ $entity, $action);
Loading history...
284
            } catch (Exception $exception) {
285
                $this->addFlash(
286
                    'error',
287
                    $this->trans(
288
                        'Sorry, but an error occured during the %action% action.',
289
                        ['%action%' => $action]
290
                    ) . '  ' . $exception->getMessage()
291
                );
292
                $logger->error(
293
                    '{app}: User {user} tried to execute the {action} workflow action for the {entity} with id {id},'
294
                        . ' but failed. Error details: {errorMessage}.',
295
                    [
296
                        'app' => 'ZikulaRoutesModule',
297
                        'user' => $userName,
298
                        'action' => $action,
299
                        'entity' => 'route',
300
                        'id' => $itemId,
301
                        'errorMessage' => $exception->getMessage(),
302
                    ]
303
                );
304
            }
305
        
306
            if (!$success) {
307
                continue;
308
            }
309
        
310
            if ('delete' === $action) {
311
                $this->addFlash(
312
                    'status',
313
                    'Done! Route deleted.'
314
                );
315
                $logger->notice(
316
                    '{app}: User {user} deleted the {entity} with id {id}.',
317
                    [
318
                        'app' => 'ZikulaRoutesModule',
319
                        'user' => $userName,
320
                        'entity' => 'route',
321
                        'id' => $itemId,
322
                    ]
323
                );
324
            } else {
325
                $this->addFlash(
326
                    'status',
327
                    'Done! Route updated.'
328
                );
329
                $logger->notice(
330
                    '{app}: User {user} executed the {action} workflow action for the {entity} with id {id}.',
331
                    [
332
                        'app' => 'ZikulaRoutesModule',
333
                        'user' => $userName,
334
                        'action' => $action,
335
                        'entity' => 'route',
336
                        'id' => $itemId,
337
                    ]
338
                );
339
            }
340
        }
341
        
342
        return $this->redirectToRoute('zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'index');
343
    }
344
}
345