Passed
Push — master ( 8a455a...42a228 )
by Craig
07:01
created

handleSelectedEntriesActionInternal()   C

Complexity

Conditions 11
Paths 10

Size

Total Lines 95
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 56
nc 10
nop 5
dl 0
loc 95
rs 6.8133
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
 * @see https://ziku.la
10
 * @version Generated by ModuleStudio 1.4.0 (https://modulestudio.de).
11
 */
12
13
declare(strict_types=1);
14
15
namespace Zikula\RoutesModule\Controller\Base;
16
17
use Exception;
18
use RuntimeException;
19
use Symfony\Component\HttpFoundation\RedirectResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use Symfony\Component\Routing\RouterInterface;
23
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
24
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
25
use Zikula\Component\SortableColumns\Column;
26
use Zikula\Component\SortableColumns\SortableColumns;
27
use Zikula\Core\Controller\AbstractController;
28
use Zikula\UsersModule\Api\ApiInterface\CurrentUserApiInterface;
29
use Zikula\RoutesModule\Entity\RouteEntity;
30
use Zikula\RoutesModule\Entity\Factory\EntityFactory;
31
use Zikula\RoutesModule\Form\Handler\Route\EditHandler;
32
use Zikula\RoutesModule\Helper\ControllerHelper;
33
use Zikula\RoutesModule\Helper\PermissionHelper;
34
use Zikula\RoutesModule\Helper\ViewHelper;
35
use Zikula\RoutesModule\Helper\WorkflowHelper;
36
37
/**
38
 * Route controller base class.
39
 */
40
abstract class AbstractRouteController extends AbstractController
41
{
42
    
43
    /**
44
     * This is the default action handling the main area called without defining arguments.
45
     *
46
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
47
     */
48
    protected function indexInternal(
49
        Request $request,
50
        PermissionHelper $permissionHelper,
51
        bool $isAdmin = false
52
    ): Response {
53
        $objectType = 'route';
54
        // permission check
55
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_OVERVIEW;
56
        if (!$permissionHelper->hasComponentPermission($objectType, $permLevel)) {
57
            throw new AccessDeniedException();
58
        }
59
        
60
        $templateParameters = [
61
            'routeArea' => $isAdmin ? 'admin' : ''
62
        ];
63
        
64
        return $this->redirectToRoute('zikularoutesmodule_route_' . $templateParameters['routeArea'] . 'view');
65
    }
66
    
67
    
68
    /**
69
     * This action provides an item list overview.
70
     *
71
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
72
     * @throws Exception
73
     */
74
    protected function viewInternal(
75
        Request $request,
76
        PermissionHelper $permissionHelper,
77
        ControllerHelper $controllerHelper,
78
        ViewHelper $viewHelper,
79
        string $sort,
80
        string $sortdir,
81
        int $pos,
82
        int $num,
83
        bool $isAdmin = false
84
    ): Response {
85
        $objectType = 'route';
86
        // permission check
87
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_READ;
88
        if (!$permissionHelper->hasComponentPermission($objectType, $permLevel)) {
89
            throw new AccessDeniedException();
90
        }
91
        
92
        $templateParameters = [
93
            'routeArea' => $isAdmin ? 'admin' : ''
94
        ];
95
        
96
        $request->query->set('sort', $sort);
97
        $request->query->set('sortdir', $sortdir);
98
        $request->query->set('pos', $pos);
99
        
100
        /** @var RouterInterface $router */
101
        $router = $this->get('router');
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
            $objectType,
134
            $templateParameters['items'],
135
            $permLevel
136
        );
137
        
138
        // fetch and return the appropriate template
139
        return $viewHelper->processTemplate($objectType, 'view', $templateParameters);
140
    }
141
    
142
    
143
    /**
144
     * This action provides a item detail view.
145
     *
146
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
147
     * @throws NotFoundHttpException Thrown if route to be displayed isn't found
148
     */
149
    protected function displayInternal(
150
        Request $request,
151
        PermissionHelper $permissionHelper,
152
        ControllerHelper $controllerHelper,
153
        ViewHelper $viewHelper,
154
        EntityFactory $entityFactory,
155
        RouteEntity $route = null,
156
        int $id = 0,
157
        bool $isAdmin = false
158
    ): Response {
159
        if (null === $route) {
160
            $route = $entityFactory->getRepository('route')->selectById($id);
161
        }
162
        if (null === $route) {
0 ignored issues
show
introduced by
The condition null === $route is always false.
Loading history...
163
            throw new NotFoundHttpException($this->__('No such route found.'));
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\Core\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
    /**
191
     * This action provides a handling of edit requests.
192
     *
193
     * @throws AccessDeniedException Thrown if the user doesn't have required permissions
194
     * @throws RuntimeException Thrown if another critical error occurs (e.g. workflow actions not available)
195
     * @throws Exception
196
     */
197
    protected function editInternal(
198
        Request $request,
199
        PermissionHelper $permissionHelper,
200
        ControllerHelper $controllerHelper,
201
        ViewHelper $viewHelper,
202
        EditHandler $formHandler,
203
        bool $isAdmin = false
204
    ): Response {
205
        $objectType = 'route';
206
        // permission check
207
        $permLevel = $isAdmin ? ACCESS_ADMIN : ACCESS_EDIT;
208
        if (!$permissionHelper->hasComponentPermission($objectType, $permLevel)) {
209
            throw new AccessDeniedException();
210
        }
211
        
212
        $templateParameters = [
213
            'routeArea' => $isAdmin ? 'admin' : ''
214
        ];
215
        
216
        $templateParameters = $controllerHelper->processEditActionParameters($objectType, $templateParameters);
217
        
218
        // delegate form processing to the form handler
219
        $result = $formHandler->processForm($templateParameters);
220
        if ($result instanceof RedirectResponse) {
221
            return $result;
222
        }
223
        
224
        $templateParameters = $formHandler->getTemplateParameters();
225
        
226
        // fetch and return the appropriate template
227
        return $viewHelper->processTemplate($objectType, 'edit', $templateParameters);
228
    }
229
    
230
    
231
    /**
232
     * Process status changes for multiple items.
233
     *
234
     * This function processes the items selected in the admin view page.
235
     * Multiple items may have their state changed or be deleted.
236
     *
237
     * @throws RuntimeException Thrown if executing the workflow action fails
238
     */
239
    protected function handleSelectedEntriesActionInternal(
240
        Request $request,
241
        EntityFactory $entityFactory,
242
        WorkflowHelper $workflowHelper,
243
        CurrentUserApiInterface $currentUserApi,
244
        bool $isAdmin = false
245
    ): RedirectResponse {
246
        $objectType = 'route';
247
        
248
        // Get parameters
249
        $action = $request->request->get('action');
250
        $items = $request->request->get('items');
251
        if (!is_array($items) || !count($items)) {
252
            return $this->redirectToRoute('zikularoutesmodule_route_' . ($isAdmin ? 'admin' : '') . 'index');
253
        }
254
        
255
        $action = strtolower($action);
256
        
257
        $repository = $entityFactory->getRepository($objectType);
258
        $logger = $this->get('logger');
259
        $userName = $currentUserApi->get('uname');
260
        
261
        // process each item
262
        foreach ($items as $itemId) {
263
            // check if item exists, and get record instance
264
            $entity = $repository->selectById($itemId, false);
265
            if (null === $entity) {
266
                continue;
267
            }
268
        
269
            // check if $action can be applied to this entity (may depend on it's current workflow state)
270
            $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\Core\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

270
            $allowedActions = $workflowHelper->getActionsForObject(/** @scrutinizer ignore-type */ $entity);
Loading history...
271
            $actionIds = array_keys($allowedActions);
272
            if (!in_array($action, $actionIds, true)) {
273
                // action not allowed, skip this object
274
                continue;
275
            }
276
        
277
            $success = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
278
            try {
279
                // execute the workflow action
280
                $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\Core\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

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