Passed
Push — feature/uploadable ( 7c6d25...a7ed20 )
by Daniel
11:07
created

NewEmailAddressValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 32
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 22 5
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components 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\ApiComponentsBundle\Validator\Constraints;
15
16
use Silverback\ApiComponentsBundle\Entity\User\AbstractUser;
17
use Silverback\ApiComponentsBundle\Repository\User\UserRepository;
18
use Symfony\Component\Validator\Constraint;
19
use Symfony\Component\Validator\ConstraintValidator;
20
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
21
22
/**
23
 * @author Daniel West <[email protected]>
24
 */
25
class NewEmailAddressValidator extends ConstraintValidator
26
{
27
    private UserRepository $userRepository;
28
29 5
    public function __construct(
30
        UserRepository $userRepository
31
    ) {
32 5
        $this->userRepository = $userRepository;
33 5
    }
34
35 5
    public function validate($user, Constraint $constraint): void
36
    {
37 5
        if (!$user instanceof AbstractUser) {
38 1
            throw new UnexpectedTypeException($user, AbstractUser::class);
39
        }
40
41 4
        if (!$user->getNewEmailAddress()) {
42 1
            return;
43
        }
44
45 3
        if ($user->getNewEmailAddress() === $user->getEmailAddress()) {
46 1
            $this->context->buildViolation($constraint->differentMessage)
47 1
                ->addViolation();
48
49 1
            return;
50
        }
51
52 2
        if ($this->userRepository->findOneBy(['email_address' => $user->getNewEmailAddress()])) {
53 1
            $this->context->buildViolation($constraint->uniqueMessage)
54 1
                ->addViolation();
55
56 1
            return;
57
        }
58 1
    }
59
}
60