Completed
Pull Request — development (#720)
by Thomas
24:05
created

UserRepository::getEntityFromDatabaseArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 53
rs 9.0254
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php 
2
3
use Doctrine\DBAL\Connection;
4
use Oc\Repository\Exception\RecordAlreadyExistsException;
5
use Oc\Repository\Exception\RecordNotFoundException;
6
use Oc\Repository\Exception\RecordNotPersistedException;
7
use Oc\Repository\Exception\RecordsNotFoundException;
8
9
class UserRepository
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
10
{
11
    const TABLE = 'user';
12
13
    /** @var Connection */
14
    private $connection;
15
16
    public function __construct(Connection $connection)
17
    {
18
        $this->connection = $connection;
19
    }
20
21
    /**
22
     * @return UserEntity[]
23
     */
24
    public function fetchAll()
25
    {
26
        $statement = $this->connection->createQueryBuilder()
27
                    ->select('*')
28
                    ->from(self::TABLE)
29
                    ->execute();
30
31
        $result = $statement->fetchAll();
32
33
        if ($statement->rowCount() === 0) {
34
            throw new RecordsNotFoundException('No records found');
35
        }
36
37
        $records = [];
38
39
        foreach ($result as $item) {
40
            $records[] = $this->getEntityFromDatabaseArray($item);
41
        }
42
43
        return $records;
44
    }
45
46
    /**
47
     * @param array $where
48
     * @return UserEntity
49
     */
50
    public function fetchOneBy(array $where = [])
51
    {
52
        $queryBuilder = $this->connection->createQueryBuilder()
53
                     ->select('*')
54
                     ->from(self::TABLE)
55
                     ->setMaxResults(1);
56
57
        if (count($where) > 0) {
58
            foreach ($where as $column => $value) {
59
                $queryBuilder->andWhere($column . ' = ' . $queryBuilder->createNamedParameter($value));
60
            }
61
        }
62
63
        $statement = $queryBuilder->execute();
64
65
        $result = $statement->fetch();
66
67
        if ($statement->rowCount() === 0) {
68
            throw new RecordNotFoundException('Record with given where clause not found');
69
        }
70
71
        return $this->getEntityFromDatabaseArray($result);
72
    }
73
74
    /**
75
     * @param array $where
76
     * @return UserEntity[]
77
     */
78
    public function fetchBy(array $where = [])
79
    {
80
        $queryBuilder = $this->connection->createQueryBuilder()
81
                     ->select('*')
82
                     ->from(self::TABLE);
83
84
        if (count($where) > 0) {
85
            foreach ($where as $column => $value) {
86
                $queryBuilder->andWhere($column . ' = ' . $queryBuilder->createNamedParameter($value));
87
            }
88
        }
89
90
        $statement = $queryBuilder->execute();
91
92
        $result = $statement->fetchAll();
93
94
        if ($statement->rowCount() === 0) {
95
            throw new RecordsNotFoundException('No records with given where clause found');
96
        }
97
98
        $entities = [];
99
100
        foreach ($result as $item) {
101
            $entities[] = $this->getEntityFromDatabaseArray($item);
102
        }
103
104
        return $entities;
105
    }
106
107
    /**
108
     * @param UserEntity $entity
109
     * @return UserEntity
110
     */
111
    public function create(UserEntity $entity)
112
    {
113
        if (!$entity->isNew()) {
114
            throw new RecordAlreadyExistsException('The entity does already exist.');
115
        }
116
117
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
118
119
        $this->connection->insert(
120
                    self::TABLE,
121
                    $databaseArray
122
                );
123
124
        $entity->userId = (int) $this->connection->lastInsertId();
125
126
        return $entity;
127
    }
128
129
    /**
130
     * @param UserEntity $entity
131
     * @return UserEntity
132
     */
133
    public function update(UserEntity $entity)
134
    {
135
        if ($entity->isNew()) {
136
            throw new RecordNotPersistedException('The entity does not exist.');
137
        }
138
139
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
140
141
        $this->connection->update(
142
                    self::TABLE,
143
                    $databaseArray,
144
                    ['user_id' => $entity->userId]
145
                );
146
147
        return $entity;
148
    }
149
150
    /**
151
     * @param UserEntity $entity
152
     * @return UserEntity
153
     */
154
    public function remove(UserEntity $entity)
155
    {
156
        if ($entity->isNew()) {
157
            throw new RecordNotPersistedException('The entity does not exist.');
158
        }
159
160
        $this->connection->delete(
161
                    self::TABLE,
162
                    ['user_id' => $entity->userId]
163
                );
164
165
        $entity->cacheId = null;
0 ignored issues
show
Bug introduced by
The property cacheId does not seem to exist in UserEntity.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
166
167
        return $entity;
168
    }
169
170
    /**
171
     * @param UserEntity $entity
172
     * @return []
0 ignored issues
show
Documentation introduced by
The doc-type [] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
173
     */
174
    public function getDatabaseArrayFromEntity(UserEntity $entity)
175
    {
176
        return [
177
        'user_id' => $entity->userId,
178
        'uuid' => $entity->uuid,
179
        'node' => $entity->node,
180
        'date_created' => $entity->dateCreated,
181
        'last_modified' => $entity->lastModified,
182
        'last_login' => $entity->lastLogin,
183
        'username' => $entity->username,
184
        'password' => $entity->password,
185
        'admin_password' => $entity->adminPassword,
186
        'roles' => $entity->roles,
187
        'email' => $entity->email,
188
        'email_problems' => $entity->emailProblems,
189
        'first_email_problem' => $entity->firstEmailProblem,
190
        'last_email_problem' => $entity->lastEmailProblem,
191
        'mailing_problems' => $entity->mailingProblems,
192
        'accept_mailing' => $entity->acceptMailing,
193
        'usermail_send_addr' => $entity->usermailSendAddr,
194
        'latitude' => $entity->latitude,
195
        'longitude' => $entity->longitude,
196
        'is_active_flag' => $entity->isActiveFlag,
197
        'last_name' => $entity->lastName,
198
        'first_name' => $entity->firstName,
199
        'country' => $entity->country,
200
        'pmr_flag' => $entity->pmrFlag,
201
        'new_pw_code' => $entity->newPwCode,
202
        'new_pw_date' => $entity->newPwDate,
203
        'new_email_code' => $entity->newEmailCode,
204
        'new_email_date' => $entity->newEmailDate,
205
        'new_email' => $entity->newEmail,
206
        'permanent_login_flag' => $entity->permanentLoginFlag,
207
        'watchmail_mode' => $entity->watchmailMode,
208
        'watchmail_hour' => $entity->watchmailHour,
209
        'watchmail_nextmail' => $entity->watchmailNextmail,
210
        'watchmail_day' => $entity->watchmailDay,
211
        'activation_code' => $entity->activationCode,
212
        'statpic_logo' => $entity->statpicLogo,
213
        'statpic_text' => $entity->statpicText,
214
        'no_htmledit_flag' => $entity->noHtmleditFlag,
215
        'notify_radius' => $entity->notifyRadius,
216
        'notify_oconly' => $entity->notifyOconly,
217
        'language' => $entity->language,
218
        'language_guessed' => $entity->languageGuessed,
219
        'domain' => $entity->domain,
220
        'admin' => $entity->admin,
221
        'data_license' => $entity->dataLicense,
222
        'description' => $entity->description,
223
        'desc_htmledit' => $entity->descHtmledit,
224
        ];
225
    }
226
227
    /**
228
     * @param array $data
229
     * @return UserEntity
230
     */
231
    public function getEntityFromDatabaseArray(array $data)
232
    {
233
        $entity = new UserEntity();
234
        $entity->userId = (int) $data['user_id'];
235
        $entity->uuid = (string) $data['uuid'];
236
        $entity->node = (int) $data['node'];
237
        $entity->dateCreated =  new DateTime($data['date_created']);
238
        $entity->lastModified =  new DateTime($data['last_modified']);
239
        $entity->lastLogin =  new DateTime($data['last_login']);
240
        $entity->username = (string) $data['username'];
241
        $entity->password = (string) $data['password'];
242
        $entity->adminPassword = (string) $data['admin_password'];
243
        $entity->roles = (string) $data['roles'];
244
        $entity->email = (string) $data['email'];
245
        $entity->emailProblems = (int) $data['email_problems'];
246
        $entity->firstEmailProblem =  new DateTime($data['first_email_problem']);
247
        $entity->lastEmailProblem =  new DateTime($data['last_email_problem']);
248
        $entity->mailingProblems = (int) $data['mailing_problems'];
249
        $entity->acceptMailing = (int) $data['accept_mailing'];
250
        $entity->usermailSendAddr = (int) $data['usermail_send_addr'];
251
        $entity->latitude = $data['latitude'];
252
        $entity->longitude = $data['longitude'];
253
        $entity->isActiveFlag = (int) $data['is_active_flag'];
254
        $entity->lastName = (string) $data['last_name'];
255
        $entity->firstName = (string) $data['first_name'];
256
        $entity->country = (string) $data['country'];
257
        $entity->pmrFlag = (int) $data['pmr_flag'];
258
        $entity->newPwCode = (string) $data['new_pw_code'];
259
        $entity->newPwDate =  new DateTime($data['new_pw_date']);
260
        $entity->newEmailCode = (string) $data['new_email_code'];
261
        $entity->newEmailDate =  new DateTime($data['new_email_date']);
262
        $entity->newEmail = (string) $data['new_email'];
263
        $entity->permanentLoginFlag = (int) $data['permanent_login_flag'];
264
        $entity->watchmailMode = (int) $data['watchmail_mode'];
265
        $entity->watchmailHour = (int) $data['watchmail_hour'];
266
        $entity->watchmailNextmail =  new DateTime($data['watchmail_nextmail']);
267
        $entity->watchmailDay = (int) $data['watchmail_day'];
268
        $entity->activationCode = (string) $data['activation_code'];
269
        $entity->statpicLogo = (int) $data['statpic_logo'];
270
        $entity->statpicText = (string) $data['statpic_text'];
271
        $entity->noHtmleditFlag = (int) $data['no_htmledit_flag'];
272
        $entity->notifyRadius = (int) $data['notify_radius'];
273
        $entity->notifyOconly = (int) $data['notify_oconly'];
274
        $entity->language = (string) $data['language'];
275
        $entity->languageGuessed = (int) $data['language_guessed'];
276
        $entity->domain = (string) $data['domain'];
277
        $entity->admin = $data['admin'];
278
        $entity->dataLicense = (int) $data['data_license'];
279
        $entity->description = (string) $data['description'];
280
        $entity->descHtmledit = (int) $data['desc_htmledit'];
281
282
        return $entity;
283
    }
284
}
285