Passed
Push — master ( 50ceb2...ce9491 )
by Angel Fernando Quiroz
13:40 queued 05:22
created

UsergroupPostStateProcessor::process()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 4
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chamilo\CoreBundle\State;
6
7
use ApiPlatform\Metadata\Operation;
8
use ApiPlatform\State\ProcessorInterface;
9
use Chamilo\CoreBundle\Entity\Usergroup;
10
use Chamilo\CoreBundle\Entity\UsergroupRelUser;
11
use Doctrine\ORM\EntityManagerInterface;
12
use Symfony\Bundle\SecurityBundle\Security;
13
use Symfony\Component\HttpFoundation\RequestStack;
14
15
final class UsergroupPostStateProcessor implements ProcessorInterface
16
{
17
    private ProcessorInterface $processor;
18
    private EntityManagerInterface $entityManager;
19
    private Security $security;
20
    private RequestStack $requestStack;
21
22
    public function __construct(
23
        ProcessorInterface $processor,
24
        EntityManagerInterface $entityManager,
25
        Security $security,
26
        RequestStack $requestStack
27
    ) {
28
        $this->processor = $processor;
29
        $this->entityManager = $entityManager;
30
        $this->security = $security;
31
        $this->requestStack = $requestStack;
32
    }
33
34
    public function process($data, Operation $operation, array $uriVariables = [], array $context = [])
35
    {
36
        /** @var Usergroup $usergroup */
37
        $usergroup = $this->processor->process($data, $operation, $uriVariables, $context);
38
39
        if ($usergroup instanceof Usergroup) {
0 ignored issues
show
introduced by
$usergroup is always a sub-type of Chamilo\CoreBundle\Entity\Usergroup.
Loading history...
40
            $this->associateCurrentUser($usergroup);
41
            $this->entityManager->flush();
42
        }
43
44
        return $usergroup;
45
    }
46
47
    private function associateCurrentUser(Usergroup $usergroup): void
48
    {
49
        $currentUser = $this->security->getUser();
50
        if ($currentUser) {
51
            $usergroupRelUser = new UsergroupRelUser();
52
            $usergroupRelUser->setUsergroup($usergroup);
53
            $usergroupRelUser->setUser($currentUser);
54
            $usergroupRelUser->setRelationType(Usergroup::GROUP_USER_PERMISSION_ADMIN);
55
56
            $this->entityManager->persist($usergroupRelUser);
57
        }
58
    }
59
}
60