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

UniqueUsernameValidator::validate()   A

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 10
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
    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
}