Completed
Push — dev ( 330909...b3efe2 )
by Arnaud
03:30
created

Admin::remove()   B

Complexity

Conditions 3
Paths 5

Size

Total Lines 24
Code Lines 18

Duplication

Lines 24
Ratio 100 %

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 24
loc 24
ccs 16
cts 16
cp 1
rs 8.9713
cc 3
eloc 18
nc 5
nop 0
crap 3
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 15
    public function __construct(
103
        $name,
104
        DataProviderInterface $dataProvider,
105
        AdminConfiguration $configuration,
106
        MessageHandlerInterface $messageHandler
107
    ) {
108 15
        $this->name = $name;
109 15
        $this->dataProvider = $dataProvider;
110 15
        $this->configuration = $configuration;
111 15
        $this->messageHandler = $messageHandler;
112 15
        $this->entities = new ArrayCollection();
113 15
    }
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 5
    public function handleRequest(Request $request, $user = null)
124
    {
125
        // set current action
126 5
        $this->currentAction = $this->getAction($request->get('_route_params')['_action']);
127
        // check if user is logged have required permissions to get current action
128 5
        $this->checkPermissions($user);
129
130
        // criteria filter request
131 5
        $filter = new RequestFilter($this->currentAction->getConfiguration()->getCriteria());
132 5
        $criteriaFilter = $filter->filter($request);
133
134
        // pager filter request
135 5
        if ($this->currentAction->getConfiguration()->getPager() == 'pagerfanta') {
136 4
            $filter = new PagerfantaFilter();
137 4
            $pagerFilter = $filter->filter($request);
138 4
        } else {
139
            // empty bag
140 2
            $pagerFilter = new ParameterBag();
141
        }
142
143
        // if load strategy is none, no entity should be loaded
144 5
        if ($this->currentAction->getConfiguration()->getLoadStrategy() == Admin::LOAD_STRATEGY_NONE) {
145 1
            return;
146
        }
147
148
        // load entities according to action and request
149 5
        $this->load(
150 5
            $criteriaFilter->all(),
151 5
            $pagerFilter->get('order', []),
152 5
            $this->configuration->getMaxPerPage(),
153 5
            $pagerFilter->get('page', 1)
154 5
        );
155 5
    }
156
157
    /**
158
     * Check if user is allowed to be here
159
     *
160
     * @param UserInterface|string $user
161
     * @throws Exception
162
     */
163 5
    public function checkPermissions($user)
164
    {
165 5
        if (!($user instanceof UserInterface)) {
166 5
            return;
167
        }
168 1
        if ($this->currentAction === null) {
169 1
            throw new Exception('Current action should be set before checking the permissions');
170
        }
171 1
        $roles = $user->getRoles();
172 1
        $actionName = $this
173 1
            ->getCurrentAction()
174 1
            ->getName();
175
176 1
        if (!$this->isActionGranted($actionName, $roles)) {
177 1
            $message = sprintf('User with roles %s not allowed for action "%s"',
178 1
                implode(', ', $roles),
179
                $actionName
180 1
            );
181 1
            throw new NotFoundHttpException($message);
182
        }
183 1
    }
184
185
    /**
186
     * Create and return a new entity.
187
     *
188
     * @return object
189
     */
190 3
    public function create()
