Passed
Pull Request — master (#5329)
by Angel Fernando Quiroz
09:42
created

UserRelUserStateProcessor   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 38
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 31 4
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\State;
8
9
use ApiPlatform\Metadata\Operation;
10
use ApiPlatform\Metadata\Put;
11
use ApiPlatform\State\ProcessorInterface;
12
use Chamilo\CoreBundle\Entity\UserRelUser;
13
use Doctrine\ORM\EntityManagerInterface;
14
15
final class UserRelUserStateProcessor implements ProcessorInterface
16
{
17
    public function __construct(
18
        private readonly ProcessorInterface $persistProcessor,
19
        private readonly EntityManagerInterface $entityManager,
20
    ) {}
21
22
    public function process($data, Operation $operation, array $uriVariables = [], array $context = []): UserRelUser
23
    {
24
        $result = $this->persistProcessor->process($data, $operation, $uriVariables, $context);
25
26
        assert($result instanceof UserRelUser);
27
28
        if ($operation instanceof Put) {
29
            if (UserRelUser::USER_RELATION_TYPE_FRIEND === $data->getRelationType()) {
30
                $repo = $this->entityManager->getRepository(UserRelUser::class);
31
                // Check if the inverse connection is a friend request.
32
                $connection = $repo->findOneBy(
33
                    [
34
                        'user' => $data->getFriend(),
35
                        'friend' => $data->getUser(),
36
                        'relationType' => UserRelUser::USER_RELATION_TYPE_FRIEND,
37
                    ]
38
                );
39
40
                if (null === $connection) {
41
                    $connection = (new UserRelUser())
42
                        ->setUser($data->getFriend())
43
                        ->setFriend($data->getUser())
44
                        ->setRelationType(UserRelUser::USER_RELATION_TYPE_FRIEND)
45
                    ;
46
                    $this->entityManager->persist($connection);
47
                    $this->entityManager->flush();
48
                }
49
            }
50
        }
51
52
        return $result;
53
    }
54
}
55