UserFactory   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 5
dl 0
loc 63
rs 10
c 0
b 0
f 0
ccs 0
cts 21
cp 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B findOrCreateFromDTO() 0 25 6
A findOrCreateFromDTOArray() 0 12 2
1
<?php
2
3
namespace Skobkin\Bundle\PointToolsBundle\Service\Factory;
4
5
use Psr\Log\LoggerInterface;
6
use Skobkin\Bundle\PointToolsBundle\DTO\Api\User as UserDTO;
7
use Skobkin\Bundle\PointToolsBundle\Entity\User;
8
use Skobkin\Bundle\PointToolsBundle\Repository\UserRepository;
9
use Skobkin\Bundle\PointToolsBundle\Exception\Factory\InvalidUserDataException;
10
11
class UserFactory extends AbstractFactory
12
{
13
    public const DATE_FORMAT = 'Y-m-d_H:i:s';
14
15
    /** @var UserRepository */
16
    private $userRepository;
17
18
19
    public function __construct(LoggerInterface $logger, UserRepository $userRepository)
20
    {
21
        parent::__construct($logger);
22
        $this->userRepository = $userRepository;
23
    }
24
25
    /**
26
     * @param UserDTO $userData
27
     *
28
     * @return User
29
     *
30
     * @throws InvalidUserDataException
31
     */
32
    public function findOrCreateFromDTO(UserDTO $userData): User
33
    {
34
        // @todo LOG
35
36
        if (!$userData->isValid()) {
37
            throw new InvalidUserDataException('Invalid user data', $userData);
38
        }
39
40
        /** @var User $user */
41
        if (null === ($user = $this->userRepository->find($userData->getId()))) {
42
            $user = new User(
43
                $userData->getId(),
44
                \DateTime::createFromFormat('Y-m-d_H:i:s', $userData->getCreated()) ?: new \DateTime()
45
            );
46
            $this->userRepository->add($user);
47
        }
48
49
        $user->updateLoginAndName($userData->getLogin(), $userData->getName());
50
51
        if (null !== $userData->getDenyAnonymous() && null !== $userData->getPrivate()) {
52
            $user->updatePrivacy(!$userData->getDenyAnonymous(), $userData->getPrivate());
53
        }
54
55
        return $user;
56
    }
57
58
    /**
59
     * @return User[]
60
     */
61
    public function findOrCreateFromDTOArray(array $usersData): array
62
    {
63
        // @todo LOG
64
65
        $result = [];
66
67
        foreach ($usersData as $userData) {
68
            $result[] = $this->findOrCreateFromDTO($userData);
69
        }
70
71
        return $result;
72
    }
73
}