191
    {
192
        // create an entity from the data provider
193 3
        $entity = $this
194
            ->dataProvider
195 3
            ->create();
196
197
        // add it to the collection
198 3
        $this
199
            ->entities
200 3
            ->add($entity);
201
202 3
        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 1 View Code Duplication
    public function save()
211
    {
212
        try {
213 1
            foreach ($this->entities as $entity) {
214 1
                $this
215
                    ->dataProvider
216 1
                    ->save($entity);
217 1
            }
218
            // inform user everything went fine
219 1
            $this
220
                ->messageHandler
221 1
                ->handleSuccess('lag.admin.' . $this->name . '.saved');
222 1
            $success = true;
223 1
        } catch (Exception $e) {
224 1
            $this
225
                ->messageHandler
226 1
                ->handleError(
227 1
                    'lag.admin.saved_errors',
228 1
                    "An error has occurred while saving an entity : {$e->getMessage()}, stackTrace: {$e->getTraceAsString()}"
229 1
                );
230 1
            $success = false;
231
        }
232 1
        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 1 View Code Duplication
    public function remove()
241
    {
242
        try {
243 1
            foreach ($this->entities as $entity) {
244 1
                $this
245
                    ->dataProvider
246 1
                    ->remove($entity);
247 1
            }
248
            // inform user everything went fine
249 1
            $this
250
                ->messageHandler
251 1
                ->handleSuccess('lag.admin.' . $this->name . '.deleted');
252 1
            $success = true;
253 1
        } catch (Exception $e) {
254 1
            $this
255
                ->messageHandler
256 1
                ->handleError(
257 1
                    'lag.admin.deleted_errors',
258 1
                    "An error has occurred while deleting an entity : {$e->getMessage()}, stackTrace: {$e->getTraceAsString()} "
259 1
                );
260 1
            $success = false;
261
        }
262 1
        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 1
    public function generateRouteName($actionName)
275
    {
276 1
        if (!array_key_exists($actionName, $this->getConfiguration()->getActions())) {
277 1
            $message = 'Invalid action name %s for admin %s (available action are: %s)';
278 1
            throw new Exception(sprintf($message, $actionName, $this->getName(), implode(', ', $this->getActionNames())));
279
        }
280
        // get routing name pattern
281 1
        $routingPattern = $this->getConfiguration()->getRoutingNamePattern();
282
        // replace admin and action name in pattern
283 1
        $routeName = str_replace('{admin}', Container::underscore($this->getName()), $routingPattern);
284 1
        $routeName = str_replace('{action}', $actionName, $routeName);
285
286 1
        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 5
    public function load(array $criteria, $orderBy = [], $limit = 25, $offset = 1)
299
    {
300 5
        $pager = $this
301 5
            ->getCurrentAction()
302 5
            ->getConfiguration()
303 5
            ->getPager();
304
305 5
        if ($pager == 'pagerfanta') {
306
            // adapter to pager fanta
307 4
            $adapter = new PagerFantaAdminAdapter($this->dataProvider, $criteria, $orderBy);
308
            // create pager
309 4
            $this->pager = new Pagerfanta($adapter);
310 4
            $this->pager->setMaxPerPage($limit);
311 4
            $this->pager->setCurrentPage($offset);
312
313 4
            $entities = $this
314
                ->pager
315 4
                ->getCurrentPageResults();
316 4
        } else {
317 2
            $entities = $this
318
                ->dataProvider
319 2
                ->findBy($criteria, $orderBy, $limit, $offset);
320
        }
321 5
        if (!is_array($entities) && !($entities instanceof Collection)) {
322 1
            throw new Exception('The data provider should return either a collection or an array. Got ' . gettype($entities) . ' instead');
323
        }
324
325 5
        if (is_array($entities)) {
326 5
            $entities = new ArrayCollection($entities);
327 5
        }
328 5
        $this->entities = $entities;
329 5
    }
330
331
    /**
332
     * Return loaded entities
333
     *
334
     * @return Collection
335
     */
336 2
    public function getEntities()
337
    {
338 2
        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 1
    public function getUniqueEntity()
349
    {
350 1
        if ($this->entities->count() == 0) {
351 1
            throw new Exception("Entity not found in admin \"{$this->getName()}\".");
352
        }
353 1
        if ($this->entities->count() > 1) {
354 1
            throw new Exception("Too much entities found in admin \"{$this->getName()}\".");
355
        }
356 1
        return $this->entities->first();
357
    }
358
359
    /**
360
     * Return admin name
361
     *
362
     * @return string
363
     */
364 10
    public function getName()
365
    {
366 10
        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 1
    public function isActionGranted($actionName, array $roles)
378
    {
379 1
        $isGranted = array_key_exists($actionName, $this->actions);
380
381
        // if action exists
382 1
        if ($isGranted) {
383 1
            $isGranted = false;
384
            /** @var Action $action */
385 1
            $action = $this->actions[$actionName];
386
            // checking roles permissions
387 1
            foreach ($roles as $role) {
388
389 1
                if ($role instanceof Role) {
390
                    $role = $role->getRole();
391
                }
392 1
                if (in_array($role, $action->getPermissions())) {
393 1
                    $isGranted = true;
394 1
                }
395 1
            }
396 1
        }
397
398 1
        return $isGranted;
399
    }
400
401
    /**
402
     * @return ActionInterface[]
403
     */
404 6
    public function getActions()
405
    {
406 6
        return $this->actions;
407
    }
408
409
    /**
410
     * @return array
411
     */
412 1
    public function getActionNames()
413
    {
414 1
        return array_keys($this->actions);
415
    }
416
417
    /**
418
     * @param $name
419
     * @return ActionInterface
420
     * @throws Exception
421
     */
422 5
    public function getAction($name)
423
    {
424 5
        if (!array_key_exists($name, $this->getActions())) {
425 1
            throw new Exception(
426 1
                "Invalid action name \"{$name}\" for admin '{$this->getName()}'. Check your configuration"
427 1
            );
428
        }
429
430 5
        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 11
    public function addAction(ActionInterface $action)
449
    {
450 11
        $this->actions[$action->getName()] = $action;
451 11
    }
452
453
    /**
454
     * @return ActionInterface
455
     * @throws Exception
456
     */
457 5
    public function getCurrentAction()
458
    {
459 5
        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 5
        return $this->currentAction;
467
    }
468
469
    /**
470
     * Return admin configuration object
471
     *
472
     * @return AdminConfiguration
473
     */
474 9
    public function getConfiguration()
475
    {
476 9
        return $this->configuration;
477
    }
478
}
479