Completed
Push — master ( 693283...8cba26 )
by Craig
06:26
created

processEditActionParameters()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 9
loc 9
rs 9.6666
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.5 (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\ApiInterface\VariableApiInterface;
20
use Zikula\RoutesModule\Entity\Factory\EntityFactory;
21
use Zikula\RoutesModule\Helper\CollectionFilterHelper;
22
use Zikula\RoutesModule\Helper\ModelHelper;
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 VariableApiInterface
41
     */
42
    protected $variableApi;
43
44
    /**
45
     * @var EntityFactory
46
     */
47
    protected $entityFactory;
48
49
    /**
50
     * @var CollectionFilterHelper
51
     */
52
    protected $collectionFilterHelper;
53
54
    /**
55
     * @var ModelHelper
56
     */
57
    protected $modelHelper;
58
59
    /**
60
     * ControllerHelper constructor.
61
     *
62
     * @param RequestStack        $requestStack    RequestStack service instance
63
     * @param FormFactoryInterface $formFactory    FormFactory service instance
64
     * @param VariableApiInterface $variableApi     VariableApi service instance
65
     * @param EntityFactory       $entityFactory   EntityFactory service instance
66
     * @param CollectionFilterHelper $collectionFilterHelper CollectionFilterHelper service instance
67
     * @param ModelHelper         $modelHelper     ModelHelper service instance
68
     */
69
    public function __construct(
70
        RequestStack $requestStack,
71
        FormFactoryInterface $formFactory,
72
        VariableApiInterface $variableApi,
73
        EntityFactory $entityFactory,
74
        CollectionFilterHelper $collectionFilterHelper,
75
        ModelHelper $modelHelper
76
    ) {
77
        $this->request = $requestStack->getCurrentRequest();
78
        $this->formFactory = $formFactory;
79
        $this->variableApi = $variableApi;
80
        $this->entityFactory = $entityFactory;
81
        $this->collectionFilterHelper = $collectionFilterHelper;
82
        $this->modelHelper = $modelHelper;
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
    public function getObjectTypes($context = '', array $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...
94
    {
95 View Code Duplication
        if (!in_array($context, ['controllerAction', 'api', 'helper', 'actionHandler', 'block', 'contentType', 'util'])) {
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...
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
    public function getDefaultObjectType($context = '', array $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...
114
    {
115 View Code Duplication
        if (!in_array($context, ['controllerAction', 'api', 'helper', 'actionHandler', 'block', 'contentType', 'util'])) {
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...
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
        return 'route';
120
    }
121
122
    /**
123
     * Processes the parameters for a view action.
124
     * This includes handling pagination, quick navigation forms and other aspects.
125
     *
126
     * @param string          $objectType         Name of treated entity type
127
     * @param SortableColumns $sortableColumns    Used SortableColumns instance
128
     * @param array           $templateParameters Template data
129
     *
130
     * @return array Enriched template parameters used for creating the response
131
     */
132
    public function processViewActionParameters($objectType, SortableColumns $sortableColumns, array $templateParameters = [])
133
    {
134
        $contextArgs = ['controller' => $objectType, 'action' => 'view'];
135
        if (!in_array($objectType, $this->getObjectTypes('controllerAction', $contextArgs))) {
136
            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...
137
        }
138
    
139
        $request = $this->request;
140
        $repository = $this->entityFactory->getRepository($objectType);
141
    
142
        // parameter for used sorting field
143
        $sort = $request->query->get('sort', '');
144
        if (empty($sort) || !in_array($sort, $repository->getAllowedSortingFields())) {
145
            $sort = $repository->getDefaultSortingField();
146
            $request->query->set('sort', $sort);
147
            // set default sorting in route parameters (e.g. for the pager)
148
            $routeParams = $request->attributes->get('_route_params');
149
            $routeParams['sort'] = $sort;
150
            $request->attributes->set('_route_params', $routeParams);
151
        }
152
        $sortdir = $request->query->get('sortdir', 'ASC');
153
        $sortableColumns->setOrderBy($sortableColumns->getColumn($sort), strtoupper($sortdir));
154
    
155
        $templateParameters['all'] = 'csv' == $request->getRequestFormat() ? 1 : $request->query->getInt('all', 0);
156
        $templateParameters['own'] = $request->query->getInt('own', $this->variableApi->get('ZikulaRoutesModule', 'showOnlyOwnEntries', 0));
157
    
158
        $resultsPerPage = 0;
159
        if ($templateParameters['all'] != 1) {
160
            // the number of items displayed on a page for pagination
161
            $resultsPerPage = $request->query->getInt('num', 0);
162
            if (in_array($resultsPerPage, [0, 10])) {
163
                $resultsPerPage = $this->variableApi->get('ZikulaRoutesModule', $objectType . 'EntriesPerPage', 10);
164
            }
165
        }
166
        $templateParameters['num'] = $resultsPerPage;
167
        $templateParameters['tpl'] = $request->query->getAlnum('tpl', '');
168
    
169
        $templateParameters = $this->addTemplateParameters($objectType, $templateParameters, 'controllerAction', $contextArgs);
170
    
171
        $quickNavForm = $this->formFactory->create('Zikula\RoutesModule\Form\Type\QuickNavigation\\' . ucfirst($objectType) . 'QuickNavType', $templateParameters);
172
        if ($quickNavForm->handleRequest($request) && $quickNavForm->isSubmitted()) {
173
            $quickNavData = $quickNavForm->getData();
174
            foreach ($quickNavData as $fieldName => $fieldValue) {
175
                if ($fieldName == 'routeArea') {
176
                    continue;
177
                }
178
                if (in_array($fieldName, ['all', 'own', 'num'])) {
179
                    $templateParameters[$fieldName] = $fieldValue;
180
                } else {
181
                    // set filter as query argument, fetched inside repository
182
                    $request->query->set($fieldName, $fieldValue);
183
                }
184
            }
185
        }
186
    
187
        $urlParameters = $templateParameters;
188
        foreach ($urlParameters as $parameterName => $parameterValue) {
189
            if (false !== stripos($parameterName, 'thumbRuntimeOptions')) {
190
                unset($urlParameters[$parameterName]);
191
            }
192
        }
193
    
194
        $sort = $sortableColumns->getSortColumn()->getName();
195
        $sortdir = $sortableColumns->getSortDirection();
196
        $sortableColumns->setAdditionalUrlParameters($urlParameters);
197
    
198
        $where = '';
199
        if ($templateParameters['all'] == 1) {
200
            // retrieve item list without pagination
201
            $entities = $repository->selectWhere($where, $sort . ' ' . $sortdir);
202
        } else {
203
            // the current offset which is used to calculate the pagination
204
            $currentPage = $request->query->getInt('pos', 1);
205
    
206
            // retrieve item list with pagination
207
            list($entities, $objectCount) = $repository->selectWherePaginated($where, $sort . ' ' . $sortdir, $currentPage, $resultsPerPage);
208
    
209
            $templateParameters['currentPage'] = $currentPage;
210
            $templateParameters['pager'] = [
211
                'amountOfItems' => $objectCount,
212
                'itemsPerPage' => $resultsPerPage
213
            ];
214
        }
215
    
216
        $templateParameters['sort'] = $sort;
217
        $templateParameters['sortdir'] = $sortdir;
218
        $templateParameters['items'] = $entities;
219
    
220
    
221
        $templateParameters['sort'] = $sortableColumns->generateSortableColumns();
222
        $templateParameters['quickNavForm'] = $quickNavForm->createView();
223
    
224
        $templateParameters['canBeCreated'] = $this->modelHelper->canBeCreated($objectType);
225
    
226
        return $templateParameters;
227
    }
228
229
    /**
230
     * Processes the parameters for a display action.
231
     *
232
     * @param string  $objectType         Name of treated entity type
233
     * @param array   $templateParameters Template data
234
     *
235
     * @return array Enriched template parameters used for creating the response
236
     */
237 View Code Duplication
    public function processDisplayActionParameters($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...
238
    {
239
        $contextArgs = ['controller' => $objectType, 'action' => 'display'];
240
        if (!in_array($objectType, $this->getObjectTypes('controllerAction', $contextArgs))) {
241
            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...
242
        }
243
    
244
        return $this->addTemplateParameters($objectType, $templateParameters, 'controllerAction', $contextArgs);
245
    }
246
247
    /**
248
     * Processes the parameters for an edit action.
249
     *
250
     * @param string  $objectType         Name of treated entity type
251
     * @param array   $templateParameters Template data
252
     *
253
     * @return array Enriched template parameters used for creating the response
254
     */
255 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...
256
    {
257
        $contextArgs = ['controller' => $objectType, 'action' => 'edit'];
258
        if (!in_array($objectType, $this->getObjectTypes('controllerAction', $contextArgs))) {
259
            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...
260
        }
261
    
262
        return $this->addTemplateParameters($objectType, $templateParameters, 'controllerAction', $contextArgs);
263
    }
264
265
    /**
266
     * Processes the parameters for a delete action.
267
     *
268
     * @param string  $objectType         Name of treated entity type
269
     * @param array   $templateParameters Template data
270
     *
271
     * @return array Enriched template parameters used for creating the response
272
     */
273 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...
274
    {
275
        $contextArgs = ['controller' => $objectType, 'action' => 'delete'];
276
        if (!in_array($objectType, $this->getObjectTypes('controllerAction', $contextArgs))) {
277
            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...
278
        }
279
    
280
        return $this->addTemplateParameters($objectType, $templateParameters, 'controllerAction', $contextArgs);
281
    }
282
283
    /**
284
     * Returns an array of additional template variables which are specific to the object type treated by this repository.
285
     *
286
     * @param string $objectType Name of treated entity type
287
     * @param array  $parameters Given parameters to enrich
288
     * @param string $context    Usage context (allowed values: controllerAction, api, actionHandler, block, contentType)
289
     * @param array  $args       Additional arguments
290
     *
291
     * @return array List of template variables to be assigned
292
     */
293
    public function addTemplateParameters($objectType = '', array $parameters = [], $context = '', array $args = [])
294
    {
295 View Code Duplication
        if (!in_array($context, ['controllerAction', 'api', 'actionHandler', 'block', 'contentType', 'mailz'])) {
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...
296
            $context = 'controllerAction';
297
        }
298
    
299
        if ($context == 'controllerAction') {
300
            if (!isset($args['action'])) {
301
                $routeName = $this->request->get('_route');
302
                $routeNameParts = explode('_', $routeName);
303
                $args['action'] = end($routeNameParts);
304
            }
305
            if (in_array($args['action'], ['index', 'view'])) {
306
                $parameters = array_merge($parameters, $this->collectionFilterHelper->getViewQuickNavParameters($objectType, $context, $args));
307
            }
308
        }
309
    
310
        return $parameters;
311
    }
312
}
313