Passed
Pull Request — master (#7302)
by Angel Fernando Quiroz
18:19 queued 07:15
created

ScimHelper::findUser()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 15
rs 10
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\Helpers;
8
9
use Chamilo\CoreBundle\Entity\ExtraField;
10
use Chamilo\CoreBundle\Entity\User;
11
use Chamilo\CoreBundle\Repository\ExtraFieldRepository;
12
use Chamilo\CoreBundle\Repository\ExtraFieldValuesRepository;
13
use Chamilo\CoreBundle\Repository\Node\UserRepository;
14
use Doctrine\ORM\NonUniqueResultException;
15
16
readonly class ScimHelper
17
{
18
    public const SCIM_FIELD = 'scim_external_id';
19
20
    public function __construct(
21
        private ExtraFieldRepository $extraFieldRepo,
22
        private ExtraFieldValuesRepository $extraFieldValuesRepo,
23
        private UserRepository $userRepo,
24
    ) {}
25
26
    private function getExtraField(): ExtraField
27
    {
28
        return $this->extraFieldRepo->findByVariable(
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->extraField...TYPE, self::SCIM_FIELD) could return the type null which is incompatible with the type-hinted return Chamilo\CoreBundle\Entity\ExtraField. Consider adding an additional type-check to rule them out.
Loading history...
29
            ExtraField::USER_FIELD_TYPE,
30
            self::SCIM_FIELD
31
        );
32
    }
33
34
    public function findUser(string $externalId): ?User
35
    {
36
        $field = $this->getExtraField();
37
38
        try {
39
            $fieldValue = $this->extraFieldValuesRepo->findByVariableAndValue($field, $externalId);
40
        } catch (NonUniqueResultException) {
41
            return null;
42
        }
43
44
        if (!$fieldValue) {
45
            return null;
46
        }
47
48
        return $this->userRepo->find($fieldValue->getItemId());
49
    }
50
51
    public function getExternalId(User $user): ?string
52
    {
53
        $fieldValue = $this->extraFieldValuesRepo->getValueByVariableAndItem(
54
            self::SCIM_FIELD,
55
            $user->getId(),
56
            ExtraField::USER_FIELD_TYPE
57
        );
58
59
        return $fieldValue?->getFieldValue();
60
    }
61
62
    public function saveExternalId(string $externalId, User $user): void
63
    {
64
        $this->extraFieldValuesRepo->updateItemData(
65
            $this->getExtraField(),
66
            $user,
67
            $externalId
68
        );
69
    }
70
}
71