Completed
Pull Request — master (#92)
by Arnaud
17:46
created

Admin::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

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