Completed
Pull Request — master (#71)
by Arnaud
14:19 queued 12:02
created

Admin::loadPaginate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 7
cts 7
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 1
    }
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
        $roles = $user->getRoles();
174
        $actionName = $this
175
            ->getCurrentAction()
176
            ->getName();
177
178
        if (!$this->isActionGranted($actionName, $roles)) {
179
            $rolesStringArray = [];
180
181
            foreach ($roles as $role) {
182
183
                if ($role instanceof Role) {
184
                    $rolesStringArray[] = $role->getRole();
185
                } else {
186
                    $rolesStringArray[] = $role;
187
                }
188
            }
189
190
            $message = sprintf('User with roles %s not allowed for action "%s"',
191
                implode(', ', $rolesStringArray),
192
                $actionName
193
            );
194
            throw new NotFoundHttpException($message);
195
        }
196
    }
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 1
            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
            $entities = $this->loadPaginate($criteria, $orderBy, $limit, $offset);
347
        } else {
348
            // load using the data provider
349 8
            $entities = $this->loadWithoutPagination($criteria, $orderBy, $limit, $offset);
350
        }
351
352
        // the data provider should return an array or a collection of entities.
353 9
        if (!is_array($entities) && !$entities instanceof Collection) {
354 1
            throw new AdminException(
355
                'The data provider should return either a collection or an array. Got '
356 1
                .gettype($entities).' instead',
357 1
                $currentAction->getName(),
358
                $this
359
            );
360
        }
361
362
        // if an array is provided, transform it to a collection to be more convenient
363 8
        if (is_array($entities)) {
364 8
            $entities = new ArrayCollection($this->entities);
0 ignored issues
show
Documentation introduced by
$this->entities is of type object<Doctrine\Common\C...ctions\ArrayCollection>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
365
        }
366
367
        // load the entities into the Admin
368
        $this->entities = $entities;
369
    }
370
371
    /**
372
     * Return loaded entities
373
     *
374
     * @return Collection
375
     */
376 1
    public function getEntities()
377
    {
378 1
        return $this->entities;
379
    }
380
381
    /**
382
     * Return entity for current admin. If entity does not exist, it throws an exception.
383
     *
384
     * @return mixed
385
     *
386
     * @throws Exception
387
     */
388
    public function getUniqueEntity()
389
    {
390
        if ($this->entities->count() == 0) {
391
            throw new Exception('Entity not found in admin "'.$this->getName());
392
        }
393
        if ($this->entities->count() > 1) {
394
            throw new Exception(
395
                'Too much entities found in admin "{$this->getName()}" ('.$this->entities->count().').'
396
            );
397
        }
398
        return $this->entities->first();
399
    }
400
401
    /**
402
     * Return admin name
403
     *
404
     * @return string
405
     */
406 26
    public function getName()
407
    {
408 26
        return $this->name;
409
    }
410
411
    /**
412
     * Return true if current action is granted for user.
413
     *
414
     * @param string $actionName Le plus grand de tous les héros
415
     * @param array $roles
416
     *
417
     * @return bool
418
     */
419
    public function isActionGranted($actionName, array $roles)
420
    {
421
        $isGranted = array_key_exists($actionName, $this->actions);
422
423
        // if action exists
424
        if ($isGranted) {
425
            $isGranted = false;
426
            /** @var ActionInterface $action */
427
            $action = $this->actions[$actionName];
428
            // checking roles permissions
429
            foreach ($roles as $role) {
430
431
                if ($role instanceof Role) {
432
                    $role = $role->getRole();
433
                }
434
                if (in_array($role, $action->getPermissions())) {
435
                    $isGranted = true;
436
                }
437
            }
438
        }
439
440
        return $isGranted;
441
    }
442
443
    /**
444
     * @return ActionInterface[]
445
     */
446 13
    public function getActions()
447
    {
448 13
        return $this->actions;
449
    }
450
451
    /**
452
     * @return integer[]
453
     */
454 2
    public function getActionNames()
455
    {
456 2
        return array_keys($this->actions);
457
    }
