Completed
Pull Request — dev (#56)
by Arnaud
18:15 queued 10:16
created

Admin::getActionNames()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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