Completed
Pull Request — development (#546)
by Nick
06:40
created

UserRepository::fetchOneById()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 13
nc 2
nop 1
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Oc\User;
4
5
use Doctrine\DBAL\Connection;
6
use Oc\Repository\Exception\RecordAlreadyExistsException;
7
use Oc\Repository\Exception\RecordNotFoundException;
8
use Oc\Repository\Exception\RecordNotPersistedException;
9
use Oc\Repository\Exception\RecordsNotFoundException;
10
11
/**
12
 * Class UserRepository
13
 *
14
 * @package Oc\User
15
 */
16
class UserRepository
17
{
18
    /**
19
     * Database table name that this repository maintains.
20
     *
21
     * @var string
22
     */
23
    const TABLE = 'user';
24
25
    /**
26
     * @var Connection
27
     */
28
    private $connection;
29
30
    /**
31
     * UserRepository constructor.
32
     *
33
     * @param Connection $connection
34
     */
35
    public function __construct(Connection $connection)
36
    {
37
        $this->connection = $connection;
38
    }
39
40
    /**
41
     * Fetches all users.
42
     *
43
     * @return UserEntity[]
44
     *
45
     * @throws RecordsNotFoundException Thrown when no records are found
46
     */
47 View Code Duplication
    public function fetchAll()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
48
    {
49
        $statement = $this->connection->createQueryBuilder()
50
            ->select('*')
51
            ->from(self::TABLE)
52
            ->execute();
53
54
        $result = $statement->fetchAll();
55
56
        if ($statement->rowCount() === 0) {
57
            throw new RecordsNotFoundException('No records found');
58
        }
59
60
        return $this->getEntityArrayFromDatabaseArray($result);
61
    }
62
63
    /**
64
     * Fetches a user by its id.
65
     *
66
     * @param int $id
67
     *
68
     * @return UserEntity
69
     *
70
     * @throws RecordNotFoundException Thrown when the request record is not found
71
     */
72
    public function fetchOneById($id)
73
    {
74
        $statement = $this->connection->createQueryBuilder()
75
            ->select('*')
76
            ->from(self::TABLE)
77
            ->where('user_id = :id')
78
            ->setParameter(':id', $id)
79
            ->execute();
80
81
        $result = $statement->fetch();
82
83
        if ($statement->rowCount() === 0) {
84
            throw new RecordNotFoundException(sprintf(
85
                'Record with id #%s not found',
86
                $id
87
            ));
88
        }
89
90
        return $this->getEntityFromDatabaseArray($result);
91
    }
92
93
    /**
94
     * Creates a user in the database.
95
     *
96
     * @param UserEntity $entity
97
     *
98
     * @return UserEntity
99
     *
100
     * @throws RecordAlreadyExistsException
101
     */
102
    public function create(UserEntity $entity)
103
    {
104
        if (!$entity->isNew()) {
105
            throw new RecordAlreadyExistsException('The user entity already exists');
106
        }
107
108
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
109
110
        $this->connection->insert(
111
            self::TABLE,
112
            $databaseArray
113
        );
114
115
        $entity->id = (int) $this->connection->lastInsertId();
116
117
        return $entity;
118
    }
119
120
    /**
121
     * Update a user in the database.
122
     *
123
     * @param UserEntity $entity
124
     *
125
     * @return UserEntity
126
     *
127
     * @throws RecordNotPersistedException
128
     */
129 View Code Duplication
    public function update(UserEntity $entity)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
130
    {
131
        if ($entity->isNew()) {
132
            throw new RecordNotPersistedException('The entity does not exist.');
133
        }
134
135
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
136
137
        $this->connection->update(
138
            self::TABLE,
139
            $databaseArray,
140
            ['id' => $entity->id]
141
        );
142
143
        $entity->id = (int) $this->connection->lastInsertId();
144
145
        return $entity;
146
    }
147
148
    /**
149
     * Removes a user from the database.
150
     *
151
     * @param UserEntity $entity
152
     *
153
     * @return UserEntity
154
     *
155
     * @throws RecordNotPersistedException
156
     */
157 View Code Duplication
    public function remove(UserEntity $entity)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
158
    {
159
        if ($entity->isNew()) {
160
            throw new RecordNotPersistedException('The entity does not exist.');
161
        }
162
163
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
164
165
        $this->connection->delete(
166
            self::TABLE,
167
            $databaseArray,
168
            ['id' => $entity->id]
169
        );
170
171
        $entity->id = null;
172
173
        return $entity;
174
    }
175
176
    /**
177
     * Converts database array to entity array.
178
     *
179
     * @param array $result
180
     *
181
     * @return UserEntity[]
182
     */
183
    private function getEntityArrayFromDatabaseArray(array $result)
184
    {
185
        $languages = [];
186
187
        foreach ($result as $item) {
188
            $languages[] = $this->getEntityFromDatabaseArray($item);
189
        }
190
191
        return $languages;
192
    }
193
194
    /**
195
     * Maps the given entity to the database array.
196
     *
197
     * @param UserEntity $entity
198
     *
199
     * @return array
200
     */
201
    public function getDatabaseArrayFromEntity(UserEntity $entity)
202
    {
203
        return [
204
            'user_id' => $entity->id,
205
            'username' => $entity->username,
206
            'password' => $entity->password,
207
            'email' => $entity->email,
208
            'latitude' => $entity->latitude,
209
            'longitude' => $entity->longitude,
210
            'is_active_flag' => $entity->isActive,
211
            'first_name' => $entity->firstname,
212
            'last_name' => $entity->lastname,
213
            'country' => $entity->country,
214
            'language' => $entity->language,
215
        ];
216
    }
217
218
    /**
219
     * Prepares database array from properties.
220
     *
221
     * @param array $data
222
     *
223
     * @return UserEntity
224
     */
225
    public function getEntityFromDatabaseArray(array $data)
226
    {
227
        $entity = new UserEntity();
228
        $entity->id = (int) $data['user_id'];
229
        $entity->username = (string) $data['username'];
230
        $entity->password = (string) $data['password'];
231
        $entity->email = (string) $data['email'];
232
        $entity->latitude = (double) $data['latitude'];
233
        $entity->longitude = (double) $data['longitude'];
234
        $entity->isActive = (bool) $data['is_active_flag'];
235
        $entity->firstname = (string) $data['first_name'];
236
        $entity->lastname = (string) $data['last_name'];
237
        $entity->country = (string) $data['country'];
238
        $entity->language = strtolower($data['language']);
239
240
        return $entity;
241
    }
242
}
243