Completed
Push — master ( 2fb092...058edd )
by Craig
06:38
created

processViewActionParameters()   D

Complexity

Conditions 16
Paths 73

Size

Total Lines 114
Code Lines 74

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
eloc 74
nc 73
nop 3
dl 0
loc 114
rs 4.8736
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
 * 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.1 (http://modulestudio.de).
11
 */
12
13
namespace Zikula\RoutesModule\Helper\Base;
14
15
use Symfony\Component\Form\FormFactoryInterface;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\RequestStack;
18
use Zikula\Component\SortableColumns\SortableColumns;
19
use Zikula\ExtensionsModule\Api\VariableApi;
20
use Zikula\RoutesModule\Entity\Factory\RoutesFactory;
21
use Zikula\RoutesModule\Helper\ModelHelper;
22
use Zikula\RoutesModule\Helper\SelectionHelper;
23
24
/**
25
 * Helper base class for controller layer methods.
26
 */
27
abstract class AbstractControllerHelper
28
{
29
    /**
30
     * @var Request
31
     */
32
    protected $request;
33
34
    /**
35
     * @var FormFactoryInterface
36
     */
37
    protected $formFactory;
38
39
    /**
40
     * @var VariableApi
41
     */
42
    protected $variableApi;
43
44
    /**
45
     * @var RoutesFactory
46
     */
47
    protected $entityFactory;
48
49
    /**
50
     * @var ModelHelper
51
     */
52
    protected $modelHelper;
53
54
    /**
55
     * @var SelectionHelper
56
     */
57
    protected $selectionHelper;
58
59
    /**
60
     * ControllerHelper constructor.
61
     *
62
     * @param RequestStack        $requestStack    RequestStack service instance
63
     * @param FormFactoryInterface $formFactory    FormFactory service instance
64
     * @param VariableApi         $variableApi     VariableApi service instance
65
     * @param RoutesFactory $entityFactory RoutesFactory service instance
66
     * @param ModelHelper         $modelHelper     ModelHelper service instance
67
     * @param SelectionHelper     $selectionHelper SelectionHelper service instance
68
     */
69
    public function __construct(
70
        RequestStack $requestStack,
71
        FormFactoryInterface $formFactory,
72
        VariableApi $variableApi,
73
        RoutesFactory $entityFactory,
74
        ModelHelper $modelHelper,
75
        SelectionHelper $selectionHelper)
76
    {
77
        $this->request = $requestStack->getCurrentRequest();
78
        $this->formFactory = $formFactory;
79
        $this->variableApi = $variableApi;
80
        $this->entityFactory = $entityFactory;
81
        $this->modelHelper = $modelHelper;
82
        $this->selectionHelper = $selectionHelper;
83
    }
84
85
    /**
86
     * Returns an array of all allowed object types in ZikulaRoutesModule.
87
     *
88
     * @param string $context Usage context (allowed values: controllerAction, api, helper, actionHandler, block, contentType, util)
89
     * @param array  $args    Additional arguments
90
     *
91
     * @return array List of allowed object types
92
     */
93 View Code Duplication
    public function getObjectTypes($context = '', $args = [])
0 ignored issues
show
Unused Code introduced by
The parameter $args 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...
94
    {
95
        if (!in_array($context, ['controllerAction', 'api', 'helper', 'actionHandler', 'block', 'contentType', 'util'])) {
96
            $context = 'controllerAction';
0 ignored issues
show
Unused Code introduced by
$context 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...
97
        }
98
    
99
        $allowedObjectTypes = [];
100
        $allowedObjectTypes[] = 'route';
101
    
102
        return $allowedObjectTypes;
103
    }
104
105
    /**
106
     * Returns the default object type in ZikulaRoutesModule.
107
     *
108
     * @param string $context Usage context (allowed values: controllerAction, api, helper, actionHandler, block, contentType, util)
109
     * @param array  $args    Additional arguments
110
     *
111
     * @return string The name of the default object type
112
     */
113 View Code Duplication
    public function getDefaultObjectType($context = '', $args = [])
0 ignored issues
show
Unused Code introduced by
The parameter $args 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...
114
    {
115
        if (!in_array($context, ['controllerAction', 'api', 'helper', 'actionHandler', 'block', 'contentType', 'util'])) {
116
            $context = 'controllerAction';
0 ignored issues
show
Unused Code introduced by
$context 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...
117
        }
118
    
119
        $defaultObjectType = 'route';
120
    
121
        return $defaultObjectType;
122
    }
123
124
    /**
125
     * Retrieve identifier parameters for a given object type.
126
     *
127
     * @param Request $request    The current request
128
     * @param array   $args       List of arguments used as fallback if request does not contain a field
129
     * @param string  $objectType Name of treated entity type
130
     * @param array   $idFields   List of identifier field names
131
     *
132
     * @return array List of fetched identifiers
133
     */
134
    public function retrieveIdentifier(Request $request, array $args, $objectType = '', array $idFields)
135
    {
136
        $idValues = [];
137
        $routeParams = $request->get('_route_params', []);
138
        foreach ($idFields as $idField) {
139
            $defaultValue = isset($args[$idField]) && is_numeric($args[$idField]) ? $args[$idField] : 0;
140
            if ($this->selectionHelper->hasCompositeKeys($objectType)) {
141
                // composite key may be alphanumeric
142 View Code Duplication
                if (array_key_exists($idField, $routeParams)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
143
                    $id = !empty($routeParams[$idField]) ? $routeParams[$idField] : $defaultValue;
144
                } elseif ($request->query->has($idField)) {
145
                    $id = $request->query->getAlnum($idField, $defaultValue);
146
                } else {
147
                    $id = $defaultValue;
148
                }
149 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
150
                // single identifier
151
                if (array_key_exists($idField, $routeParams)) {
152
                    $id = (int) !empty($routeParams[$idField]) ? $routeParams[$idField] : $defaultValue;
153
                } elseif ($request->query->has($idField)) {
154
                    $id = $request->query->getInt($idField, $defaultValue);
155
                } else {
156
                    $id = $defaultValue;
157
                }
158
            }
159
    
160
            // fallback if id has not been found yet
161
            if (!$id && $idField != 'id' && count($idFields) == 1) {
162
                $defaultValue = isset($args['id']) && is_numeric($args['id']) ? $args['id'] : 0;
163
                if (array_key_exists('id', $routeParams)) {
164
                    $id = (int) !empty($routeParams['id']) ? $routeParams['id'] : $defaultValue;
165
                } elseif ($request->query->has('id')) {
166
                    $id = (int) $request->query->getInt('id', $defaultValue);
167
                } else {
168
                    $id = $defaultValue;
169
                }
170
            }
171
            $idValues[$idField] = $id;
172
        }
173
    
174
        return $idValues;
175
    }
176
177
    /**
178
     * Checks if all identifiers are set properly.
179
     *
180
     * @param array  $idValues List of identifier field values
181
     *
182
     * @return boolean Whether all identifiers are set or not
183
     */
184
    public function isValidIdentifier(array $idValues)
185
    {
186
        if (!count($idValues)) {
187
            return false;
188
        }
189
    
190
        foreach ($idValues as $idField => $idValue) {
191
            if (!$idValue) {
192
                return false;
193
            }
194
        }
195
    
196
        return true;
197
    }
198
199
    /**
200
     * Create nice permalinks.
201
     *
202
     * @param string $name The given object title
203
     *
204
     * @return string processed permalink
205
     * @deprecated made obsolete by Doctrine extensions
206
     */
207
    public function formatPermalink($name)
208
    {
209
        $name = str_replace(
210
            ['ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü', 'ß', '.', '?', '"', '/', ':', 'é', 'è', 'â'],
211
            ['ae', 'oe', 'ue', 'Ae', 'Oe', 'Ue', 'ss', '', '', '', '-', '-', 'e', 'e', 'a'],
212
            $name
213
        );
214
        $name = preg_replace("#(\s*\/\s*|\s*\+\s*|\s+)#", '-', strtolower($name));
215
    
216
        return $name;
217
    }
218
219
    /**
220
     * Processes the parameters for a view action.
221
     * This includes handling pagination, quick navigation forms and other aspects.
222
     *
223
     * @param string          $objectType         Name of treated entity type
224
     * @param SortableColumns $sortableColumns    Used SortableColumns instance
225
     * @param array           $templateParameters Template data
226
     *
227
     * @return array Enriched template parameters used for creating the response
228
     */
229
    public function processViewActionParameters($objectType, SortableColumns $sortableColumns, array $templateParameters = [])
230
    {
231
        $contextArgs = ['controller' => $objectType, 'action' => 'view'];
232
        if (!in_array($objectType, $this->getObjectTypes('controllerAction', $contextArgs))) {
233
            throw new Exception($this->__('Error! Invalid object type received.'));
0 ignored issues
show
Bug introduced by
The method __() does not seem to exist on object<Zikula\RoutesModu...stractControllerHelper>.

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...
234
        }
235
    
236
        $request = $this->request;
237
        $repository = $this->entityFactory->getRepository($objectType);
238
        $repository->setRequest($request);
239
    
240
        // parameter for used sorting field
241
        if (empty($sort) || !in_array($sort, $repository->getAllowedSortingFields())) {
0 ignored issues
show
Bug introduced by
The variable $sort seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
242
            $sort = $repository->getDefaultSortingField();
243
            $request->query->set('sort', $sort);
244
            // set default sorting in route parameters (e.g. for the pager)
245
            $routeParams = $request->attributes->get('_route_params');
246
            $routeParams['sort'] = $sort;
247
            $request->attributes->set('_route_params', $routeParams);
248
        }
249
    
250
    
251
        $showOwnEntries = $request->query->getInt('own', $this->variableApi->get('ZikulaRoutesModule', 'showOnlyOwnEntries', 0));
252
        $showAllEntries = $request->query->getInt('all', 0);
253
    
254
    
255
        $resultsPerPage = 0;
256
        if ($showAllEntries != 1) {
257
            // the number of items displayed on a page for pagination
258
            $resultsPerPage = $request->query->getInt('num', 0);
259
            if (in_array($resultsPerPage, [0, 10])) {
260
                $resultsPerPage = $this->variableApi->get('ZikulaRoutesModule', $objectType . 'EntriesPerPage', 10);
261
            }
262
        }
263
    
264
        $additionalParameters = $repository->getAdditionalTemplateParameters('controllerAction', $contextArgs);
265
    
266
        $additionalUrlParameters = [
267
            'all' => $showAllEntries,
268
            'own' => $showOwnEntries,
269
            'num' => $resultsPerPage
270
        ];
271
        foreach ($additionalParameters as $parameterName => $parameterValue) {
272
            if (false !== stripos($parameterName, 'thumbRuntimeOptions')) {
273
                continue;
274
            }
275
            $additionalUrlParameters[$parameterName] = $parameterValue;
276
        }
277
    
278
        $templateParameters['own'] = $showAllEntries;
279
        $templateParameters['all'] = $showOwnEntries;
280
        $templateParameters['num'] = $resultsPerPage;
281
        $templateParameters['tpl'] = $request->query->getAlnum('tpl', '');
282
    
283
        $quickNavForm = $this->formFactory->create('Zikula\RoutesModule\Form\Type\QuickNavigation\\' . ucfirst($objectType) . 'QuickNavType', $templateParameters);
284
        if ($quickNavForm->handleRequest($request) && $quickNavForm->isSubmitted()) {
285
            $quickNavData = $quickNavForm->getData();
286
            foreach ($quickNavData as $fieldName => $fieldValue) {
287
                if ($fieldName == 'routeArea') {
288
                    continue;
289
                }
290
                if ($fieldName == 'all') {
291
                    $showAllEntries = $additionalUrlParameters['all'] = $templateParameters['all'] = $fieldValue;
292
                } elseif ($fieldName == 'own') {
293
                    $showOwnEntries = $additionalUrlParameters['own'] = $templateParameters['own'] = $fieldValue;
0 ignored issues
show
Unused Code introduced by
$showOwnEntries is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
294
                } elseif ($fieldName == 'num') {
295
                    $resultsPerPage = $additionalUrlParameters['num'] = $fieldValue;
296
                } else {
297
                    // set filter as query argument, fetched inside repository
298
                    $request->query->set($fieldName, $fieldValue);
299
                }
300
            }
301
        }
302
        $sort = $request->query->get('sort');
303
        $sortdir = $request->query->get('sortdir');
304
        $sortableColumns->setOrderBy($sortableColumns->getColumn($sort), strtoupper($sortdir));
305
        $sortableColumns->setAdditionalUrlParameters($additionalUrlParameters);
306
        $templateParameters['sort'] = $sort;
307
        $templateParameters['sortdir'] = $sortdir;
308
    
309
        $where = '';
310
        if ($showAllEntries == 1) {
311
            // retrieve item list without pagination
312
            $entities = $this->selectionHelper->getEntities($objectType, [], $where, $sort . ' ' . $sortdir);
313
        } else {
314
            // the current offset which is used to calculate the pagination
315
            $currentPage = $request->query->getInt('pos', 1);
316
    
317
            // retrieve item list with pagination
318
            list($entities, $objectCount) = $this->selectionHelper->getEntitiesPaginated($objectType, $where, $sort . ' ' . $sortdir, $currentPage, $resultsPerPage);
319
    
320
            $templateParameters['currentPage'] = $currentPage;
321
            $templateParameters['pager'] = [
322
                'amountOfItems' => $objectCount,
323
                'itemsPerPage' => $resultsPerPage
324
            ];
325
        }
326
    
327
        $templateParameters['items'] = $entities;
328
        $templateParameters['sort'] = $sort;
329
        $templateParameters['sortdir'] = $sortdir;
330
        $templateParameters['num'] = $resultsPerPage;
331
        $templateParameters = array_merge($templateParameters, $additionalParameters);
332
    
333
        $templateParameters['sort'] = $sortableColumns->generateSortableColumns();
334
        $templateParameters['quickNavForm'] = $quickNavForm->createView();
335
    
336
        $templateParameters['showAllEntries'] = $templateParameters['all'];
337
        $templateParameters['showOwnEntries'] = $templateParameters['own'];
338
    
339
        $templateParameters['canBeCreated'] = $this->modelHelper->canBeCreated($objectType);
340
    
341
        return $templateParameters;
342
    }
343
344
    /**
345
     * Processes the parameters for a display action.
346
     *
347
     * @param string  $objectType         Name of treated entity type
348
     * @param array   $templateParameters Template data
349
     *
350
     * @return array Enriched template parameters used for creating the response
351
     */
352
    public function processDisplayActionParameters($objectType, array $templateParameters = [])
353
    {
354
        $contextArgs = ['controller' => $objectType, 'action' => 'display'];
355
        if (!in_array($objectType, $this->getObjectTypes('controllerAction', $contextArgs))) {
356
            throw new Exception($this->__('Error! Invalid object type received.'));
0 ignored issues
show
Bug introduced by
The method __() does not seem to exist on object<Zikula\RoutesModu...stractControllerHelper>.

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...
357
        }
358
    
359
        $repository = $this->entityFactory->getRepository($objectType);
360
        $repository->setRequest($this->request);
361
        $entity = $templateParameters[$objectType];
0 ignored issues
show
Unused Code introduced by
$entity 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...
362
    
363
        $additionalParameters = $repository->getAdditionalTemplateParameters('controllerAction', $contextArgs);
364
        $templateParameters = array_merge($templateParameters, $additionalParameters);
365
    
366
        return $templateParameters;
367
    }
368
369
    /**
370
     * Processes the parameters for an edit action.
371
     *
372
     * @param string  $objectType         Name of treated entity type
373
     * @param array   $templateParameters Template data
374
     *
375
     * @return array Enriched template parameters used for creating the response
376
     */
377 View Code Duplication
    public function processEditActionParameters($objectType, array $templateParameters = [])
0 ignored issues
show
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...
378
    {
379
        $contextArgs = ['controller' => $objectType, 'action' => 'edit'];
380
        if (!in_array($objectType, $this->getObjectTypes('controllerAction', $contextArgs))) {
381
            throw new Exception($this->__('Error! Invalid object type received.'));
0 ignored issues
show
Bug introduced by
The method __() does not seem to exist on object<Zikula\RoutesModu...stractControllerHelper>.

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...
382
        }
383
    
384
        $repository = $this->entityFactory->getRepository($objectType);
385
        $repository->setRequest($this->request);
386
    
387
        $additionalParameters = $repository->getAdditionalTemplateParameters('controllerAction', $contextArgs);
388
        $templateParameters = array_merge($templateParameters, $additionalParameters);
389
    
390
        return $templateParameters;
391
    }
392
393
    /**
394
     * Processes the parameters for a delete action.
395
     *
396
     * @param string  $objectType         Name of treated entity type
397
     * @param array   $templateParameters Template data
398
     *
399
     * @return array Enriched template parameters used for creating the response
400
     */
401 View Code Duplication
    public function processDeleteActionParameters($objectType, array $templateParameters = [])
0 ignored issues
show
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...
402
    {
403
        $contextArgs = ['controller' => $objectType, 'action' => 'delete'];
404
        if (!in_array($objectType, $this->getObjectTypes('controllerAction', $contextArgs))) {
405
            throw new Exception($this->__('Error! Invalid object type received.'));
0 ignored issues
show
Bug introduced by
The method __() does not seem to exist on object<Zikula\RoutesModu...stractControllerHelper>.

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...
406
        }
407
    
408
        $repository = $this->entityFactory->getRepository($objectType);
409
        $repository->setRequest($this->request);
410
    
411
        $additionalParameters = $repository->getAdditionalTemplateParameters('controllerAction', $contextArgs);
412
        $templateParameters = array_merge($templateParameters, $additionalParameters);
413
    
414
        return $templateParameters;
415
    }
416
}
417