UniqueUsernameValidator::validate()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 9
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 15
ccs 0
cts 8
cp 0
crap 30
rs 9.6111
1
<?php
2
3
namespace App\Validator;
4
5
use App\Entity\ActiveDirectoryUser;
6
use App\Entity\User;
7
use App\Repository\UserRepositoryInterface;
8
use Symfony\Component\Validator\Constraint;
9
use Symfony\Component\Validator\ConstraintValidator;
10
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
11
12
class UniqueUsernameValidator extends ConstraintValidator {
13
14
    public function __construct(private UserRepositoryInterface $userRepository)
15
    {
16
    }
17
18
    /**
19
     * @inheritDoc
20
     */
21
    public function validate($value, Constraint $constraint) {
22
        if(!$constraint instanceof UniqueUsername) {
23
            throw new UnexpectedTypeException($constraint, UniqueUsername::class);
24
        }
25
26
        if(!is_string($value)) {
27
            throw new UnexpectedTypeException($constraint, 'string');
28
        }
29
30
        $user = $this->userRepository->findOneByUsername($value);
31
32
        if($user !== null && $this->matchesType($user, $constraint->type) === false) {
33
            $this->context
34
                ->buildViolation($constraint->message)
35
                ->addViolation();
36
        }
37
    }
38
39
    private function matchesType(User $user, string $type) {
40
        return ($user::class === User::class && $type === 'user')
41
            || ($user::class === ActiveDirectoryUser::class && $type === 'ad');
42
    }
43
}