NewEmailAddressValidator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 38
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validate() 0 24 6
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\UserRepositoryInterface;
18
use Silverback\ApiComponentsBundle\Utility\ClassMetadataTrait;
19
use Symfony\Component\Validator\Constraint;
20
use Symfony\Component\Validator\ConstraintValidator;
21
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
22
23
/**
24
 * @author Daniel West <[email protected]>
25
 */
26
class NewEmailAddressValidator extends ConstraintValidator
27
{
28
    use ClassMetadataTrait;
29
30
    private UserRepositoryInterface $userRepository;
31
32 5
    public function __construct(UserRepositoryInterface $userRepository)
33
    {
34 5
        $this->userRepository = $userRepository;
35
    }
36
37
    /**
38
     * @param NewEmailAddress $constraint
39
     */
40 5
    public function validate($user, Constraint $constraint): void
41
    {
42 5
        if (!$user instanceof AbstractUser) {
43 1
            throw new UnexpectedTypeException($user, AbstractUser::class);
44
        }
45
46 4
        if (!$user->getNewEmailAddress()) {
47 1
            return;
48
        }
49
50 3
        if ($user->isEmailAddressVerified() && $user->getNewEmailAddress() === $user->getEmailAddress()) {
51 1
            $this->context->buildViolation($constraint->message)
52 1
                ->atPath('newEmailAddress')
53 1
                ->addViolation();
54
55 1
            return;
56
        }
57
58 3
        if ($this->userRepository->findExistingUserByNewEmail($user)) {
59 1
            $this->context->buildViolation($constraint->uniqueMessage)
60 1
                ->atPath('newEmailAddress')
61 1
                ->addViolation();
62
63 1
            return;
64
        }
65
    }
66
}
67