Completed
Push — dev ( 4306de...25864c )
by Arnaud
02:52
created

Admin::handleRequest()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 3.0013

Importance

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