Completed
Push — refonte ( 107432...1242fa )
by Arnaud
12:35 queued 07:47
created

ActionConfiguration::getAdminConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace LAG\AdminBundle\Configuration;
4
5
use Closure;
6
use JK\Configuration\Configuration;
7
use LAG\AdminBundle\Admin\Action;
8
use LAG\AdminBundle\Controller\AdminAction;
9
use LAG\AdminBundle\Exception\Exception;
10
use LAG\AdminBundle\LAGAdminBundle;
11
use LAG\AdminBundle\Routing\RoutingLoader;
12
use Symfony\Component\DependencyInjection\Container;
13
use Symfony\Component\OptionsResolver\Options;
14
use Symfony\Component\OptionsResolver\OptionsResolver;
15
16
class ActionConfiguration extends Configuration
17
{
18
     /**
19
     * Related Action name.
20
     *
21
     * @var string
22
     */
23
    private $actionName;
24
25
    /**
26
     * @var AdminConfiguration
27
     */
28
    private $adminConfiguration;
29
30
    /**
31
     * @var string
32
     */
33
    private $adminName;
34
35
    /**
36
     * ActionConfiguration constructor.
37
     *
38
     * @param string             $actionName
39
     * @param                    $adminName
40
     * @param AdminConfiguration $adminConfiguration
41
     */
42
    public function __construct($actionName, $adminName, AdminConfiguration $adminConfiguration)
43
    {
44
        parent::__construct();
45
46
        $this->actionName = $actionName;
47
        $this->adminConfiguration = $adminConfiguration;
48
        $this->adminName = $adminName;
49
    }
50
51
    /**
52
     * Define allowed parameters and values for this configuration, using optionsResolver component.
53
     *
54
     * @param OptionsResolver $resolver
55
     */
56
    public function configureOptions(OptionsResolver $resolver)
57
    {
58
        $resolver
59
            ->setDefaults([
60
                'title' => 'AdminBundle',
61
                'class' => Action::class,
62
                'fields' => [],
63
                'permissions' => [
64
                    'ROLE_ADMIN',
65
                ],
66
                'export' => [],
67
                'order' => [],
68
                'route' => $this->generateRouteName(),
69
                'route_parameters' => [],
70
                'route_path' => $this->getDefaultRoutePath(),
71
                'route_requirements' => [],
72
                'route_defaults' => [
73
                    '_controller' => AdminAction::class,
74
                ],
75
                'icon' => null,
76
                'load_strategy' => LAGAdminBundle::LOAD_STRATEGY_NONE,
77
                'pager' => false,
78
                'max_per_page' => 30,
79
                'criteria' => [],
80
                'filters' => [],
81
                'menus' => [],
82
                'template' => $this->getDefaultTemplate(),
83
                'sortable' => false,
84
                'string_length' => $this->adminConfiguration->getParameter('string_length'),
85
                'string_length_truncate' => $this->adminConfiguration->getParameter('string_length_truncate'),
86
                'date_format' => $this->adminConfiguration->getParameter('date_format'),
87
                'use_form' => false,
88
            ])
89
            ->setAllowedTypes('title', 'string')
90
            ->setAllowedTypes('class', 'string')
91
            ->setAllowedTypes('fields', 'array')
92
            ->setAllowedTypes('permissions', 'array')
93
            ->setAllowedTypes('export', 'array')
94
            ->setAllowedTypes('order', 'array')
95
            ->setAllowedTypes('route', 'string')
96
            ->setAllowedTypes('route_parameters', 'array')
97
            ->setAllowedTypes('route_path', 'string')
98
            ->setAllowedTypes('route_defaults', 'array')
99
            ->setAllowedTypes('route_requirements', 'array')
100
            ->setAllowedTypes('string_length', 'integer')
101
            ->setAllowedTypes('string_length_truncate', 'string')
102
            ->setNormalizer('fields', $this->getFieldsNormalizer())
103
            ->setNormalizer('order', $this->getOrderNormalizer())
104
            ->setNormalizer('load_strategy', $this->getLoadStrategyNormalizer())
105
            ->setNormalizer('criteria', $this->getCriteriaNormalizer())
106
            ->setNormalizer('menus', $this->getMenuNormalizer())
107
            ->setNormalizer('filters', $this->getFiltersNormalizer())
108
            ->setNormalizer('route_defaults', $this->getRouteDefaultNormalizer())
109
            ->setAllowedValues('load_strategy', [
110
                LAGAdminBundle::LOAD_STRATEGY_NONE,
111
                LAGAdminBundle::LOAD_STRATEGY_UNIQUE,
112
                LAGAdminBundle::LOAD_STRATEGY_MULTIPLE,
113
            ])
114
            ->setAllowedValues('pager', [
115
                'pagerfanta',
116
                false,
117
                null,
118
            ])
119
;
120
        $this->configureNormalizers($resolver);
0 ignored issues
show
Unused Code introduced by
The call to the method LAG\AdminBundle\Configur...:configureNormalizers() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
121
    }
122
123
    /**
124
     * Generate an admin route name using the pattern in the configuration.
125
     *
126
     * @return string
127
     *
128
     * @throws Exception
129
     */
130
    private function generateRouteName()
131
    {
132
        if (!array_key_exists($this->actionName, $this->adminConfiguration->getParameter('actions'))) {
133
            throw new Exception(
134
                sprintf('Invalid action name %s for admin %s (available action are: %s)',
135
                    $this->actionName,
136
                    $this->adminName,
137
                    implode(', ', array_keys($this->adminConfiguration->getParameter('actions'))))
138
            );
139
        }
140
        $routeName = RoutingLoader::generateRouteName(
141
            $this->adminName,
142
            $this->actionName,
143
            $this->adminConfiguration->getParameter('routing_name_pattern')
144
        );
145
146
        return $routeName;
147
    }
148
149
    /**
150
     * Configure the normalizers.
151
     *
152
     * @param OptionsResolver $resolver
153
     */
154
    private function configureNormalizers(OptionsResolver $resolver)
0 ignored issues
show
Unused Code introduced by
The parameter $resolver 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...
155
    {
156
157
    }
158
159
    /**
160
     * Return the field normalizer. It will transform null configuration into array to allow field type guessing
161
     * working.
162
     *
163
     * @return Closure
164
     */
165
    private function getFieldsNormalizer()
166
    {
167
        return function (Options $options, $fields) {
168
            $normalizedFields = [];
169
170
            foreach ($fields as $name => $field) {
171
172
                if ($field === null) {
173
                    $field = [];
174
                }
175
176
                $normalizedFields[$name] = $field;
177
            }
178
179
            return $normalizedFields;
180
        };
181
    }
182
183
    /**
184
     * Return the order normalizer. It will check if the order value passed are valid.
185
     *
186
     * @return Closure
187
     */
188
    private function getOrderNormalizer()
189
    {
190
        return function (Options $options, $order) {
191
            foreach ($order as $field => $sort) {
192
193
                if (!is_string($sort) || !is_string($field) || !in_array(strtolower($sort), ['asc', 'desc'])) {
194
                    throw new Exception(
195
                        'Order value should be an array of string (["field" => $key]), got '.gettype($sort),
196
                        $this->actionName,
197
                        $this->adminName
198
                    );
199
                }
200
            }
201
202
            return $order;
203
        };
204
    }
205
206
    /**
207
     * Return the load strategy normalizer. It will set the default strategy according to the action name, if no value
208
     * is provided.
209
     *
210
     * @return Closure
211
     */
212
    private function getLoadStrategyNormalizer()
213
    {
214
        return function (Options $options, $value) {
215
            if (!$value) {
216
                if ($this->actionName == 'create') {
217
                    $value = LAGAdminBundle::LOAD_STRATEGY_NONE;
218
                } else if ($this->actionName == 'list') {
219
                    $value = LAGAdminBundle::LOAD_STRATEGY_MULTIPLE;
220
                } else {
221
                    $value = LAGAdminBundle::LOAD_STRATEGY_UNIQUE;
222
                }
223
            }
224
225
            return $value;
226
        };
227
    }
228
229
    /**
230
     * Return the menu normalizer. It will transform false values into an empty array to allow default menu
231
     * configuration working.
232
     *
233
     * @return Closure
234
     */
235
    private function getMenuNormalizer()
236
    {
237
        return function (Options $options, $menus) {
238
            // set default to an array
239
            if ($menus === false) {
240
                $menus = [];
241
            }
242
243
            return $menus;
244
        };
245
    }
246
247
    /**
248
     * Return the criteria normalizer. It will add the id parameters for the edit and delete actions if no value is
249
     * provided.
250
     *
251
     * @return Closure
252
     */
253
    private function getCriteriaNormalizer()
254
    {
255
        return function (Options $options, $value) {
256
            if (!$value) {
257
                $idActions = [
258
                    'edit',
259
                    'delete',
260
                ];
261
262
                if (in_array($this->actionName, $idActions)) {
263
                    $value = [
264
                        'id',
265
                    ];
266
                }
267
            }
268
269
            return $value;
270
        };
271
    }
272
273
    /**
274
     * @return string
275
     */
276
    public function getAdminName(): string
277
    {
278
        return $this->adminName;
279
    }
280
281
    /**
282
     * @return string
283
     */
284
    public function getActionName(): string
285
    {
286
        return $this->actionName;
287
    }
288
289
    /**
290
     * @return AdminConfiguration
291
     */
292
    public function getAdminConfiguration(): AdminConfiguration
293
    {
294
        return $this->adminConfiguration;
295
    }
296
297
    /**
298
     * Return the filters normalizer.
299
     *
300
     * @return Closure
301
     */
302
    private function getFiltersNormalizer()
303
    {
304
        return function (Options $options, $data) {
305
            $normalizedData = [];
306
307
            foreach ($data as $name => $field) {
308
                if (is_string($field)) {
309
                    $field = [
310
                        'type' => $field,
311
                        'options' => [],
312
                    ];
313
                }
314
                $field['name'] = $name;
315
316
                $resolver = new OptionsResolver();
317
                $filterConfiguration = new FilterConfiguration();
318
                $filterConfiguration->configureOptions($resolver);
319
                $filterConfiguration->setParameters($resolver->resolve($field));
320
321
                $normalizedData[$name] = $filterConfiguration->getParameters();
322
            }
323
324
            return $normalizedData;
325
        };
326
    }
327
328
    private function getRouteDefaultNormalizer()
329
    {
330
        return function (Options $options, $value) {
331
            if (!is_array($value)) {
332
                $value = [];
333
            }
334
            $value['_admin'] = $this->adminName;
335
            $value['_action'] = $this->actionName;
336
337
            return $value;
338
        };
339
    }
340
341
    /**
342
     * Return the default title using the configured translation pattern.
343
     *
344
     * @return string
345
     */
346
    private function getDefaultTitle()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
347
    {
348
        $translationPattern = $this
349
            ->adminConfiguration
350
            ->getParameter('translation_pattern');
351
352
        if (false !== $translationPattern) {
353
            // by default, the action title is action name using the configured translation pattern
354
355
            $actionTitle = $this->getTranslationKey(
0 ignored issues
show
Bug introduced by
The method getTranslationKey() does not seem to exist on object<LAG\AdminBundle\C...on\ActionConfiguration>.

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...
356
                $translationPattern,
357
                $this->actionName,
358
                $this->adminName
359
            );
360
        } else {
361
            // no admin was provided, we camelize the action name
362
            $actionTitle = Container::camelize($this->actionName);
363
        }
364
365
        return $actionTitle;
366
    }
367
368
    /**
369
     * Return the default route path according to the action name.
370
     *
371
     * @return string
372
     */
373
    private function getDefaultRoutePath()
374
    {
375
        $pattern = $this
376
            ->adminConfiguration
377
            ->getParameter('routing_url_pattern')
378
        ;
379
        $path = str_replace('{admin}', $this->adminName, $pattern);
380
        $path = str_replace('{action}', $this->actionName, $path);
381
382
        if (in_array($this->actionName, ['edit', 'delete'])) {
383
            $path .= '/{id}';
384
        }
385
386
        return $path;
387
    }
388
389
    /**
390
     * Return the defaults route parameters according to a mapping based on the action name.
391
     *
392
     * @return array
393
     */
394
    private function getDefaultRouteDefaults()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
395
    {
396
        $mapping = [
397
            'list' => [
398
                '_controller' => LAGAdminBundle::SERVICE_ID_LIST_ACTION,
399
                '_admin' => $this->adminName,
400
                '_action' => $this->actionName,
401
            ],
402
            'create' => [
403
                '_controller' => LAGAdminBundle::SERVICE_ID_CREATE_ACTION,
404
                '_admin' => $this->adminName,
405
                '_action' => $this->actionName,
406
            ],
407
            'edit' => [
408
                '_controller' => LAGAdminBundle::SERVICE_ID_EDIT_ACTION,
409
                '_admin' => $this->adminName,
410
                '_action' => $this->actionName,
411
            ],
412
            'delete' => [
413
                '_controller' => LAGAdminBundle::SERVICE_ID_DELETE_ACTION,
414
                '_admin' => $this->adminName,
415
                '_action' => $this->actionName,
416
            ],
417
        ];
418
        $defaults = [];
419
420
        if (array_key_exists($this->actionName, $mapping)) {
421
            $defaults = $mapping[$this->actionName];
422
        }
423
424
        return $defaults;
425
    }
426
427
    /**
428
     * Return the default route requirements according to the action name.
429
     *
430
     * @return array
431
     */
432
    private function getDefaultRouteRequirements()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
433
    {
434
        $mapping = [
435
            'edit' => [
436
                'id' => '\d+',
437
            ],
438
            'delete' => [
439
                'id' => '\d+',
440
            ],
441
        ];
442
        $requirements = [];
443
444
        if (array_key_exists($this->actionName, $mapping)) {
445
            $requirements = $mapping[$this->actionName];
446
        }
447
448
        return $requirements;
449
    }
450
451
    /**
452
     * Return the default form according to the action name.
453
     *
454
     * @return string|null
455
     */
456
    private function getDefaultForm()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
457
    {
458
        $mapping = [
459
            'list' => ListType::class,
460
            'delete' => DeleteType::class,
461
        ];
462
463
        if (!array_key_exists($this->actionName, $mapping)) {
464
            // try to get an admin globally configured form
465
            $adminForm = $this
466
                ->adminConfiguration
467
                ->getParameter('form');
468
469
            if (null !== $adminForm) {
470
                return $adminForm;
471
            }
472
473
            return null;
474
        }
475
476
        return $mapping[$this->actionName];
477
    }
478
479
    /**
480
     * Return a default form handler service id, or null, according to to the action name.
481
     *
482
     * @return mixed|null
483
     */
484
    private function getDefaultFormHandler()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
485
    {
486
        $mapping = [
487
            'edit' => LAGAdminBundle::SERVICE_ID_EDIT_FORM_HANDLER,
488
            'list' => LAGAdminBundle::SERVICE_ID_LIST_FORM_HANDLER,
489
        ];
490
491
        if (!array_key_exists($this->actionName, $mapping)) {
492
            return null;
493
        }
494
495
        return $mapping[$this->actionName];
496
    }
497
498
    private function getDefaultFormOptions()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
499
    {
500
        $mapping = [
501
            'list' => [
502
                'actions' => [
503
                    'lag.admin.delete' => 'delete',
504
                ]
505
            ],
506
        ];
507
508
        if (!$this->isActionInMapping($mapping)) {
509
            return [];
510
        }
511
512
        return $mapping[$this->actionName];
513
    }
514
515
    private function getDefaultTemplate()
516
    {
517
        $mapping = [
518
            'list' => '@LAGAdmin/CRUD/list.html.twig',
519
            'edit' => '@LAGAdmin/CRUD/edit.html.twig',
520
            'create' => '@LAGAdmin/CRUD/create.html.twig',
521
            'delete' => '@LAGAdmin/CRUD/delete.html.twig',
522
        ];
523
524
        if (!$this->isActionInMapping($mapping)) {
525
            return null;
526
        }
527
528
        return $mapping[$this->actionName];
529
    }
530
531
    private function isActionInMapping(array $mapping)
532
    {
533
        return array_key_exists($this->actionName, $mapping);
534
    }
535
536
    private function getDefaultSortable()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
537
    {
538
        $mapping = [
539
            'list' => true,
540
        ];
541
542
        if (!$this->isActionInMapping($mapping)) {
543
            return false;
544
        }
545
546
        return $mapping[$this->actionName];
547
    }
548
549
    private function getDefaultResponder()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
550
    {
551
        $mapping = [
552
            'list' => 'lag.admin.action.list_responder',
553
            'create' => 'lag.admin.action.create_responder',
554
            'edit' => 'lag.admin.action.edit_responder',
555
            'delete' => 'lag.admin.action.delete_responder',
556
        ];
557
558
        if (!$this->isActionInMapping($mapping)) {
559
            return null;
560
        }
561
562
        return $mapping[$this->actionName];
563
    }
564
}
565