Completed
Pull Request — master (#71)
by Arnaud
15:22 queued 12:55
created

Admin::loadPaginate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 4
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
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 33
    public function __construct(
100
        $name,
101
        DataProviderInterface $dataProvider,
102
        AdminConfiguration $configuration,
103
        MessageHandlerInterface $messageHandler,
104
        EventDispatcherInterface $eventDispatcher,
105
        RequestFilterInterface $requestFilter
106
    ) {
107 33
        $this->name = $name;
108 33
        $this->dataProvider = $dataProvider;
109 33
        $this->configuration = $configuration;
110 33
        $this->messageHandler = $messageHandler;
111 33
        $this->eventDispatcher = $eventDispatcher;
112 33
        $this->entities = new ArrayCollection();
113 33
        $this->requestFilter = $requestFilter;
114 33
    }
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 12
    public function handleRequest(Request $request, $user = null)
125
    {
126
        // set current action
127 12
        $this->currentAction = $this->getAction($request->get('_route_params')['_action']);
128
129
        // check if user is logged have required permissions to get current action
130 12
        $this->checkPermissions($user);
131
132
        $actionConfiguration = $this
133 12
            ->currentAction
134 12
            ->getConfiguration();
135
136
        // configure the request filter with the action and admin configured parameters
137
        $this
138 12
            ->requestFilter
139 12
            ->configure(
140 12
                $actionConfiguration->getParameter('criteria'),
141 12
                $actionConfiguration->getParameter('order'),
142 12
                $this->configuration->getParameter('max_per_page')
143
            );
144
145
        // filter the request with the configured criteria, order and max_per_page parameter
146
        $this
147 12
            ->requestFilter
148 12
            ->filter($request);
149
150
        // load entities according to action and request
151 12
        $this->load(
152 12
            $this->requestFilter->getCriteria(),
153 12
            $this->requestFilter->getOrder(),
154 12
            $this->requestFilter->getMaxPerPage(),
155 12
            $this->requestFilter->getCurrentPage()
156
        );
157 9
    }
158
159
    /**
160
     * Check if user is allowed to be here
161
     *
162
     * @param UserInterface|string $user
163
     * @throws Exception
164
     */
165 12
    public function checkPermissions($user)
166
    {
167 12
        if (!($user instanceof UserInterface)) {
168 12
            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
        $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
                } else {
186 1
                    $rolesStringArray[] = $role;
187
                }
188
            }
189
190 1
            $message = sprintf('User with roles %s not allowed for action "%s"',
191 1
                implode(', ', $rolesStringArray),
192
                $actionName
193
            );
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
        $entity = $this
207 5
            ->dataProvider
208 5
            ->create();
209
210
        // add it to the collection
211
        $this
212 5
            ->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
                $this
228 2
                    ->dataProvider
229 2
                    ->save($entity);
230
            }
231
            // inform the user that the entity is saved
232
            $this
233 1
                ->messageHandler
234 1
                ->handleSuccess($this->generateMessageTranslationKey('saved'));
235 1
            $success = true;
236 1
        } catch (Exception $e) {
237
            $this
238 1
                ->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
                );
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
                $this
258 2
                    ->dataProvider
259 2
                    ->remove($entity);
260
            }
261
            // inform the user that the entity is removed
262
            $this
263 1
                ->messageHandler
264 1
                ->handleSuccess($this->generateMessageTranslationKey('deleted'));
265 1
            $success = true;
266 1
        } catch (Exception $e) {
267
            $this
268 1
                ->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
                );
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 19
    public function generateRouteName($actionName)
288
    {
289 19
        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
                    $actionName,
293 2
                    $this->getName(),
294 2
                    implode(', ', $this->getActionNames()))
295
            );
296
        }
297
        // get routing name pattern
298 18
        $routingPattern = $this->getConfiguration()->getParameter('routing_name_pattern');
299
        // replace admin and action name in pattern
300 18
        $routeName = str_replace('{admin}', Container::underscore($this->getName()), $routingPattern);
301 18
        $routeName = str_replace('{action}', $actionName, $routeName);
302
303 18
        return $routeName;
304
    }
305
306
    /**
307
     * Load entities according to the given criteria and the current action configuration.
308
     *
309
     * @param array $criteria
310
     * @param array $orderBy
311
     * @param int $limit
312
     * @param int $offset
313
     * @throws Exception
314
     */
