Completed
Push — master ( 06c1ce...67d37c )
by Jeroen
06:20
created

ActionsMenuBuilder   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 519
Duplicated Lines 27.36 %

Coupling/Cohesion

Components 1
Dependencies 12

Test Coverage

Coverage 79.07%

Importance

Changes 0
Metric Value
wmc 46
lcom 1
cbo 12
dl 142
loc 519
ccs 136
cts 172
cp 0.7907
rs 8.72
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 19 1
A createSubActionsMenu() 0 30 3
F createActionsMenu() 142 312 36
A createTopActionsMenu() 0 11 1
A createHomeActionsMenu() 0 23 1
A createTopHomeActionsMenu() 0 11 1
A setActiveNodeVersion() 0 6 1
A getActiveNodeVersion() 0 4 1
A setEditableNode() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ActionsMenuBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ActionsMenuBuilder, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Kunstmaan\NodeBundle\Helper\Menu;
4
5
use Doctrine\ORM\EntityManager;
6
use FOS\UserBundle\Model\UserInterface;
7
use Knp\Menu\FactoryInterface;
8
use Knp\Menu\ItemInterface;
9
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionMap;
10
use Kunstmaan\NodeBundle\Entity\NodeVersion;
11
use Kunstmaan\NodeBundle\Event\ConfigureActionMenuEvent;
12
use Kunstmaan\NodeBundle\Event\Events;
13
use Kunstmaan\NodeBundle\Helper\PagesConfiguration;
14
use Kunstmaan\PagePartBundle\Helper\HasPageTemplateInterface;
15
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
16
use Symfony\Component\Routing\RouterInterface;
17
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
18
19
class ActionsMenuBuilder
20
{
21
    /**
22
     * @var FactoryInterface
23
     */
24
    private $factory;
25
26
    /**
27
     * @var NodeVersion
28
     */
29
    private $activeNodeVersion;
30
31
    /**
32
     * @var EntityManager
33
     */
34
    private $em;
35
36
    /**
37
     * @var RouterInterface
38
     */
39
    private $router;
40
41
    /**
42
     * @var EventDispatcherInterface
43
     */
44
    private $dispatcher;
45
46
    /**
47
     * @var AuthorizationCheckerInterface
48
     */
49
    private $authorizationChecker;
50
51
    /**
52
     * @var PagesConfiguration
53
     */
54
    private $pagesConfiguration;
55
56
    /**
57
     * @var bool
58
     */
59
    private $isEditableNode = true;
60
61
    /**
62
     * @var bool
63
     */
64
    private $enableExportPageTemplate;
65
66
    /** @var bool */
67
    private $showDuplicateWithChildren;
68
69
    /**
70
     * @param FactoryInterface              $factory
71
     * @param EntityManager                 $em
72
     * @param RouterInterface               $router
73
     * @param EventDispatcherInterface      $dispatcher
74
     * @param AuthorizationCheckerInterface $authorizationChecker
75
     * @param PagesConfiguration            $pagesConfiguration
76
     * @param bool                          $enableExportPageTemplate
77
     * @param bool                          $showDuplicateWithChildren
78
     */
79 8
    public function __construct(
80
        FactoryInterface $factory,
81
        EntityManager $em,
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $em. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
82
        RouterInterface $router,
83
        EventDispatcherInterface $dispatcher,
84
        AuthorizationCheckerInterface $authorizationChecker,
85
        PagesConfiguration $pagesConfiguration,
86
        $enableExportPageTemplate = true,
87
        bool $showDuplicateWithChildren = false
88
    ) {
89 8
        $this->factory = $factory;
90 8
        $this->em = $em;
91 8
        $this->router = $router;
92 8
        $this->dispatcher = $dispatcher;
93 8
        $this->authorizationChecker = $authorizationChecker;
94 8
        $this->pagesConfiguration = $pagesConfiguration;
95 8
        $this->enableExportPageTemplate = $enableExportPageTemplate;
96 8
        $this->showDuplicateWithChildren = $showDuplicateWithChildren;
97 8
    }
98
99
    /**
100
     * @return ItemInterface
101
     */
102 1
    public function createSubActionsMenu()
103
    {
104 1
        $activeNodeVersion = $this->getActiveNodeVersion();
105 1
        $menu = $this->factory->createItem('root');
106 1
        $menu->setChildrenAttribute('class', 'page-sub-actions');
107
108 1
        if (null !== $activeNodeVersion && $this->isEditableNode) {
109 1
            $menu->addChild(
110 1
                'subaction.versions',
111
                [
112
                    'linkAttributes' => [
113 1
                        'data-toggle' => 'modal',
114
                        'data-keyboard' => 'true',
115
                        'data-target' => '#versions',
116
                    ],
117
                ]
118
            );
119
        }
120
121 1
        $this->dispatcher->dispatch(
122 1
            Events::CONFIGURE_SUB_ACTION_MENU,
123 1
            new ConfigureActionMenuEvent(
124 1
                $this->factory,
125
                $menu,
126
                $activeNodeVersion
127
            )
128
        );
129
130 1
        return $menu;
131
    }
132
133
    /**
134
     * @return ItemInterface
135
     */
136 6
    public function createActionsMenu()
137
    {
138 6
        $activeNodeVersion = $this->getActiveNodeVersion();
139
140 6
        $translations = $activeNodeVersion->getNodeTranslation()->getNode()->getNodeTranslations(true);
141 6
        $canRecopy = false;
142 6
        foreach ($translations as $translation) {
143 1
            if ($translation->getLang() != $activeNodeVersion->getNodeTranslation()->getLang()) {
144 1
                $canRecopy = true;
145
            }
146
        }
147
148 6
        $menu = $this->factory->createItem('root');
149 6
        $menu->setChildrenAttribute(
150 6
            'class',
151 6
            'page-main-actions js-auto-collapse-buttons'
152
        );
153 6
        $menu->setChildrenAttribute(
154 6
            'data-visible-buttons',
155 6
            '3'
156
        );
157
158 6
        if (null === $activeNodeVersion) {
159
            $this->dispatcher->dispatch(
160
                Events::CONFIGURE_ACTION_MENU,
161
                new ConfigureActionMenuEvent(
162
                    $this->factory,
163
                    $menu,
164
                    $activeNodeVersion
165
                )
166
            );
167
168
            return $menu;
169
        }
170
171 6
        $activeNodeTranslation = $activeNodeVersion->getNodeTranslation();
172 6
        $node = $activeNodeTranslation->getNode();
173 6
        $queuedNodeTranslationAction = $this->em->getRepository(
174 6
            'KunstmaanNodeBundle:QueuedNodeTranslationAction'
175 6
        )->findOneBy(['nodeTranslation' => $activeNodeTranslation]);
176
177 6
        $isFirst = true;
178 6
        $canEdit = $this->authorizationChecker->isGranted(PermissionMap::PERMISSION_EDIT, $node);
179 6
        $canPublish = $this->authorizationChecker->isGranted(PermissionMap::PERMISSION_PUBLISH, $node);
180 6
        $isSuperAdmin = $this->authorizationChecker->isGranted(UserInterface::ROLE_SUPER_ADMIN);
181
182 6
        if ($activeNodeVersion->isDraft() && $this->isEditableNode) {
183 1 View Code Duplication
            if ($canEdit) {
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...
184 1
                $menu->addChild(
185 1
                    'action.saveasdraft',
186
                    [
187
                        'linkAttributes' => [
188 1
                            'type' => 'submit',
189
                            'class' => 'js-save-btn btn btn--raise-on-hover btn-primary',
190
                            'value' => 'save',
191
                            'name' => 'save',
192
                        ],
193
                        'extras' => ['renderType' => 'button'],
194
                    ]
195
                );
196 1
                if ($this->enableExportPageTemplate && $isSuperAdmin && is_subclass_of($node->getRefEntityName(), HasPageTemplateInterface::class)) {
197
                    $menu->addChild(
198
                        'action.exportpagetemplate',
199
                        [
200
                            'linkAttributes' => [
201
                                'class' => 'btn btn-default btn--raise-on-hover',
202
                                'data-toggle' => 'modal',
203
                                'data-keyboard' => 'true',
204
                                'data-target' => '#exportPagetemplate',
205
                            ],
206
                        ]
207
                    );
208
                }
209 1
                if ($canRecopy) {
210
                    $menu->addChild(
211
                        'action.recopyfromlanguage',
212
                        [
213
                            'linkAttributes' => [
214
                                'class' => 'btn btn-default btn--raise-on-hover',
215
                                'data-toggle' => 'modal',
216
                                'data-keyboard' => 'true',
217
                                'data-target' => '#recopy',
218
                            ],
219
                        ]
220
                    );
221
                }
222 1
                $isFirst = false;
223
            }
224
225 1
            $menu->addChild(
226 1
                'action.preview',
227
                [
228 1
                    'uri' => $this->router->generate(
229 1
                        '_slug_preview',
230
                        [
231 1
                            'url' => $activeNodeTranslation->getUrl(),
232 1
                            'version' => $activeNodeVersion->getId(),
233
                        ]
234
                    ),
235
                    'linkAttributes' => [
236
                        'target' => '_blank',
237
                        'class' => 'btn btn-default btn--raise-on-hover',
238
                    ],
239
                ]
240
            );
241
242 1 View Code Duplication
            if (empty($queuedNodeTranslationAction) && $canPublish) {
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...
243 1
                $menu->addChild(
244 1
                    'action.publish',
245
                    [
246
                        'linkAttributes' => [
247 1
                            'data-toggle' => 'modal',
248 1
                            'data-target' => '#pub',
249 1
                            'class' => 'btn btn--raise-on-hover'.($isFirst ? ' btn-primary btn-save' : ' btn-default'),
250
                        ],
251
                    ]
252
                );
253
            }
254
        } else {
255 5
            if ($canEdit && $canPublish) {
256 5
                $menu->addChild(
257 5
                    'action.save',
258
                    [
259
                        'linkAttributes' => [
260 5
                            'type' => 'submit',
261
                            'class' => 'js-save-btn btn btn--raise-on-hover btn-primary',
262
                            'value' => 'save',
263
                            'name' => 'save',
264
                        ],
265
                        'extras' => ['renderType' => 'button'],
266
                    ]
267
                );
268 5
                $isFirst = false;
269
            }
270
271 5
            if ($this->isEditableNode) {
272 4
                $menu->addChild(
273 4
                    'action.preview',
274
                    [
275 4
                        'uri' => $this->router->generate(
276 4
                            '_slug_preview',
277 4
                            ['url' => $activeNodeTranslation->getUrl()]
278
                        ),
279
                        'linkAttributes' => [
280
                            'target' => '_blank',
281
                            'class' => 'btn btn-default btn--raise-on-hover',
282
                        ],
283
                    ]
284
                );
285
286 4
                if (empty($queuedNodeTranslationAction)
287 4
                    && $activeNodeTranslation->isOnline()
288 1
                    && $this->authorizationChecker->isGranted(
289 4
                        PermissionMap::PERMISSION_UNPUBLISH,
290
                        $node
291
                    )
292
                ) {
293 1
                    $menu->addChild(
294 1
                        'action.unpublish',
295
                        [
296
                            'linkAttributes' => [
297 1
                                'class' => 'btn btn-default btn--raise-on-hover',
298
                                'data-toggle' => 'modal',
299
                                'data-keyboard' => 'true',
300
                                'data-target' => '#unpub',
301
                            ],
302
                        ]
303
                    );
304 4 View Code Duplication
                } elseif (empty($queuedNodeTranslationAction)
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...
305 4
                    && !$activeNodeTranslation->isOnline()
306 4
                    && $canPublish
307
                ) {
308 4
                    $menu->addChild(
309 4
                        'action.publish',
310
                        [
311
                            'linkAttributes' => [
312 4
                                'class' => 'btn btn-default btn--raise-on-hover',
313
                                'data-toggle' => 'modal',
314
                                'data-keyboard' => 'true',
315
                                'data-target' => '#pub',
316
                            ],
317
                        ]
318
                    );
319
                }
320
321 4 View Code Duplication
                if ($canEdit) {
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...
322 4
                    $menu->addChild(
323 4
                        'action.saveasdraft',
324
                        [
325
                            'linkAttributes' => [
326 4
                                'type' => 'submit',
327 4
                                'class' => 'btn btn--raise-on-hover'.($isFirst ? ' btn-primary btn-save' : ' btn-default'),
328 4
                                'value' => 'saveasdraft',
329 4
                                'name' => 'saveasdraft',
330
                            ],
331
                            'extras' => ['renderType' => 'button'],
332
                        ]
333
                    );
334 4
                    if ($this->enableExportPageTemplate && $isSuperAdmin && is_subclass_of($node->getRefEntityName(), HasPageTemplateInterface::class)) {
335
                        $menu->addChild(
336
                            'action.exportpagetemplate',
337
                            [
338
                                'linkAttributes' => [
339
                                    'class' => 'btn btn-default btn--raise-on-hover',
340
                                    'data-toggle' => 'modal',
341
                                    'data-keyboard' => 'true',
342
                                    'data-target' => '#exportPagetemplate',
343
                                ],
344
                            ]
345
                        );
346
                    }
347 4
                    if ($canRecopy) {
348 1
                        $menu->addChild(
349 1
                            'action.recopyfromlanguage',
350
                            [
351
                                'linkAttributes' => [
352 1
                                    'class' => 'btn btn-default btn--raise-on-hover',
353
                                    'data-toggle' => 'modal',
354
                                    'data-keyboard' => 'true',
355
                                    'data-target' => '#recopy',
356
                                ],
357
                            ]
358
                        );
359
                    }
360
                }
361
            }
362
        }
363
364 6 View Code Duplication
        if ($this->pagesConfiguration->getPossibleChildTypes(
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...
365 6
            $node->getRefEntityName()
366
        )
367
        ) {
368
            $menu->addChild(
369
                'action.addsubpage',
370
                [
371
                    'linkAttributes' => [
372
                        'type' => 'button',
373
                        'class' => 'btn btn-default btn--raise-on-hover',
374
                        'data-toggle' => 'modal',
375
                        'data-keyboard' => 'true',
376
                        'data-target' => '#add-subpage-modal',
377
                    ],
378
                    'extras' => ['renderType' => 'button'],
379
                ]
380
            );
381
        }
382
383 6
        if (null !== $node->getParent() && $canEdit) {
384 1
            $menu->addChild(
385 1
                'action.duplicate',
386
                [
387
                    'linkAttributes' => [
388 1
                        'type' => 'button',
389
                        'class' => 'btn btn-default btn--raise-on-hover',
390
                        'data-toggle' => 'modal',
391
                        'data-keyboard' => 'true',
392
                        'data-target' => '#duplicate-page-modal',
393
                    ],
394
                    'extras' => ['renderType' => 'button'],
395
                ]
396
            );
397
398 1 View Code Duplication
            if ($this->showDuplicateWithChildren) {
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...
399
                $menu->addChild(
400
                    'action.duplicate_with_children',
401
                    [
402
                        'linkAttributes' => [
403
                            'type' => 'button',
404
                            'class' => 'btn btn-default btn--raise-on-hover',
405
                            'data-toggle' => 'modal',
406
                            'data-keyboard' => 'true',
407
                            'data-target' => '#duplicate-with-children-page-modal',
408
                        ],
409
                        'extras' => ['renderType' => 'button'],
410
                    ]
411
                );
412
            }
413
        }
414
415 6
        if ((null !== $node->getParent() || $node->getChildren()->isEmpty())
416 6
            && $this->authorizationChecker->isGranted(
417 6
                PermissionMap::PERMISSION_DELETE,
418
                $node
419
            )
420
        ) {
421 6
            $menu->addChild(
422 6
                'action.delete',
423
                [
424
                    'linkAttributes' => [
425 6
                        'type' => 'button',
426
                        'class' => 'btn btn-default btn--raise-on-hover',
427
                        'onClick' => 'oldEdited = isEdited; isEdited=false',
428
                        'data-toggle' => 'modal',
429
                        'data-keyboard' => 'true',
430
                        'data-target' => '#delete-page-modal',
431
                    ],
432
                    'extras' => ['renderType' => 'button'],
433
                ]
434
            );
435
        }
436
437 6
        $this->dispatcher->dispatch(
438 6
            Events::CONFIGURE_ACTION_MENU,
439 6
            new ConfigureActionMenuEvent(
440 6
                $this->factory,
441
                $menu,
442
                $activeNodeVersion
443
            )
444
        );
445
446 6
        return $menu;
447
    }
448
449
    /**
450
     * @return ItemInterface
451
     */
452 1
    public function createTopActionsMenu()
453
    {
454 1
        $menu = $this->createActionsMenu();
455 1
        $menu->setChildrenAttribute('id', 'page-main-actions-top');
456 1
        $menu->setChildrenAttribute(
457 1
            'class',
458 1
            'page-main-actions page-main-actions--top'
459
        );
460
461 1
        return $menu;
462
    }
463
464
    /**
465
     * @return ItemInterface
466
     */
467
    public function createHomeActionsMenu()
468
    {
469
        $menu = $this->factory->createItem('root');
470
        $menu->setChildrenAttribute(
471
            'class',
472
            'page-main-actions js-auto-collapse-buttons'
473
        );
474
        $menu->addChild(
475
            'action.addhomepage',
476
            [
477
                'linkAttributes' => [
478
                    'type' => 'button',
479
                    'class' => 'btn btn-default btn--raise-on-hover',
480
                    'data-toggle' => 'modal',
481
                    'data-keyboard' => 'true',
482
                    'data-target' => '#add-homepage-modal',
483
                ],
484
                'extras' => ['renderType' => 'button'],
485
            ]
486
        );
487
488
        return $menu;
489
    }
490
491
    /**
492
     * @return ItemInterface
493
     */
494
    public function createTopHomeActionsMenu()
495
    {
496
        $menu = $this->createHomeActionsMenu();
497
        $menu->setChildrenAttribute('id', 'page-main-actions-top');
498
        $menu->setChildrenAttribute(
499
            'class',
500
            'page-main-actions page-main-actions--top'
501
        );
502
503
        return $menu;
504
    }
505
506
    /**
507
     * Set activeNodeVersion
508
     *
509
     * @param NodeVersion $activeNodeVersion
510
     *
511
     * @return ActionsMenuBuilder
512
     */
513 8
    public function setActiveNodeVersion(NodeVersion $activeNodeVersion)
514
    {
515 8
        $this->activeNodeVersion = $activeNodeVersion;
516
517 8
        return $this;
518
    }
519
520
    /**
521
     * Get activeNodeVersion
522
     *
523
     * @return NodeVersion
524
     */
525 8
    public function getActiveNodeVersion()
526
    {
527 8
        return $this->activeNodeVersion;
528
    }
529
530
    /**
531
     * @param bool $value
532
     */
533 1
    public function setEditableNode($value)
534
    {
535 1
        $this->isEditableNode = $value;
536 1
    }
537
}
538