Completed
Pull Request — dev (#48)
by Arnaud
03:46
created

Admin::addAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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