Completed
Pull Request — master (#8)
by Arnaud
02:50
created

Admin::getAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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