UniqueUsernameValidator   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 30
ccs 0
cts 15
cp 0
rs 10
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A matchesType() 0 3 4
A __construct() 0 2 1
A validate() 0 15 5
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
}