Passed
Pull Request — master (#42)
by Rafael
04:36
created

Users::initialize()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 81
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 55
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 56
nc 1
nop 0
dl 0
loc 81
ccs 55
cts 55
cp 1
crap 1
rs 8.9599
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
declare(strict_types=1);
3
4
namespace Gewaer\Models;
5
6
use Gewaer\Traits\PermissionsTrait;
7
use Gewaer\Traits\SubscriptionPlanLimitTrait;
8
use Phalcon\Cashier\Billable;
9
use Gewaer\Exception\ServerErrorHttpException;
10
use Exception;
11
use Carbon\Carbon;
12
use Phalcon\Validation;
13
use Phalcon\Validation\Validator\Email;
14
use Phalcon\Validation\Validator\PresenceOf;
15
use Phalcon\Validation\Validator\Regex;
16
use Phalcon\Validation\Validator\Uniqueness;
17
18
/**
19
 * Class Users
20
 *
21
 * @package Gewaer\Models
22
 *
23
 * @property Users $user
24
 * @property Config $config
25
 * @property Apps $app
26
 * @property Companies $defaultCompany
27
 * @property \Phalcon\Di $di
28
 */
29
class Users extends \Baka\Auth\Models\Users
30
{
31
    use PermissionsTrait;
32
    use Billable;
33
    use SubscriptionPlanLimitTrait;
34
35
    public $default_company_branch;
36
    public $roles_id;
37
    public $stripe_id;
38
    public $card_last_four;
39
    public $card_brand;
40
    public $trial_ends_at;
41
42
    /**
43
     * Provide the app plan id
44
     * if the user is signing up a new company
45
     *
46
     * @var integer
47
     */
48
    public $appPlanId = null;
49
50
    /**
51
     * Initialize method for model.
52
     */
53 59
    public function initialize()
54
    {
55 59
        $this->setSource('users');
56
57
        //overwrite parent relationships
58 59
        $this->hasOne('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'session']);
59 59
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
60 59
        $this->hasMany('id', 'Baka\Auth\Models\SessionKeys', 'users_id', ['alias' => 'sessionKeys']);
61 59
        $this->hasMany('id', 'Baka\Auth\Models\Banlist', 'users_id', ['alias' => 'bans']);
62 59
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
63 59
        $this->hasMany('id', 'Gewaer\Models\UserConfig', 'users_id', ['alias' => 'config']);
64 59
        $this->hasMany('id', 'Gewaer\Models\UserLinkedSources', 'users_id', ['alias' => 'sources']);
65 59
        $this->hasMany('id', 'Baka\Auth\Models\UsersAssociatedCompany', 'users_id', ['alias' => 'companies']);
66 59
        $this->hasOne('default_company', 'Gewaer\Models\Companies', 'id', ['alias' => 'defaultCompany']);
67 59
        $this->hasOne('default_company', 'Gewaer\Models\Companies', 'id', ['alias' => 'currentCompany']);
68
69 59
        $this->hasOne(
70 59
            'id',
71 59
            'Gewaer\Models\UserRoles',
72 59
            'users_id',
73 59
            ['alias' => 'permission']
74
        );
75
76 59
        $this->hasMany(
77 59
            'id',
78 59
            'Gewaer\Models\UserRoles',
79 59
            'users_id',
80 59
            ['alias' => 'permissions']
81
        );
82
83 59
        $this->hasManyToMany(
84 59
            'id',
85 59
            'Gewaer\Models\UserRoles',
86 59
            'users_id',
87 59
            'roles_id',
88 59
            'Gewaer\Models\Roles',
89 59
            'id',
90
            [
91 59
                'alias' => 'roles',
92
                'params' => [
93 59
                    'limit' => 1,
94 59
                    'conditions' => 'Gewaer\Models\UserRoles.apps_id = ' . $this->di->getConfig()->app->id,
95
                ]
96
            ]
97
        );
98
99 59
        $this->hasMany(
100 59
            'id',
101 59
            'Gewaer\Models\Subscription',
102 59
            'user_id',
103
            [
104 59
                'alias' => 'allSubscriptions',
105
                'params' => [
106 59
                    'conditions' => 'apps_id = ?0',
107 59
                    'bind' => [$this->di->getApp()->getId()],
108 59
                    'order' => 'id DESC'
109
                ]
110
            ]
111
        );
112
113 59
        $this->hasMany(
114 59
            'id',
115 59
            'Gewaer\Models\UsersAssociatedCompany',
116 59
            'users_id',
117
            [
118 59
                'alias' => 'companies',
119
            ]
120
        );
121
122 59
        $this->hasMany(
123 59
            'id',
124 59
            'Gewaer\Models\UserWebhooks',
125 59
            'users_id',
126 59
            ['alias' => 'userWebhook']
127
        );
128
129 59
        $this->hasMany(
130 59
            'id',
131 59
            'Gewaer\Models\FileSystem',
132 59
            'users_id',
133 59
            ['alias' => 'filesystem']
134
        );
135 59
    }
136
137
    /**
138
     * Validations and business logic
139
     */
140 3
    public function validation()
141
    {
142 3
        $validator = new Validation();
143 3
        $validator->add(
144 3
            'email',
145 3
            new Email([
146 3
                'field' => 'email',
147
                'required' => true,
148
            ])
149
        );
150
151 3
        $validator->add(
152 3
            'displayname',
153 3
            new PresenceOf([
154 3
                'field' => 'displayname',
155
                'required' => true,
156
            ])
157
        );
158
159 3
        $validator->add(
160 3
            'displayname',
161 3
            new Regex([
162 3
                'field' => 'displayname',
163 3
                'message' => _('Please use alphanumerics only.'),
164 3
                'pattern' => '/^[A-Za-z0-9_-]{1,32}$/',
165
            ])
166
        );
167
168
        // Unique values
169 3
        $validator->add(
170 3
            'email',
171 3
            new Uniqueness([
172 3
                'field' => 'email',
173 3
                'message' => _('This email already has an account.'),
174
            ])
175
        );
176
177 3
        return $this->validate($validator);
178
    }
179
180
    /**
181
     * Returns table name mapped in the model.
182
     *
183
     * @return string
184
     */
185 45
    public function getSource() : string
186
    {
187 45
        return 'users';
188
    }
189
190
    /**
191
     * Get the User key for redis
192
     *
193
     * @return string
194
     */
195
    public function getKey() : string
196
    {
197
        return $this->id;
198
    }
199
200
    /**
201
     * A company owner is the first person that register this company
202
     * This only ocurres when signing up the first time, after that all users invites
203
     * come with a default_company id attached
204
     *
205
     * @return boolean
206
     */
207 3
    public function isFirstSignup(): bool
208
    {
209 3
        return empty($this->default_company) ? true : false;
210
    }
211
212
    /**
213
     * Does the user have a role assign to him?
214
     *
215
     * @return boolean
216
     */
217 7
    public function hasRole(): bool
218
    {
219 7
        return !empty($this->roles_id) ? true : false;
220
    }
221
222
    /**
223
     * Get all of the subscriptions for the user.
224
     */
225 3
    public function subscriptions()
226
    {
227 3
        $this->hasMany(
228 3
            'id',
229 3
            'Gewaer\Models\Subscription',
230 3
            'user_id',
231
            [
232 3
                'alias' => 'subscriptions',
233
                'params' => [
234 3
                    'conditions' => 'apps_id = ?0 and companies_id = ?1',
235 3
                    'bind' => [$this->di->getApp()->getId(), $this->default_company],
236 3
                    'order' => 'id DESC'
237
                ]
238
            ]
239
        );
240
241 3
        return $this->getRelated('subscriptions');
242
    }
243
244
    /**
245
     * Strat a free trial
246
     *
247
     * @param Users $user
248
     * @return Subscription
249
     */
250 1
    public function startFreeTrial() : Subscription
251
    {
252 1
        $defaultPlan = AppsPlans::getDefaultPlan();
253
254 1
        $subscription = new Subscription();
255 1
        $subscription->user_id = $this->getId();
256 1
        $subscription->companies_id = $this->default_company;
257 1
        $subscription->apps_id = $this->di->getApp()->getId();
258 1
        $subscription->apps_plans_id = $this->di->getApp()->default_apps_plan_id;
259 1
        $subscription->name = $defaultPlan->name;
260 1
        $subscription->stripe_id = $defaultPlan->stripe_id;
261 1
        $subscription->stripe_plan = $defaultPlan->stripe_plan;
262 1
        $subscription->quantity = 1;
263 1
        $subscription->trial_ends_at = Carbon::now()->addDays($this->di->getApp()->plan->free_trial_dates)->toDateTimeString();
264
265 1
        if (!$subscription->save()) {
266
            throw new ServerErrorHttpException((string)current($this->getMessages()));
267
        }
268
269 1
        $this->trial_ends_at = $subscription->trial_ends_at;
270 1
        $this->update();
271
272 1
        return $subscription;
273
    }
274
275
    /**
276
     * Before create
277
     *
278
     * @return void
279
     */
280 3
    public function beforeCreate()
281
    {
282 3
        parent::beforeCreate();
283
284
        //this is only empty when creating a new user
285 3
        if (!$this->isFirstSignup()) {
286
            //confirm if the app reach its limit
287 2
            $this->isAtLimit();
288
        }
289
290
        //Assign admin role to the system if we dont get a specify role
291 3
        if (!$this->hasRole()) {
292 1
            $role = Roles::findFirstByName('Admins');
293 1
            $this->roles_id = $role->getId();
294
        }
295 3
    }
296
297
    /**
298
     * Get an array of the associates companies Ids
299
     *
300
     * @return array
301
     */
302 6
    public function getAssociatedCompanies(): array
303
    {
304
        return array_map(function ($company) {
305 6
            return $company['companies_id'];
306 6
        }, $this->getCompanies(['columns' => 'companies_id'])->toArray());
307
    }
308
309
    /**
310
     * What the current company the users is logged in with
311
     * in this current session?
312
     *
313
     * @return integer
314
     */
315 33
    public function currentCompanyId(): int
316
    {
317 33
        return (int) $this->default_company;
318
    }
319
320
    /**
321
     * What the current company brach the users is logged in with
322
     * in this current session?
323
     *
324
     * @return integer
325
     */
326 1
    public function currentCompanyBranchId(): int
327
    {
328 1
        return (int) $this->default_company_branch;
329
    }
330
331
    /**
332
     * What to do after the creation of a new users
333
     *  - Assign default role
334
     *
335
     * @return void
336
     */
337 3
    public function afterCreate()
338
    {
339
        //need to run it here, since we overwirte the default_company id and null this function objective
340 3
        $isFirstSignup = $this->isFirstSignup();
341
342
        /**
343
         * User signing up for a new app / plan
344
         * How do we know? well he doesnt have a default_company
345
         */
346 3
        if ($isFirstSignup) {
347 1
            $company = new Companies();
348 1
            $company->name = $this->defaultCompanyName;
349 1
            $company->users_id = $this->getId();
350
351 1
            if (!$company->save()) {
352
                throw new Exception(current($company->getMessages()));
353
            }
354
355 1
            $this->default_company = $company->getId();
356
357 1
            if (!$this->update()) {
358
                throw new ServerErrorHttpException((string) current($this->getMessages()));
359
            }
360
361 1
            $this->default_company_branch = $this->defaultCompany->branch->getId();
362 1
            $this->update();
363
364
            //update default subscription free trial
365 1
            $company->app->subscriptions_id = $this->startFreeTrial()->getId();
366 1
            $company->update();
367
        } else {
368
            //we have the company id
369 2
            if (empty($this->default_company_branch)) {
370
                $this->default_company_branch = $this->defaultCompany->branch->getId();
371
            }
372
        }
373
374
        //Create new company associated company
375 3
        $newUserAssocCompany = new UsersAssociatedCompany();
376 3
        $newUserAssocCompany->users_id = $this->id;
377 3
        $newUserAssocCompany->companies_id = $this->default_company;
378 3
        $newUserAssocCompany->identify_id = 1;
379 3
        $newUserAssocCompany->user_active = 1;
380 3
        $newUserAssocCompany->user_role = $this->roles_id == 1 ? 'admins' : 'users';
381
382 3
        if (!$newUserAssocCompany->save()) {
383
            throw new ServerErrorHttpException((string)current($newUserAssocCompany->getMessages()));
384
        }
385
386
        //Insert record into user_roles
387 3
        $userRole = new UserRoles();
388 3
        $userRole->users_id = $this->id;
389 3
        $userRole->roles_id = $this->roles_id;
390 3
        $userRole->apps_id = $this->di->getApp()->getId();
391 3
        $userRole->companies_id = $this->default_company;
392
393 3
        if (!$userRole->save()) {
394
            throw new ServerErrorHttpException((string)current($userRole->getMessages()));
395
        }
396
397
        //update user activity when its not a empty user
398 3
        if (!$isFirstSignup) {
399 2
            $this->updateAppActivityLimit();
400
        }
401 3
    }
402
}
403