Completed
Pull Request — master (#178)
by Fèvre
10:47 queued 04:57
created

UsersTable::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 54
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 9.6716
c 0
b 0
f 0
cc 1
eloc 39
nc 1
nop 1

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
namespace App\Model\Table;
3
4
use Cake\ORM\Query;
5
use Cake\ORM\Table;
6
use Cake\Validation\Validator;
7
8
class UsersTable extends Table
9
{
10
11
    /**
12
     * Initialize method.
13
     *
14
     * @param array $config The configuration for the Table.
15
     *
16
     * @return void
17
     */
18
    public function initialize(array $config)
19
    {
20
        $this->table('users');
21
        $this->displayField('username');
22
        $this->primaryKey('id');
23
24
        $this->addBehavior('Timestamp');
25
        $this->addBehavior('Xety/Cake3Upload.Upload', [
26
            'fields' => [
27
                'avatar' => [
28
                    'path' => 'upload/avatar/:id/:md5',
29
                    'overwrite' => true,
30
                    'prefix' => '../',
31
                    'defaultFile' => 'avatar.png'
32
                ]
33
            ]
34
        ]);
35
        $this->addBehavior('Acl.Acl', [
36
            'type' => 'requester',
37
            'enabled' => false
38
        ]);
39
40
        $this->hasMany('BlogArticles', [
41
            'foreignKey' => 'user_id',
42
            'dependent' => true,
43
            'cascadeCallbacks' => true
44
        ]);
45
        $this->hasMany('BlogArticlesComments', [
46
            'foreignKey' => 'user_id',
47
            'dependent' => true,
48
            'cascadeCallbacks' => true
49
        ]);
50
        $this->hasMany('BlogArticlesLikes', [
51
            'foreignKey' => 'user_id',
52
            'dependent' => true,
53
            'cascadeCallbacks' => true
54
        ]);
55
        $this->hasMany('BadgesUsers', [
56
            'foreignKey' => 'user_id',
57
            'dependent' => true,
58
            'cascadeCallbacks' => true
59
        ]);
60
        $this->belongsTo('Groups', [
61
            'foreignKey' => 'group_id'
62
        ]);
63
        $this->hasMany('Notifications', [
64
            'foreignKey' => 'user_id',
65
            'dependent' => true,
66
            'cascadeCallbacks' => true
67
        ]);
68
        $this->hasMany('Conversations', [
69
            'foreignKey' => 'user_id'
70
        ]);
71
    }
72
73
    /**
74
     * Create validation rules.
75
     *
76
     * @param \Cake\Validation\Validator $validator The Validator instance.
77
     *
78
     * @return \Cake\Validation\Validator
79
     */
80
    public function validationCreate(Validator $validator)
81
    {
82
        $validator
83
            ->notEmpty('username', __("You must set an username"))
84
            ->add('username', [
85
                'unique' => [
86
                    'rule' => 'validateUnique',
87
                    'provider' => 'table',
88
                    'message' => __("This username is already used.")
89
                ],
90
                'alphanumeric' => [
91
                    'rule' => ['custom', '#^[A-Za-z0-9]+$#'],
92
                    'message' => __("Only alphanumeric characters.")
93
                ],
94
                'lengthBetween' => [
95
                    'rule' => ['lengthBetween', 4, 20],
96
                    'message' => __("Your username must be between {0} and {1} characters.", 4, 20)
97
                ]
98
            ])
99
            ->notEmpty('password', __("You must specify your password."))
100
            ->notEmpty('password_confirm', __("You must specify your password (confirmation)."))
101
            ->add('password_confirm', [
102
                'lengthBetween' => [
103
                    'rule' => ['lengthBetween', 8, 20],
104
                    'message' => __("Your password (confirmation) must be between {0} and {1} characters.", 8, 20)
105
                ],
106
                'equalToPassword' => [
107
                    'rule' => function ($value, $context) {
108
                        return $value === $context['data']['password'];
109
                    },
110
                    'message' => __("Your password confirm must match with your password.")
111
                ]
112
            ])
113
            ->notEmpty('email')
114
            ->add('email', [
115
                'unique' => [
116
                    'rule' => 'validateUnique',
117
                    'provider' => 'table',
118
                    'message' => __("This E-mail is already used.")
119
                ],
120
                'email' => [
121
                    'rule' => 'email',
122
                    'message' => __("You must specify a valid E-mail address.")
123
                ]
124
            ]);
125
126
        return $validator;
127
    }
128
129
    /**
130
     * Account validation rules.
131
     *
132
     * @param \Cake\Validation\Validator $validator The Validator instance.
133
     *
134
     * @return \Cake\Validation\Validator
135
     */
136
    public function validationAccount(Validator $validator)
137
    {
138
        return $validator
139
            ->provider('upload', 'App\Model\Validation\UploadValidator')
140
            ->provider('purifier', 'App\Model\Validation\PurifierValidator')
141
            ->allowEmpty('first_name')
142
            ->add('first_name', 'maxLength', [
143
                'rule' => ['maxLength', 100],
144
                'message' => __("Your First Name can not contain more than {0} characters.", 100)
145
            ])
146
            ->allowEmpty('last_name')
147
            ->add('last_name', 'maxLength', [
148
                'rule' => ['maxLength', 100],
149
                'message' => __("Your Last Name can not contain more than {0} characters.", 100)
150
            ])
151
            ->allowEmpty('avatar_file')
152
            ->add('avatar_file', [
153
                'mimeType' => [
154
                    'rule' => ['mimeType', ['image/jpeg', 'image/png']],
155
                    'message' => __("The mimeType is not allowed."),
156
                    'on' => function ($context) {
157
                            return !empty($context['data']['avatar_file']['name']);
158
                    }
159
                ],
160
                'fileExtension' => [
161
                    'rule' => ['extension', ['jpg', 'jpeg', 'png']],
162
                    'message' => __("The extensions allowed are {0}.", '.jpg, .jpeg and .png'),
163
                    'on' => function ($context) {
164
                            return !empty($context['data']['avatar_file']['name']);
165
                    }
166
                ],
167
                'fileSize' => [
168
                    'rule' => ['fileSize', '<', '500KB'],
169
                    'message' => __("The file exceeded the max allowed size of {0}", '500KB'),
170
                    'on' => function ($context) {
171
                            return !empty($context['data']['avatar_file']['name']);
172
                    }
173
                ],
174
                'maxDimension' => [
175
                    'rule' => ['maxDimension', 230, 230],
176
                    'provider' => 'upload',
177
                    'message' => __(
178
                        "The file exceeded the max allowed dimension. Max height : {0} Max width : {1}",
179
                        230,
180
                        230
181
                    ),
182
                ]
183
            ])
184
            ->allowEmpty('facebook')
185
            ->add('facebook', 'maxLength', [
186
                'rule' => ['maxLength', 200],
187
                'message' => __("Your Facebook can not contain more than {0} characters.", 200)
188
            ])
189
            ->allowEmpty('twitter')
190
            ->add('twitter', 'maxLength', [
191
                'rule' => ['maxLength', 200],
192
                'message' => __("Your Twitter can not contain more than {0} characters.", 200)
193
            ])
194
            ->allowEmpty('biography')
195
            ->add('biography', [
196
                'purifierMaxLength' => [
197
                    'rule' => ['purifierMaxLength', 3000],
198
                    'provider' => 'purifier',
199
                    'message' => __('Your biography can not contain more than {0} characters.', 3000)
200
                ]
201
            ])
202
            ->allowEmpty('signature')
203
            ->add('signature', [
204
                'purifierMaxLength' => [
205
                    'rule' => ['purifierMaxLength', 300],
206
                    'provider' => 'purifier',
207
                    'message' => __('Your biography can not contain more than {0} characters.', 300)
208
                ]
209
            ]);
210
    }
211
212
    /**
213
     * Settings validation rules.
214
     *
215
     * @param \Cake\Validation\Validator $validator The Validator instance.
216
     *
217
     * @return \Cake\Validation\Validator
218
     */
219
    public function validationSettings(Validator $validator)
220
    {
221
        return $validator
222
            ->notEmpty('email', __("Your E-mail can not be empty."))
223
            ->add('email', [
224
                'email' => [
225
                    'rule' => 'email',
226
                    'message' => __("You must specify a valid E-mail address.")
227
                ],
228
                'unique' => [
229
                    'rule' => 'validateUnique',
230
                    'provider' => 'table',
231
                    'message' => __("This E-mail is already used, please choose another E-mail.")
232
                ],
233
            ])
234
            ->notEmpty('password', __("You must specify your new password."))
235
            ->notEmpty('password_confirm', __("You must specify your password (confirmation)."))
236
            ->add('password_confirm', [
237
                'lengthBetween' => [
238
                    'rule' => ['lengthBetween', 8, 20],
239
                    'message' => __("Your password (confirmation) must be between {0} and {1} characters.", 8, 20)
240
                ],
241
                'equalToPassword' => [
242
                    'rule' => function ($value, $context) {
243
                            return $value === $context['data']['password'];
244
                    },
245
                    'message' => __("Your password confirm must match with your new password")
246
                ]
247
            ]);
248
    }
249
250
    /**
251
     * ResetPassword validation rules.
252
     *
253
     * @param \Cake\Validation\Validator $validator The Validator instance.
254
     *
255
     * @return \Cake\Validation\Validator
256
     */
257
    public function validationResetpassword(Validator $validator)
258
    {
259
        return $validator
260
            ->notEmpty('password', __("You must specify your new password."))
261
            ->notEmpty('password_confirm', __("You must specify your password (confirmation)."))
262
            ->add('password_confirm', [
263
                'lengthBetween' => [
264
                    'rule' => ['lengthBetween', 8, 20],
265
                    'message' => __("Your password (confirmation) must be between {0} and {1} characters.", 8, 20)
266
                ],
267
                'equalToPassword' => [
268
                    'rule' => function ($value, $context) {
269
                            return $value === $context['data']['password'];
270
                    },
271
                    'message' => __("Your password confirm must match with your new password")
272
                ]
273
            ]);
274
    }
275
276
    /**
277
     * Update validation rules. (Administration)
278
     *
279
     * @param \Cake\Validation\Validator $validator The Validator instance.
280
     *
281
     * @return \Cake\Validation\Validator
282
     */
283
    public function validationUpdate(Validator $validator)
284
    {
285
        $validator
286
            ->requirePresence('username', 'update')
287
            ->notEmpty('username', __("You must set an username"))
288
            ->add('username', [
289
                'unique' => [
290
                    'rule' => 'validateUnique',
291
                    'provider' => 'table',
292
                    'message' => __("This username is already used.")
293
                ],
294
                'alphanumeric' => [
295
                    'rule' => ['custom', '#^[A-Za-z0-9]+$#'],
296
                    'message' => __("Only alphanumeric characters.")
297
                ],
298
                'lengthBetween' => [
299
                    'rule' => ['lengthBetween', 4, 20],
300
                    'message' => __("Your username must be between {0} and {1} characters.", 4, 20)
301
                ]
302
            ])
303
            ->requirePresence('email', 'update')
304
            ->notEmpty('email')
305
            ->add('email', [
306
                'unique' => [
307
                    'rule' => 'validateUnique',
308
                    'provider' => 'table',
309
                    'message' => __("This E-mail is already used.")
310
                ],
311
                'email' => [
312
                    'rule' => 'email',
313
                    'message' => __("You must specify a valid E-mail address.")
314
                ]
315
            ]);
316
317
        return $validator;
318
    }
319
320
    /**
321
     * Custom finder for select only the required fields.
322
     *
323
     * @param \Cake\ORM\Query $query The query finder.
324
     *
325
     * @return \Cake\ORM\Query
326
     */
327
    public function findShort(Query $query)
328
    {
329
        return $query->select([
330
            'id',
331
            'first_name',
332
            'last_name',
333
            'username'
334
        ]);
335
    }
336
337
    /**
338
     * Custom finder for select the required fields and avatar.
339
     *
340
     * @param \Cake\ORM\Query $query The query finder.
341
     *
342
     * @return \Cake\ORM\Query
343
     */
344
    public function findMedium(Query $query)
345
    {
346
        return $query->select([
347
            'id',
348
            'first_name',
349
            'last_name',
350
            'username',
351
            'avatar'
352
        ]);
353
    }
354
355
    /**
356
     * Custom finder for select full fields.
357
     *
358
     * @param \Cake\ORM\Query $query The query finder.
359
     *
360
     * @return \Cake\ORM\Query
361
     */
362
    public function findFull(Query $query)
363
    {
364
        return $query->select([
365
            'id',
366
            'first_name',
367
            'last_name',
368
            'username',
369
            'avatar',
370
            'group_id',
371
            'blog_articles_comment_count',
372
            'blog_article_count',
373
            'facebook',
374
            'twitter',
375
            'signature',
376
            'created',
377
            'last_login'
378
        ]);
379
    }
380
}
381