Completed
Pull Request — dev (#9)
by Arnaud
02:57
created

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