Passed
Push — v2 ( 5505d3...8372d3 )
by Daniel
04:27 queued 22s
created

NewUsernameValidator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 21 6
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentBundle\Validator\Constraints;
15
16
use Silverback\ApiComponentBundle\Entity\User\User;
17
use Silverback\ApiComponentBundle\Repository\User\UserRepository;
18
use Symfony\Component\Validator\Constraint;
19
use Symfony\Component\Validator\ConstraintValidator;
20
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
21
22
class NewUsernameValidator extends ConstraintValidator
23
{
24
    private $userRepository;
25
26
    public function __construct(
27
        UserRepository $userRepository
28
    ) {
29
        $this->userRepository = $userRepository;
30
    }
31
32
    public function validate($user, Constraint $constraint): void
33
    {
34
        if (!$user instanceof User) {
35
            throw new UnexpectedTypeException($user, User::class);
36
        }
37
38
        if (!$user->getUsername() || !$user->getNewUsername()) {
39
            return;
40
        }
41
        if ($user->getNewUsername() === $user->getUsername()) {
42
            $this->context->buildViolation($constraint->differentMessage)
43
                ->addViolation();
44
45
            return;
46
        }
47
48
        if ($this->userRepository->findOneBy(['username' => $user->getNewUsername()])) {
49
            $this->context->buildViolation($constraint->uniqueMessage)
50
                ->addViolation();
51
52
            return;
53
        }
54
    }
55
}
56