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

NewUsernameValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
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