Completed
Pull Request — master (#178)
by Fèvre
02:40
created

UsersTable::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 63
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

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