Completed
Push — master ( 97d2bc...038e4e )
by Tomáš
12:56
created

RoleControllerSubscriber::addResources()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
1
<?php
2
3
namespace Webcook\Cms\SecurityBundle\EventSubscriber;
4
5
use ApiPlatform\Core\EventListener\EventPriorities;
6
use Webcook\Cms\SecurityBundle\Entity\Role;
7
use Webcook\Cms\SecurityBundle\Entity\RoleResource;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
10
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
11
use Symfony\Component\HttpKernel\KernelEvents;
12
13
final class RoleControllerSubscriber implements EventSubscriberInterface
14
{
15
    private $em;
16
17
    public function __construct($em)
18
    {
19
        $this->em = $em;
20
    }
21
22
    public static function getSubscribedEvents()
23
    {
24
        return [
25
            KernelEvents::VIEW => [['postWrite', EventPriorities::POST_WRITE]],
26
        ];
27
    }
28
29
    public function postWrite(GetResponseForControllerResultEvent $event)
30
    {
31
        $role   = $event->getControllerResult();
32
        $method = $event->getRequest()->getMethod();
33
34
        if (!$role instanceof Role) {
35
            return;
36
        }
37
38
        if ($method == 'POST') {
39
            $this->addResources($role);
40
        }
41
    }
42
43
    /**
44
     * Add all resources from the system.
45
     *
46
     * @param Role $role
47
     */
48
    private function addResources(Role $role)
49
    {
50
        $resources = $this->em->getRepository('Webcook\Cms\SecurityBundle\Entity\Resource')->findAll();
51
        foreach ($resources as $resource) {
52
            $roleResource = new RoleResource();
53
            $roleResource->setRole($role);
54
            $roleResource->setResource($resource);
55
            $this->em->persist($roleResource);
56
        }
57
58
        $this->em->flush();
59
    }
60
}
61