458
459
    /**
460
     * @param $name
461
     * @return ActionInterface
462
     * @throws Exception
463
     */
464 12
    public function getAction($name)
465
    {
466 12
        if (!array_key_exists($name, $this->getActions())) {
467 1
            throw new Exception(
468 1
                "Invalid action name \"{$name}\" for admin '{$this->getName()}'. Check your configuration"
469
            );
470
        }
471
472 12
        return $this->actions[$name];
473
    }
474
475
    /**
476
     * Return if an action with specified name exists form this admin.
477
     *
478
     * @param $name
479
     * @return bool
480
     */
481
    public function hasAction($name)
482
    {
483
        return array_key_exists($name, $this->actions);
484
    }
485
486
    /**
487
     * @param ActionInterface $action
488
     * @return void
489
     */
490 18
    public function addAction(ActionInterface $action)
491
    {
492 18
        $this->actions[$action->getName()] = $action;
493 18
    }
494
495
    /**
496
     * Return the current action or an exception if it is not set.
497
     *
498
     * @return ActionInterface
499
     * @throws Exception
500
     */
501 13
    public function getCurrentAction()
502
    {
503 13
        if ($this->currentAction === null) {
504
            // current action should be defined
505 1
            throw new Exception(
506 1
                'Current action is null. You should initialize it (with handleRequest method for example)'
507
            );
508
        }
509
510 12
        return $this->currentAction;
511
    }
512
513
    /**
514
     * Return if the current action has been initialized and set.
515
     *
516
     * @return boolean
517
     */
518 1
    public function isCurrentActionDefined()
519
    {
520 1
        return ($this->currentAction instanceof ActionInterface);
521
    }
522
523
    /**
524
     * Return admin configuration object.
525
     *
526
     * @return AdminConfiguration
527
     */
528 23
    public function getConfiguration()
529
    {
530 23
        return $this->configuration;
531
    }
532
533
    /**
534
     * Return a translation key for a message according to the Admin's translation pattern.
535
     *
536
     * @param string $message
537
     * @return string
538
     */
539 4
    protected function generateMessageTranslationKey($message)
540
    {
541 4
        return $this->getTranslationKey(
542 4
            $this->configuration->getParameter('translation_pattern'),
543
            $message,
544 4
            $this->name
545
        );
546
    }
547
548
    /**
549
     * Load entities using PagerFanta.
550
     *
551
     * @param array $criteria
552
     * @param array $orderBy
553
     * @param int $limit
554
     * @param int $offset
555
     *
556
     * @return array|\Traversable
557
     */
558 1
    protected function loadPaginate(array $criteria, array $orderBy, $limit, $offset)
559
    {
560
        // adapter to pagerfanta
561 1
        $adapter = new PagerFantaAdminAdapter($this->dataProvider, $criteria, $orderBy);
562
        // create pager
563 1
        $this->pager = new Pagerfanta($adapter);
564 1
        $this->pager->setMaxPerPage($limit);
565 1
        $this->pager->setCurrentPage($offset);
566
567
        return $this
568 1
            ->pager
569 1
            ->getCurrentPageResults();
570
    }
571
572
    /**
573
     * Load entities using to configured data provider.
574
     *
575
     * @param array $criteria
576
     * @param array $orderBy
577
     * @param int $limit
578
     * @param int $offset
579
     *
580
     * @return array|Collection
581
     */
582 8
    protected function loadWithoutPagination(array $criteria, $orderBy, $limit, $offset)
583
    {
584 8
        $currentAction = $this->getCurrentAction();
585 8
        $currentActionConfiguration = $currentAction->getConfiguration();
586
587
        // if the current action should retrieve only one entity, the offset should be zero
588 8
        if ($currentActionConfiguration->getParameter('load_strategy') !== AdminInterface::LOAD_STRATEGY_MULTIPLE) {
589 7
            $offset = 0;
590 7
            $limit = 1;
591
        }
592
593
        return $this
594 8
            ->dataProvider
595 8
            ->findBy($criteria, $orderBy, $limit, $offset);
596
    }
597
}
598