UserValidator::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace Sinergi\Users\User;
4
5
use Interop\Container\ContainerInterface;
6
use Sinergi\Users\Container;
7
8
class UserValidator implements UserValidatorInterface
9
{
10
    private $container;
11
12
    public function __construct(ContainerInterface $container)
13
    {
14
        if ($container instanceof Container) {
15
            $this->container = $container;
16
        } else {
17
            $this->container = new Container($container);
18
        }
19
    }
20
21
    /**
22
     * @param UserEntityInterface $user
23
     * @return array
24
     */
25
    public function __invoke(UserEntityInterface $user): array
26
    {
27
        $errors = [];
28
29
        if (empty($user->getEmail())) {
30
            $errors[1302] = 'Email is empty';
31
        } elseif (strlen($user->getEmail()) > 255) {
32
            $errors[1303] = 'Email is too long';
33
        } else {
34
            /** @var UserRepositoryInterface $userRepository */
35
            $userRepository = $this->container->get(UserRepositoryInterface::class);
36
            $userExists = $userRepository->findByEmail($user->getEmail());
37
            if ($userExists && (!$user->getId() || ($user->getId() !== $userExists->getId()))) {
38
                $errors[1300] = 'Email is already in use';
39
            }
40
        }
41
42
        if (empty($user->getPassword())) {
43
            $errors[1301] = 'Password is empty';
44
        }
45
46
        return $errors;
47
    }
48
}
49