315 12
    public function load(array $criteria, array $orderBy = [], $limit = 25, $offset = 1)
316
    {
317 12
        $currentAction = $this->getCurrentAction();
318 12
        $currentActionConfiguration = $currentAction->getConfiguration();
319
320
        // some action, such as create, does not require the entities to be loaded
321 12
        if (!$currentAction->isLoadingRequired()) {
322 2
            return;
323
        }
324 11
        $pager = $currentActionConfiguration->getParameter('pager');
325
326 11
        if ($currentAction->isPaginationRequired() && $pager) {
327 3
            $loadStrategy = $currentActionConfiguration->getParameter('load_strategy');
328
329
            // only pagerfanta adapter is yet supported
330 3
            if ('pagerfanta' !== $pager) {
331 1
                throw new AdminException(
332 1
                    'Only pagerfanta value is allowed for pager parameter, given '.$pager,
333 1
                    $currentAction->getName(),
334
                    $this
335
                );
336
            }
337
            // only load strategy multiple is allowed for pagination (ie, can not paginate if only one entity is loaded)
338 2
            if (AdminInterface::LOAD_STRATEGY_MULTIPLE !== $loadStrategy) {
339 1
                throw new AdminException(
340 1
                    'Only "strategy_multiple" value is allowed for pager parameter, given '.$loadStrategy,
341 1
                    $currentAction->getName(),
342
                    $this
343
                );
344
            }
345
            // load entities using a pager
346 1
            $this->loadPaginate($criteria, $orderBy, $limit, $offset);
347
        } else {
348 8
            $this->loadWithoutPagination($criteria, $orderBy, $limit, $offset);
349
        }
350
351
        // the data provider should return an array or a collection of entities.
352 9
        if (!is_array($this->entities) && !$this->entities instanceof Collection) {
353 1
            throw new AdminException(
354
                'The data provider should return either a collection or an array. Got '
355 1
                .gettype($this->entities).' instead',
356 1
                $currentAction->getName(),
357
                $this
358
            );
359
        }
360
361
        // if an array is provided, transform it to a collection to be more convenient
362 8
        if (is_array($this->entities)) {
363 8
            $this->entities = new ArrayCollection($this->entities);
364
        }
365 8
    }
366
367
    /**
368
     * Return loaded entities
369
     *
370
     * @return Collection
371
     */
372 3
    public function getEntities()
373
    {
374 3
        return $this->entities;
375
    }
376
377
    /**
378
     * Return entity for current admin. If entity does not exist, it throws an exception.
379
     *
380
     * @return mixed
381
     *
382
     * @throws Exception
383
     */
384 1
    public function getUniqueEntity()
385
    {
386 1
        if ($this->entities->count() == 0) {
387 1
            throw new Exception('Entity not found in admin "'.$this->getName());
388
        }
389 1
        if ($this->entities->count() > 1) {
390 1
            throw new Exception(
391 1
                'Too much entities found in admin "{$this->getName()}" ('.$this->entities->count().').'
392
            );
393
        }
394 1
        return $this->entities->first();
395
    }
396
397
    /**
398
     * Return admin name
399
     *
400
     * @return string
401
     */
402 26
    public function getName()
403
    {
404 26
        return $this->name;
405
    }
406
407
    /**
408
     * Return true if current action is granted for user.
409
     *
410
     * @param string $actionName Le plus grand de tous les héros
411
     * @param array $roles
412
     *
413
     * @return bool
414
     */
415 2
    public function isActionGranted($actionName, array $roles)
416
    {
417 2
        $isGranted = array_key_exists($actionName, $this->actions);
418
419
        // if action exists
420 2
        if ($isGranted) {
421 2
            $isGranted = false;
422
            /** @var ActionInterface $action */
423 2
            $action = $this->actions[$actionName];
424
            // checking roles permissions
425 2
            foreach ($roles as $role) {
426
427 2
                if ($role instanceof Role) {
428 2
                    $role = $role->getRole();
429
                }
430 2
                if (in_array($role, $action->getPermissions())) {
431 2
                    $isGranted = true;
432
                }
433
            }
434
        }
435
436 2
        return $isGranted;
437
    }
438
439
    /**
440
     * @return ActionInterface[]
441
     */
442 13
    public function getActions()
443
    {
444 13
        return $this->actions;
445
    }
446
447
    /**
448
     * @return integer[]
449
     */
