Test Failed
Push — develop ( 28e0cd...307ddb )
by Daniel
05:05
created

NewUsernameValidator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 13
dl 0
loc 25
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 16 4
1
<?php
2
3
namespace Silverback\ApiComponentBundle\Validator\Constraints;
4
5
use Silverback\ApiComponentBundle\Entity\User\User;
6
use Silverback\ApiComponentBundle\Repository\User\UserRepository;
7
use Symfony\Component\Validator\Constraint;
8
use Symfony\Component\Validator\ConstraintValidator;
9
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
10
11
class NewUsernameValidator extends ConstraintValidator
12
{
13
    private $userRepository;
14
    public function __construct(
15
        UserRepository $userRepository
16
    ) {
17
        $this->userRepository = $userRepository;
18
    }
19
20
    public function validate($user, Constraint $constraint): void
21
    {
22
        if (!$user instanceof User) {
23
            throw new UnexpectedTypeException($user, User::class);
24
        }
25
26
        if ($user->getNewUsername() === $user->getUsername()) {
27
            $this->context->buildViolation($constraint->differentMessage)
28
                ->addViolation();
29
            return;
30
        }
31
32
        if ($this->userRepository->findOneBy(['username' => $user->getNewUsername()])) {
33
            $this->context->buildViolation($constraint->uniqueMessage)
34
                ->addViolation();
35
            return;
36
        }
37
    }
38
}
39