Completed
Pull Request — master (#71)
by Arnaud
03:02
created

Admin   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 505
Duplicated Lines 9.5 %

Coupling/Cohesion

Components 1
Dependencies 15

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 45
lcom 1
cbo 15
dl 48
loc 505
ccs 184
cts 184
cp 1
rs 7.5292
c 0
b 0
f 0

21 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 1
B handleRequest() 0 34 1
B checkPermissions() 0 32 6
A create() 0 14 1
B save() 24 24 3
B remove() 24 24 3
A generateRouteName() 0 18 2
C load() 0 39 7
A getEntities() 0 4 1
A getUniqueEntity() 0 10 3
A getName() 0 4 1
B isActionGranted() 0 23 5
A getActions() 0 4 1
A getActionNames() 0 4 1
A getAction() 0 10 2
A hasAction() 0 4 1
A addAction() 0 4 1
A getCurrentAction() 0 11 2
A isCurrentActionDefined() 0 4 1
A getConfiguration() 0 4 1
A generateMessageTranslationKey() 0 8 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 Admin 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 Admin, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace LAG\AdminBundle\Admin;
4
5
use Doctrine\Common\Collections\Collection;
6
use Doctrine\ORM\EntityManagerInterface;
7
use LAG\AdminBundle\Action\ActionInterface;
8
use LAG\AdminBundle\Admin\Behaviors\AdminTrait;
9
use LAG\AdminBundle\Admin\Configuration\AdminConfiguration;
10
use Doctrine\Common\Collections\ArrayCollection;
11
use Exception;
12
use LAG\AdminBundle\DataProvider\DataProviderInterface;
13
use LAG\AdminBundle\Exception\AdminException;
14
use LAG\AdminBundle\Filter\RequestFilterInterface;
15
use LAG\AdminBundle\Message\MessageHandlerInterface;
16
use LAG\AdminBundle\Pager\PagerFantaAdminAdapter;
17
use Pagerfanta\Pagerfanta;
18
use Symfony\Component\DependencyInjection\Container;
19
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
22
use Symfony\Component\Security\Core\Role\Role;
23
use Symfony\Component\Security\Core\User\UserInterface;
24
25
class Admin implements AdminInterface
26
{
27
    use AdminTrait;
28
29
    /**
30
     * Entities collection.
31
     *
32
     * @var ArrayCollection
33
     */
34
    protected $entities;
35
36
    /**
37
     * @var MessageHandlerInterface
38
     */
39
    protected $messageHandler;
40
41
    /**
42
     * @var EntityManagerInterface
43
     */
44
    protected $entityManager;
45
46
    /**
47
     * @var DataProviderInterface
48
     */
49
    protected $dataProvider;
50
51
    /**
52
     * Admin configuration object
53
     *
54
     * @var AdminConfiguration
55
     */
56
    protected $configuration;
57
58
    /**
59
     * Admin configured actions
60
     *
61
     * @var ActionInterface[]
62
     */
63
    protected $actions = [];
64
65
    /**
66
     * Admin current action. It will be set after calling the handleRequest()
67
     *
68
     * @var ActionInterface
69
     */
70
    protected $currentAction;
71
72
    /**
73
     * Admin name
74
     *
75
     * @var string
76
     */
77
    protected $name;
78
79
    /**
80
     * @var EventDispatcherInterface
81
     */
82
    protected $eventDispatcher;
83
84
    /**
85
     * @var RequestFilterInterface
86
     */
87
    protected $requestFilter;
88
89
    /**
90
     * Admin constructor.
91
     *
92
     * @param string $name
93
     * @param DataProviderInterface $dataProvider
94
     * @param AdminConfiguration $configuration
95
     * @param MessageHandlerInterface $messageHandler
96
     * @param EventDispatcherInterface $eventDispatcher
97
     * @param RequestFilterInterface $requestFilter
98
     */
99 27
    public function __construct(
100
        $name,
101
        DataProviderInterface $dataProvider,
102
        AdminConfiguration $configuration,
103
        MessageHandlerInterface $messageHandler,
104
        EventDispatcherInterface $eventDispatcher,
105
        RequestFilterInterface $requestFilter
106
    ) {
107 27
        $this->name = $name;
108 27
        $this->dataProvider = $dataProvider;
109 27
        $this->configuration = $configuration;
110 27
        $this->messageHandler = $messageHandler;
111 27
        $this->eventDispatcher = $eventDispatcher;
112 27
        $this->entities = new ArrayCollection();
113 27
        $this->requestFilter = $requestFilter;
114 27
    }
115
116
    /**
117
     * Load entities and set current action according to request.
118
     *
119
     * @param Request $request
120
     * @param null $user
121
     * @return void
122
     * @throws AdminException
123
     */
124 9
    public function handleRequest(Request $request, $user = null)
125
    {
126
        // set current action
127 9
        $this->currentAction = $this->getAction($request->get('_route_params')['_action']);
128
129
        // check if user is logged have required permissions to get current action
130 9
        $this->checkPermissions($user);
131
132 9
        $actionConfiguration = $this
133
            ->currentAction
134 9
            ->getConfiguration();
135
136
        // configure the request filter with the action and admin configured parameters
137 9
        $this
138
            ->requestFilter
139 9
            ->configure(
140 9
                $actionConfiguration->getParameter('criteria'),
141 9
                $actionConfiguration->getParameter('order'),
142 9
                $this->configuration->getParameter('max_per_page')
143 9
            );
144
145
        // filter the request with the configured criteria, order and max_per_page parameter
146 9
        $this
147
            ->requestFilter
148 9
            ->filter($request);
149
150
        // load entities according to action and request
151 9
        $this->load(
152 9
            $this->requestFilter->getCriteria(),
153 9
            $this->requestFilter->getOrder(),
154 9
            $this->requestFilter->getMaxPerPage(),
155 9
            $this->requestFilter->getCurrentPage()
156 9
        );
157 8
    }
158
159
    /**
160
     * Check if user is allowed to be here
161
     *
162
     * @param UserInterface|string $user
163
     * @throws Exception
164
     */
165 9
    public function checkPermissions($user)
166
    {
167 9
        if (!($user instanceof UserInterface)) {
168 9
            return;
169
        }
170 1
        if ($this->currentAction === null) {
171 1
            throw new Exception('Current action should be set before checking the permissions');
172
        }
173 1
        $roles = $user->getRoles();
174 1
        $actionName = $this
175 1
            ->getCurrentAction()
176 1
            ->getName();
177
178 1
        if (!$this->isActionGranted($actionName, $roles)) {
179 1
            $rolesStringArray = [];
180
181 1
            foreach ($roles as $role) {
182
183 1
                if ($role instanceof Role) {
184 1
                    $rolesStringArray[] = $role->getRole();
185 1
                } else {
186 1
                    $rolesStringArray[] = $role;
187
                }
188 1
            }
189
190 1
            $message = sprintf('User with roles %s not allowed for action "%s"',
191 1
                implode(', ', $rolesStringArray),
192
                $actionName
193 1
            );
194 1
            throw new NotFoundHttpException($message);
195
        }
196 1
    }
197
198
    /**
199
     * Create and return a new entity.
200
     *
201
     * @return object
202
     */
203 5
    public function create()
204
    {
205
        // create an entity from the data provider
206 5
        $entity = $this
207
            ->dataProvider
208 5
            ->create();
209
210
        // add it to the collection
211 5
        $this
212
            ->entities
213 5
            ->add($entity);
214
215 5
        return $entity;
216
    }
217
218
    /**
219
     * Save entity via admin manager. Error are catch, logged and a flash message is added to session
220
     *
221
     * @return bool true if the entity was saved without errors
222
     */
223 2 View Code Duplication
    public function save()
224
    {
225
        try {
226 2
            foreach ($this->entities as $entity) {
227 2
                $this
228
                    ->dataProvider
229 2
                    ->save($entity);
230 1
            }
231
            // inform the user that the entity is saved
232 1
            $this
233
                ->messageHandler
234 1
                ->handleSuccess($this->generateMessageTranslationKey('saved'));
235 1
            $success = true;
236 2
        } catch (Exception $e) {
237 1
            $this
238
                ->messageHandler
239 1
                ->handleError(
240 1
                    $this->generateMessageTranslationKey('lag.admin.saved_errors'),
241 1
                    "An error has occurred while saving an entity : {$e->getMessage()}, stackTrace: {$e->getTraceAsString()}"
242 1
                );
243 1
            $success = false;
244
        }
245 2
        return $success;
246
    }
247
248
    /**
249
     * Remove an entity with data provider
250
     *
251
     * @return bool true if the entity was saved without errors
252
     */
253 2 View Code Duplication
    public function remove()
254
    {
255
        try {
256 2
            foreach ($this->entities as $entity) {
257 2
                $this
258
                    ->dataProvider
259 2
                    ->remove($entity);
260 1
            }
261
            // inform the user that the entity is removed
262 1
            $this
263
                ->messageHandler
264 1
                ->handleSuccess($this->generateMessageTranslationKey('deleted'));
265 1
            $success = true;
266 2
        } catch (Exception $e) {
267 1
            $this
268
                ->messageHandler
269 1
                ->handleError(
270 1
                    $this->generateMessageTranslationKey('lag.admin.deleted_errors'),
271 1
                    "An error has occurred while deleting an entity : {$e->getMessage()}, stackTrace: {$e->getTraceAsString()} "
272 1
                );
273 1
            $success = false;
274
        }
275 2
        return $success;
276
    }
277
278
    /**
279
     * Generate a route for admin and action name (like lag.admin.my_admin)
280
     *
281
     * @param $actionName
282
     *
283
     * @return string
284
     *
285
     * @throws Exception
286
     */
287 16
    public function generateRouteName($actionName)
288
    {
289 16
        if (!array_key_exists($actionName, $this->getConfiguration()->getParameter('actions'))) {
290 2
            throw new Exception(
291 2
                sprintf('Invalid action name %s for admin %s (available action are: %s)',
292 2
                    $actionName,
293 2
                    $this->getName(),
294 2
                    implode(', ', $this->getActionNames()))
295 2
            );
296
        }
297
        // get routing name pattern
298 15
        $routingPattern = $this->getConfiguration()->getParameter('routing_name_pattern');
299
        // replace admin and action name in pattern
300 15
        $routeName = str_replace('{admin}', Container::underscore($this->getName()), $routingPattern);
301 15
        $routeName = str_replace('{action}', $actionName, $routeName);
302
303 15
        return $routeName;
304
    }
305
306
    /**
307
     * Load entities manually according to criteria.
308
     *
309
     * @param array $criteria
310
     * @param array $orderBy
311
     * @param int $limit
312
     * @param int $offset
313
     * @throws Exception
314
     */
315 9
    public function load(array $criteria, $orderBy = [], $limit = 25, $offset = 1)
316
    {
317 9
        $actionConfiguration = $this
318 9
            ->getCurrentAction()
319 9
            ->getConfiguration();
320 9
        $pager = $actionConfiguration->getParameter('pager');
321 9
        $requirePagination = $this
322 9
            ->getCurrentAction()
323 9
            ->isPaginationRequired();
324
325 9
        if ($pager == 'pagerfanta' && $requirePagination) {
326
            // adapter to pagerfanta
327 1
            $adapter = new PagerFantaAdminAdapter($this->dataProvider, $criteria, $orderBy);
328
            // create pager
329 1
            $this->pager = new Pagerfanta($adapter);
330 1
            $this->pager->setMaxPerPage($limit);
331 1
            $this->pager->setCurrentPage($offset);
332
333 1
            $entities = $this
334
                ->pager
335 1
                ->getCurrentPageResults();
336 1
        } else {
337
            // if the current action should retrieve only one entity, the offset should be zero
338 8
            if ($actionConfiguration->getParameter('load_strategy') !== AdminInterface::LOAD_STRATEGY_MULTIPLE) {
339 7
                $offset = 0;
340 7
            }
341 8
            $entities = $this
342
                ->dataProvider
343 8
                ->findBy($criteria, $orderBy, $limit, $offset);
344
        }
345 9
        if (!is_array($entities) && !($entities instanceof Collection)) {
346 1
            throw new Exception('The data provider should return either a collection or an array. Got '.gettype($entities).' instead');
347
        }
348
349 8
        if (is_array($entities)) {
350 8
            $entities = new ArrayCollection($entities);
351 8
        }
352 8
        $this->entities = $entities;
353 8
    }
354
355
    /**
356
     * Return loaded entities
357
     *
358
     * @return Collection
359
     */
360 2
    public function getEntities()
361
    {
362 2
        return $this->entities;
363
    }
364
365
    /**
366
     * Return entity for current admin. If entity does not exist, it throws an exception.
367
     *
368
     * @return mixed
369
     *
370
     * @throws Exception
371
     */
372 1
    public function getUniqueEntity()
373
    {
374 1
        if ($this->entities->count() == 0) {
375 1
            throw new Exception("Entity not found in admin \"{$this->getName()}\".");
376
        }
377 1
        if ($this->entities->count() > 1) {
378 1
            throw new Exception("Too much entities found in admin \"{$this->getName()}\".");
379
        }
380 1
        return $this->entities->first();
381
    }
382
383
    /**
384
     * Return admin name
385
     *
386
     * @return string
387
     */
388 20
    public function getName()
389
    {
390 20
        return $this->name;
391
    }
392
393
    /**
394
     * Return true if current action is granted for user.
395
     *
396
     * @param string $actionName Le plus grand de tous les héros
397
     * @param array $roles
398
     *
399
     * @return bool
400
     */
401 2
    public function isActionGranted($actionName, array $roles)
402
    {
403 2
        $isGranted = array_key_exists($actionName, $this->actions);
404
405
        // if action exists
406 2
        if ($isGranted) {
407 2
            $isGranted = false;
408
            /** @var ActionInterface $action */
409 2
            $action = $this->actions[$actionName];
410
            // checking roles permissions
411 2
            foreach ($roles as $role) {
412
413 2
                if ($role instanceof Role) {
414 2
                    $role = $role->getRole();
415 2
                }
416 2
                if (in_array($role, $action->getPermissions())) {
417 2
                    $isGranted = true;
418 2
                }
419 2
            }
420 2
        }
421
422 2
        return $isGranted;
423
    }
424
425
    /**
426
     * @return ActionInterface[]
427
     */
428 10
    public function getActions()
429
    {
430 10
        return $this->actions;
431
    }
432
433
    /**
434
     * @return integer[]
435
     */
436 2
    public function getActionNames()
437
    {
438 2
        return array_keys($this->actions);
439
    }
440
441
    /**
442
     * @param $name
443
     * @return ActionInterface
444
     * @throws Exception
445
     */
446 9
    public function getAction($name)
447
    {
448 9
        if (!array_key_exists($name, $this->getActions())) {
449 1
            throw new Exception(
450 1
                "Invalid action name \"{$name}\" for admin '{$this->getName()}'. Check your configuration"
451 1
            );
452
        }
453
454 9
        return $this->actions[$name];
455
    }
456
457
    /**
458
     * Return if an action with specified name exists form this admin.
459
     *
460
     * @param $name
461
     * @return bool
462
     */
463 1
    public function hasAction($name)
464
    {
465 1
        return array_key_exists($name, $this->actions);
466
    }
467
468
    /**
469
     * @param ActionInterface $action
470
     * @return void
471
     */
472 15
    public function addAction(ActionInterface $action)
473
    {
474 15
        $this->actions[$action->getName()] = $action;
475 15
    }
476
477
    /**
478
     * Return the current action or an exception if it is not set.
479
     *
480
     * @return ActionInterface
481
     * @throws Exception
482
     */
483 10
    public function getCurrentAction()
484
    {
485 10
        if ($this->currentAction === null) {
486
            // current action should be defined
487 1
            throw new Exception(
488
                'Current action is null. You should initialize it (with handleRequest method for example)'
489 1
            );
490
        }
491
492 9
        return $this->currentAction;
493
    }
494
495
    /**
496
     * Return if the current action has been initialized and set.
497
     *
498
     * @return boolean
499
     */
500 1
    public function isCurrentActionDefined()
501
    {
502 1
        return ($this->currentAction instanceof ActionInterface);
503
    }
504
505
    /**
506
     * Return admin configuration object.
507
     *
508
     * @return AdminConfiguration
509
     */
510 20
    public function getConfiguration()
511
    {
512 20
        return $this->configuration;
513
    }
514
515
    /**
516
     * Return a translation key for a message according to the Admin's translation pattern.
517
     *
518
     * @param string $message
519
     * @return string
520
     */
521 4
    protected function generateMessageTranslationKey($message)
522
    {
523 4
        return $this->getTranslationKey(
524 4
            $this->configuration->getParameter('translation_pattern'),
525 4
            $message,
526 4
            $this->name
527 4
        );
528
    }
529
}
530