Completed
Push — master ( 8f2b16...c80f65 )
by Marcel
03:24
created

UniqueUsernameValidator   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 32
ccs 0
cts 17
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
    private $userRepository;
15
16
    public function __construct(UserRepositoryInterface $userRepository) {
17
        $this->userRepository = $userRepository;
18
    }
19
20
    /**
21
     * @inheritDoc
22
     */
23
    public function validate($value, Constraint $constraint) {
24
        if(!$constraint instanceof UniqueUsername) {
25
            throw new UnexpectedTypeException($constraint, UniqueUsername::class);
26
        }
27
28
        if(!is_string($value)) {
29
            throw new UnexpectedTypeException($constraint, 'string');
30
        }
31
32
        $user = $this->userRepository->findOneByUsername($value);
33
34
        if($user !== null && $this->matchesType($user, $constraint->type) === false) {
35
            $this->context
36
                ->buildViolation($constraint->message)
37
                ->addViolation();
38
        }
39
    }
40
41
    private function matchesType(User $user, string $type) {
42
        return (get_class($user) === User::class && $type === 'user')
43
            || (get_class($user) === ActiveDirectoryUser::class && $type === 'ad');
44
    }
45
}