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

UsersTable::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 66
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

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