450 2
    public function getActionNames()
451
    {
452 2
        return array_keys($this->actions);
453
    }
454
455
    /**
456
     * @param $name
457
     * @return ActionInterface
458
     * @throws Exception
459
     */
460 12
    public function getAction($name)
461
    {
462 12
        if (!array_key_exists($name, $this->getActions())) {
463 1
            throw new Exception(
464 1
                "Invalid action name \"{$name}\" for admin '{$this->getName()}'. Check your configuration"
465
            );
466
        }
467
468 12
        return $this->actions[$name];
469
    }
470
471
    /**
472
     * Return if an action with specified name exists form this admin.
473
     *
474
     * @param $name
475
     * @return bool
476
     */
477 1
    public function hasAction($name)
478
    {
479 1
        return array_key_exists($name, $this->actions);
480
    }
481
482
    /**
483
     * @param ActionInterface $action
484
     * @return void
485
     */
486 18
    public function addAction(ActionInterface $action)
487
    {
488 18
        $this->actions[$action->getName()] = $action;
489 18
    }
490
491
    /**
492
     * Return the current action or an exception if it is not set.
493
     *
494
     * @return ActionInterface
495
     * @throws Exception
496
     */
497 13
    public function getCurrentAction()
498
    {
499 13
        if ($this->currentAction === null) {
500
            // current action should be defined
501 1
            throw new Exception(
502 1
                'Current action is null. You should initialize it (with handleRequest method for example)'
503
            );
504
        }
505
506 12
        return $this->currentAction;
507
    }
508
509
    /**
510
     * Return if the current action has been initialized and set.
511
     *
512
     * @return boolean
513
     */
514 1
    public function isCurrentActionDefined()
515
    {
516 1
        return ($this->currentAction instanceof ActionInterface);
517
    }
518
519
    /**
520
     * Return admin configuration object.
521
     *
522
     * @return AdminConfiguration
523
     */
524 23
    public function getConfiguration()
525
    {
526 23
        return $this->configuration;
527
    }
528
529
    /**
530
     * Return a translation key for a message according to the Admin's translation pattern.
531
     *
532
     * @param string $message
533
     * @return string
534
     */
535 4
    protected function generateMessageTranslationKey($message)
536
    {
537 4
        return $this->getTranslationKey(
538 4
            $this->configuration->getParameter('translation_pattern'),
539
            $message,
540 4
            $this->name
541
        );
542
    }
543
544
    /**
545
     * Load entities using PagerFanta.
546
     *
547
     * @param array $criteria
548
     * @param array $orderBy
549
     * @param int $limit
550
     * @param int $offset
551
     */
552 1
    protected function loadPaginate(array $criteria, array $orderBy, $limit, $offset)
553
    {
554
        // adapter to pagerfanta
555 1
        $adapter = new PagerFantaAdminAdapter($this->dataProvider, $criteria, $orderBy);
556
        // create pager
557 1
        $this->pager = new Pagerfanta($adapter);
558 1
        $this->pager->setMaxPerPage($limit);
559 1
        $this->pager->setCurrentPage($offset);
560
561 1
        $this->entities = $this
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->pager->getCurrentPageResults() of type array or object<Traversable> is incompatible with the declared type object<Doctrine\Common\C...ctions\ArrayCollection> of property $entities.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
562 1
            ->pager
563 1
            ->getCurrentPageResults();
564 1
    }
565
566
    /**
567
     * Load entities using to configured data provider.
568
     *
569
     * @param array $criteria
570
     * @param array $orderBy
571
     * @param int $limit
572
     * @param int $offset
573
     */
574 8
    protected function loadWithoutPagination(array $criteria, $orderBy, $limit, $offset)
575
    {
576 8
        $currentAction = $this->getCurrentAction();
577 8
        $currentActionConfiguration = $currentAction->getConfiguration();
578
579
        // if the current action should retrieve only one entity, the offset should be zero
580 8
        if ($currentActionConfiguration->getParameter('load_strategy') !== AdminInterface::LOAD_STRATEGY_MULTIPLE) {
581 7
            $offset = 0;
582 7
            $limit = 1;
583
        }
584
        // load entities according to the given parameters
585 8
        $this->entities = $this
586 8
            ->dataProvider
587 8
            ->findBy($criteria, $orderBy, $limit, $offset);
588 8
    }
589
}
590