Completed
Pull Request — development (#663)
by Nick
07:42
created

UserRepository::fetchOneBy()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 24
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 4
nop 1
dl 24
loc 24
rs 8.6845
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
0 ignored issues
show
introduced by
Unexpected tag type @package in doc block
Loading history...
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
0 ignored issues
show
introduced by
Connection => \Doctrine\DBAL\Connection
Loading history...
27
     */
28
    private $connection;
29
30
    /**
31
     * UserRepository constructor.
32
     *
33
     * @param Connection $connection
0 ignored issues
show
introduced by
Connection => \Doctrine\DBAL\Connection
Loading history...
34
     */
35
    public function __construct(Connection $connection)
36
    {
37
        $this->connection = $connection;
38
    }
39
40
    /**
41
     * Fetches all users.
42
     *
43
     * @return UserEntity[]
0 ignored issues
show
introduced by
UserEntity[] => \Array\UserEntity[]
Loading history...
44
     *
45
     * @throws RecordsNotFoundException Thrown when no records are found
0 ignored issues
show
introduced by
RecordsNotFoundException => \Oc\Repository\Exception\RecordsNotFoundException
Loading history...
Coding Style introduced by
@throws tag comment must end with a full stop
Loading history...
46
     */
47
    public function fetchAll()
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
0 ignored issues
show
introduced by
UserEntity => \Array\UserEntity
Loading history...
69
     *
70
     * @throws RecordNotFoundException Thrown when the request record is not found
0 ignored issues
show
introduced by
RecordNotFoundException => \Oc\Repository\Exception\RecordNotFoundException
Loading history...
Coding Style introduced by
@throws tag comment must end with a full stop
Loading history...
71
     */
72
    public function fetchOneById($id)
73
    {
74
        return $this->fetchOneBy([
75
            'user_id' => $id
76
        ]);
77
    }
78
79
    /**
80
     * Fetches a user by given where array.
81
     *
82
     * @param array $where
83
     *
84
     * @return UserEntity|null
0 ignored issues
show
introduced by
UserEntity => \Array\UserEntity
Loading history...
85
     *
86
     * @throws RecordNotFoundException Thrown when no record is found
0 ignored issues
show
introduced by
RecordNotFoundException => \Oc\Repository\Exception\RecordNotFoundException
Loading history...
Coding Style introduced by
@throws tag comment must end with a full stop
Loading history...
87
     */
88 View Code Duplication
    public function fetchOneBy(array $where = [])
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...
89
    {
90
        $queryBuilder = $this->connection->createQueryBuilder()
91
            ->select('*')
92
            ->from(self::TABLE)
93
            ->setMaxResults(1);
94
95
96
        if (count($where) > 0) {
97
            foreach ($where as $column => $value) {
98
                $queryBuilder->andWhere($column . ' = ' .  $queryBuilder->createNamedParameter($value));
0 ignored issues
show
introduced by
Expected 1 space after ., but 2 found
Loading history...
99
            }
100
        }
101
102
        $statement = $queryBuilder->execute();
103
104
        $result = $statement->fetch();
105
106
        if ($statement->rowCount() === 0) {
107
            throw new RecordNotFoundException('Record with given where clause not found');
108
        }
109
110
        return $this->getEntityFromDatabaseArray($result);
111
    }
112
113
    /**
114
     * Creates a user in the database.
115
     *
116
     * @param UserEntity $entity
0 ignored issues
show
introduced by
UserEntity => \Array\UserEntity
Loading history...
117
     *
118
     * @return UserEntity
0 ignored issues
show
introduced by
UserEntity => \Array\UserEntity
Loading history...
119
     *
120
     * @throws RecordAlreadyExistsException
0 ignored issues
show
introduced by
RecordAlreadyExistsException => \Oc\Repository\Exception\RecordAlreadyExistsException
Loading history...
121
     */
122
    public function create(UserEntity $entity)
123
    {
124
        if (!$entity->isNew()) {
125
            throw new RecordAlreadyExistsException('The user entity already exists');
126
        }
127
128
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
129
130
        $this->connection->insert(
131
            self::TABLE,
132
            $databaseArray
133
        );
134
135
        $entity->id = (int) $this->connection->lastInsertId();
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
136
137
        return $entity;
138
    }
139
140
    /**
141
     * Update a user in the database.
142
     *
143
     * @param UserEntity $entity
0 ignored issues
show
introduced by
UserEntity => \Array\UserEntity
Loading history...
144
     *
145
     * @return UserEntity
0 ignored issues
show
introduced by
UserEntity => \Array\UserEntity
Loading history...
146
     *
147
     * @throws RecordNotPersistedException
0 ignored issues
show
introduced by
RecordNotPersistedException => \Oc\Repository\Exception\RecordNotPersistedException
Loading history...
148
     */
149 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...
150
    {
151
        if ($entity->isNew()) {
152
            throw new RecordNotPersistedException('The entity does not exist.');
153
        }
154
155
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
156
157
        $this->connection->update(
158
            self::TABLE,
159
            $databaseArray,
160
            ['user_id' => $entity->id]
161
        );
162
163
        $entity->id = (int) $this->connection->lastInsertId();
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
164
165
        return $entity;
166
    }
167
168
    /**
169
     * Removes a user from the database.
170
     *
171
     * @param UserEntity $entity
0 ignored issues
show
introduced by
UserEntity => \Array\UserEntity
Loading history...
172
     *
173
     * @return UserEntity
0 ignored issues
show
introduced by
UserEntity => \Array\UserEntity
Loading history...
174
     *
175
     * @throws RecordNotPersistedException
0 ignored issues
show
introduced by
RecordNotPersistedException => \Oc\Repository\Exception\RecordNotPersistedException
Loading history...
176
     */
177 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...
178
    {
179
        if ($entity->isNew()) {
180
            throw new RecordNotPersistedException('The entity does not exist.');
181
        }
182
183
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
184
185
        $this->connection->delete(
186
            self::TABLE,
187
            $databaseArray,
188
            ['user_id' => $entity->id]
189
        );
190
191
        $entity->id = null;
192
193
        return $entity;
194
    }
195
196
    /**
197
     * Converts database array to entity array.
198
     *
199
     * @param array $result
200
     *
201
     * @return UserEntity[]
0 ignored issues
show
introduced by
UserEntity[] => \Array\UserEntity[]
Loading history...
202
     */
203
    private function getEntityArrayFromDatabaseArray(array $result)
204
    {
205
        $languages = [];
206
207
        foreach ($result as $item) {
208
            $languages[] = $this->getEntityFromDatabaseArray($item);
209
        }
210
211
        return $languages;
212
    }
213
214
    /**
215
     * Maps the given entity to the database array.
216
     *
217
     * @param UserEntity $entity
0 ignored issues
show
introduced by
UserEntity => \Array\UserEntity
Loading history...
218
     *
219
     * @return array
220
     */
221
    public function getDatabaseArrayFromEntity(UserEntity $entity)
222
    {
223
        return [
224
            'user_id' => $entity->id,
225
            'username' => $entity->username,
226
            'password' => $entity->password,
227
            'email' => $entity->email,
228
            'latitude' => $entity->latitude,
229
            'longitude' => $entity->longitude,
230
            'is_active_flag' => $entity->isActive,
231
            'first_name' => $entity->firstname,
232
            'last_name' => $entity->lastname,
233
            'country' => $entity->country,
234
            'language' => $entity->language,
235
        ];
236
    }
237
238
    /**
239
     * Prepares database array from properties.
240
     *
241
     * @param array $data
242
     *
243
     * @return UserEntity
0 ignored issues
show
introduced by
UserEntity => \Array\UserEntity
Loading history...
244
     */
245
    public function getEntityFromDatabaseArray(array $data)
246
    {
247
        $entity = new UserEntity();
248
        $entity->id = (int) $data['user_id'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
249
        $entity->username = (string) $data['username'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
250
        $entity->password = (string) $data['password'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
251
        $entity->email = (string) $data['email'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
252
        $entity->latitude = (double) $data['latitude'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
253
        $entity->longitude = (double) $data['longitude'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
254
        $entity->isActive = (bool) $data['is_active_flag'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
255
        $entity->firstname = (string) $data['first_name'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
256
        $entity->lastname = (string) $data['last_name'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
257
        $entity->country = (string) $data['country'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
258
        $entity->language = strtolower($data['language']);
259
260
        return $entity;
261
    }
262
}
263