DBALUserRepository::addUsers()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 10
rs 9.4286
ccs 9
cts 9
cp 1
cc 2
eloc 7
nc 2
nop 0
crap 2
1
<?php
2
3
namespace OpenTribes\Core\Silex\Repository;
4
5
6
use OpenTribes\Core\Entity\UserEntity;
7
use OpenTribes\Core\Repository\UserRepository;
8
use PDO;
9
use stdClass;
10
use DateTime;
11
12
class DBALUserRepository extends DBALRepository implements UserRepository, WritableRepository
13
{
14
    /**
15
     * @var UserEntity[]
16
     */
17
    private $users = [];
18
19
    /**
20
     * @param $username
21
     * @return UserEntity | null
22
     */
23 25
    public function findByUsername($username)
24
    {
25 25
        foreach ($this->users as $user) {
26 14
            if ($user->getUsername() === $username) {
27 2
                return $user;
28
            }
29 23
        }
30 23
        $sql = $this->getSql();
31 23
        $sql .= ' WHERE username = :username';
32
33 23
        $parameters = [':username' => $username];
34 23
        return $this->loadOne($sql, $parameters);
35
    }
36
37
    /**
38
     * @param $email
39
     * @return UserEntity | null
40
     */
41 15
    public function findByEmail($email)
42
    {
43 15
        foreach ($this->users as $user) {
44 13
            if ($user->getEmail() === $email) {
45 1
                return $user;
46
            }
47 14
        }
48 14
        $sql = $this->getSql();
49 14
        $sql .= ' WHERE email = :email';
50 14
        $parameters = [':email' => $email];
51 14
        return $this->loadOne($sql, $parameters);
52
    }
53
54 19
    public function getUniqueId()
55
    {
56 19
        $result = $this->connection->prepare("SELECT MAX(userId) FROM users");
57 19
        $result->execute();
58 19
        $row = $result->fetchColumn();
59 19
        $row += count($this->users);
60 19
        return (int)($row + 1);
61
    }
62
63
    /**
64
     * @param $userId
65
     * @param $username
66
     * @param $passwordHash
67
     * @param $email
68
     * @return UserEntity
69
     */
70 19
    public function create($userId, $username, $passwordHash, $email)
71
    {
72 19
        $userEntity = new UserEntity($userId, $username, $passwordHash, $email);
73 19
        return $userEntity;
74
    }
75
76 2
    public function delete(UserEntity $user)
77
    {
78 2
        $id = $user->getUserId();
79 2
        $this->markAsDeleted($id);
80 2
    }
81
82 19
    public function add(UserEntity $user)
83
    {
84 19
        $id = $user->getUserId();
85 19
        $this->users[$id] = $user;
86 19
        $this->markAsAdded($id);
87 19
    }
88
89 4
    public function modify(UserEntity $user)
90
    {
91 4
        $id = $user->getUserId();
92 4
        $this->users[$id] = $user;
93 4
        $this->markAsModified($id);
94 4
    }
95
96 9
    private function deleteUsers()
97
    {
98 9
        foreach ($this->getDeleted() as $deletedId) {
99 2
            $this->connection->delete('users', ['userId' => $deletedId]);
100 2
            $this->reset($deletedId);
101 9
        }
102 9
    }
103
104 10
    private function addUsers()
105
    {
106 10
        foreach ($this->getAdded() as $addedId) {
107 5
            $userEntity = $this->users[$addedId];
108 5
            $userEntity->setRegistrationDate(new DateTime());
109 5
            $userEntity->setLastAction(new DateTime());
110 5
            $this->connection->insert('users', $this->entityToRow($userEntity));
111 5
            $this->reset($addedId);
112 9
        }
113 9
    }
114
115 9
    private function modifyUsers()
116
    {
117 9
        foreach ($this->getModified() as $modifiedId) {
118 1
            $userEntity = $this->users[$modifiedId];
119 1
            $userEntity->setLastAction(new DateTime());
120 1
            $this->connection->update('users', $this->entityToRow($userEntity), ['userId' => $modifiedId]);
121 1
            $this->reset($modifiedId);
122 9
        }
123 9
    }
124
125 9
    public function sync()
126
    {
127 9
        $this->deleteUsers();
128 9
        $this->addUsers();
129 9
        $this->modifyUsers();
130 9
        $this->users = [];
131 9
        return true;
132
    }
133
134 4
    public function truncate()
135
    {
136 4
        $this->connection->query('TRUNCATE TABLE users');
137 4
    }
138
139 5
    private function entityToRow(UserEntity $entity)
140
    {
141
        $row = [
142 5
            'userId' => $entity->getUserId(),
143 5
            'username' => $entity->getUsername(),
144 5
            'password' => $entity->getPasswordHash(),
145 5
            'email' => $entity->getEmail(),
146 5
            'registered' => $entity->getRegistrationDate()->format('Y-m-d H:i:s')
147 5
        ];
148 5
        if ($entity->getLastAction()) {
149 5
            $row['lastAction'] = $entity->getLastAction()->format('Y-m-d H:i:s');
150 5
        }
151 5
        return $row;
152
    }
153
154 4
    private function rowToEntity(stdClass $row)
155
    {
156 4
        $userEntity = new UserEntity((int)$row->userId, $row->username, $row->password, $row->email);
157 4
        $registrationDate = DateTime::createFromFormat('Y-m-d H:i:s', $row->registered);
158 4
        if ($registrationDate) {
159 4
            $userEntity->setRegistrationDate($registrationDate);
160 4
        }
161 4
        $userEntity->setLastAction(new DateTime());
162 4
        return $userEntity;
163
    }
164
165 25
    private function getSql()
166
    {
167 25
        $sql = "SELECT userId,username,password,email,registered,lastAction,lastLogin FROM users";
168 25
        return $sql;
169
    }
170
171
    /**
172
     * @param $sql
173
     * @param $parameters
174
     * @return null|UserEntity
175
     * @throws \Doctrine\DBAL\DBALException
176
     */
177 25
    private function loadOne($sql, $parameters)
178
    {
179 25
        $statement = $this->connection->prepare($sql);
180 25
        $statement->execute($parameters);
181 25
        $this->logger->info("Executing SQL query", ['query' => $sql, 'parameters' => $parameters]);
182 25
        $result = $statement->fetch(PDO::FETCH_OBJ);
183 25
        if (!$result) {
184 22
            return null;
185
        }
186 4
        $user = $this->rowToEntity($result);
187 4
        $this->modify($user);
188 4
        return $user;
189
    }
190
}