Failed Conditions
Pull Request — master (#55)
by Rafael
06:42
created

Companies::afterCreate()   B

Complexity

Conditions 7
Paths 19

Size

Total Lines 58
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 7.0368

Importance

Changes 0
Metric Value
cc 7
eloc 32
nc 19
nop 0
dl 0
loc 58
ccs 30
cts 33
cp 0.9091
crap 7.0368
rs 8.4746
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 Phalcon\Validation;
7
use Phalcon\Validation\Validator\PresenceOf;
8
use Gewaer\Exception\ServerErrorHttpException;
9
use Exception;
10
use Carbon\Carbon;
11
use Gewaer\Traits\ModelSettingsTrait;
12
use Gewaer\Traits\UsersAssociatedTrait;
13
14
/**
15
 * Class Companies
16
 *
17
 * @package Gewaer\Models
18
 *
19
 * @property Users $user
20
 * @property Users $userData
21
 * @property DefaultCompany $default_company
22
 * @property CompaniesBranches $branch
23
 * @property CompaniesBranches $branches
24
 * @property Config $config
25
 * @property UserCompanyApps $app
26
 * @property \Phalcon\Di $di
27
 * @property Roles $roles_id
28
 */
29
class Companies extends \Gewaer\CustomFields\AbstractCustomFieldsModel
30
{
31
    use ModelSettingsTrait;
32
    use UsersAssociatedTrait;
33
34
    const DEFAULT_COMPANY = 'DefaulCompany';
35
    const PAYMENT_GATEWAY_CUSTOMER_KEY = 'payment_gateway_customer_id';
36
37
    /**
38
     *
39
     * @var integer
40
     */
41
    public $id;
42
43
    /**
44
     *
45
     * @var string
46
     */
47
    public $name;
48
49
    /**
50
     *
51
     * @var string
52
     */
53
    public $profile_image;
54
55
    /**
56
     *
57
     * @var string
58
     */
59
    public $website;
60
61
    /**
62
     *
63
     * @var integer
64
     */
65
    public $users_id;
66
67
    /**
68
     *
69
     * @var integer
70
     */
71
    public $has_activities;
72
73
    /**
74
     *
75
     * @var string
76
     */
77
    public $created_at;
78
79
    /**
80
     *
81
     * @var string
82
     */
83
    public $updated_at;
84
85
    /**
86
     *
87
     * @var integer
88
     */
89
    public $is_deleted;
90
91
    /**
92
     * Provide the app plan id
93
     *
94
     * @var integer
95
     */
96
    public $appPlanId = null;
97
98
    /**
99
     *
100
     * @var integer
101
     */
102
    public $currency_id;
103
104
    /**
105
     *
106
     * @var string
107
     */
108
    public $language;
109
110
    /**
111
     *
112
     * @var string
113
     */
114
    public $timezone;
115
116
    /**
117
     *
118
     * @var string
119
     */
120
    public $currency;
121
122
    /**
123
     * Initialize method for model.
124
     */
125 23
    public function initialize()
126
    {
127 23
        $this->setSource('companies');
128
129 23
        $this->belongsTo('users_id', 'Baka\Auth\Models\Users', 'id', ['alias' => 'user']);
130 23
        $this->hasMany('id', 'Baka\Auth\Models\CompanySettings', 'id', ['alias' => 'settings']);
131
132 23
        $this->belongsTo(
133 23
            'users_id',
134 23
            'Gewaer\Models\Users',
135 23
            'id',
136 23
            ['alias' => 'user']
137
        );
138
139 23
        $this->hasMany(
140 23
            'id',
141 23
            'Gewaer\Models\CompaniesBranches',
142 23
            'companies_id',
143 23
            ['alias' => 'branches']
144
        );
145
146 23
        $this->hasMany(
147 23
            'id',
148 23
            'Gewaer\Models\CompaniesCustomFields',
149 23
            'companies_id',
150 23
            ['alias' => 'fields']
151
        );
152
153 23
        $this->hasMany(
154 23
            'id',
155 23
            'Gewaer\CustomFields\CustomFields',
156 23
            'companies_id',
157 23
            ['alias' => 'custom-fields']
158
        );
159
160 23
        $this->hasMany(
161 23
            'id',
162 23
            'Gewaer\Models\UsersAssociatedCompanies',
163 23
            'companies_id',
164 23
            ['alias' => 'UsersAssociatedCompanies']
165
        );
166
167 23
        $this->hasMany(
168 23
            'id',
169 23
            'Gewaer\Models\UsersAssociatedApps',
170 23
            'companies_id',
171 23
            ['alias' => 'UsersAssociatedApps']
172
        );
173
174 23
        $this->hasOne(
175 23
            'id',
176 23
            'Gewaer\Models\CompaniesBranches',
177 23
            'companies_id',
178
            [
179 23
                'alias' => 'branch',
180
            ]
181
        );
182
183 23
        $this->hasOne(
184 23
            'id',
185 23
            'Gewaer\Models\UserCompanyApps',
186 23
            'companies_id',
187
            [
188 23
                'alias' => 'app',
189
                'params' => [
190 23
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId()
191
                ]
192
            ]
193
        );
194
195 23
        $this->hasOne(
196 23
            'id',
197 23
            'Gewaer\Models\UserCompanyApps',
198 23
            'companies_id',
199
            [
200 23
                'alias' => 'apps',
201
                'params' => [
202 23
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId()
203
                ]
204
            ]
205
        );
206
207 23
        $this->hasOne(
208 23
            'id',
209 23
            'Gewaer\Models\Subscription',
210 23
            'companies_id',
211
            [
212 23
                'alias' => 'subscription',
213
                'params' => [
214 23
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId() . ' AND ends_at is null AND is_deleted = 0 ',
215 23
                    'order' => 'id DESC'
216
                ]
217
            ]
218
        );
219
220 23
        $this->hasMany(
221 23
            'id',
222 23
            'Gewaer\Models\Subscription',
223 23
            'companies_id',
224
            [
225 23
                'alias' => 'subscriptions',
226
                'params' => [
227 23
                    'conditions' => 'apps_id = ' . $this->di->getApp()->getId() . ' AND is_deleted = 0',
228 23
                    'order' => 'id DESC'
229
                ]
230
            ]
231
        );
232
233 23
        $this->hasMany(
234 23
            'id',
235 23
            'Gewaer\Models\UserWebhooks',
236 23
            'companies_id',
237 23
            ['alias' => 'user-webhooks']
238
        );
239
240 23
        $systemModule = SystemModules::getSystemModuleByModelName(self::class);
241 23
        $this->hasMany(
242 23
            'id',
243 23
            'Gewaer\Models\FileSystem',
244 23
            'entity_id',
245
            [
246 23
                'alias' => 'filesystem',
247 23
                'conditions' => 'system_modules_id = ?0',
248 23
                'bind' => [$systemModule->getId()]
249
            ]
250
        );
251 23
    }
252
253
    /**
254
     * Model validation
255
     *
256
     * @return void
257
     */
258 5
    public function validation()
259
    {
260 5
        $validator = new Validation();
261
262 5
        $validator->add(
263 5
            'name',
264 5
            new PresenceOf([
265 5
                'model' => $this,
266
                'required' => true,
267
            ])
268
        );
269
270 5
        return $this->validate($validator);
271
    }
272
273
    /**
274
    * Register a company given a user and name
275
    *
276
    * @param  Users  $user
277
    * @param  string $name
278
    * @return Companies
279
    */
280
    public static function register(Users $user, string $name): Companies
281
    {
282
        $company = new self();
283
        $company->name = $name;
284
        $company->users_id = $user->getId();
285
286
        if (!$company->save()) {
287
            throw new Exception(current($company->getMessages()));
288
        }
289
290
        return $company;
291
    }
292
293
    /**
294
     * Returns table name mapped in the model.
295
     *
296
     * @return string
297
     */
298 15
    public function getSource() : string
299
    {
300 15
        return 'companies';
301
    }
302
303
    /**
304
     * Confirm if a user belongs to this current company
305
     *
306
     * @param Users $user
307
     * @return boolean
308
     */
309 2
    public function userAssociatedToCompany(Users $user): bool
310
    {
311 2
        return is_object($this->getUsersAssociatedCompanies('users_id =' . $user->getId())) ? true : false;
1 ignored issue
show
Bug introduced by
The method getUsersAssociatedCompanies() does not exist on Gewaer\Models\Companies. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

311
        return is_object($this->/** @scrutinizer ignore-call */ getUsersAssociatedCompanies('users_id =' . $user->getId())) ? true : false;
Loading history...
312
    }
313
314
    /**
315
     * Get the stripe customer id from the
316
     *
317
     * @return ?string
318
     */
319 1
    public function getPaymentGatewayCustomerId(): ?string
320
    {
321 1
        return $this->getSettings(self::PAYMENT_GATEWAY_CUSTOMER_KEY);
322
    }
323
324
    /**
325
     * Before crate company
326
     *
327
     * @return void
328
     */
329 3
    public function beforeCreate()
330
    {
331 3
        parent::beforeCreate();
332
333 3
        $this->language = $this->di->getApp()->getSettings('language');
334 3
        $this->timezone = $this->di->getApp()->getSettings('timezone');
335 3
        $this->currency_id = Currencies::findFirstByCode($this->di->getApp()->getSettings('currency'))->getId();
336 3
    }
337
338
    /**
339
     * After creating the company
340
     *
341
     * @return void
342
     */
343 3
    public function afterCreate()
344
    {
345 3
        parent::afterCreate();
346
347
        //setup the user notificatoin setting
348 3
        $this->setSettings('notifications', $this->user->email);
349
350
        //now thta we setup de company and associated with the user we need to setup this as its default company
351 3
        if (!UserConfig::findFirst(['conditions' => 'users_id = ?0 and name = ?1', 'bind' => [$this->user->getId(), self::DEFAULT_COMPANY]])) {
352 1
            $userConfig = new UserConfig();
353 1
            $userConfig->users_id = $this->user->getId();
354 1
            $userConfig->name = self::DEFAULT_COMPANY;
355 1
            $userConfig->value = $this->getId();
356
357 1
            if (!$userConfig->save()) {
358
                throw new Exception((string)current($userConfig->getMessages()));
359
            }
360
        }
361
362 3
        $this->associate($this->user, $this);
363 3
        $this->di->getApp()->associate($this->user, $this);
364
365
        /**
366
         * @var CompaniesBranches
367
         */
368 3
        $branch = new CompaniesBranches();
369 3
        $branch->companies_id = $this->getId();
370 3
        $branch->users_id = $this->user->getId();
371 3
        $branch->name = 'Default';
372 3
        $branch->is_default = 1;
373 3
        $branch->description = '';
374 3
        if (!$branch->save()) {
375
            throw new ServerErrorHttpException((string)current($branch->getMessages()));
376
        }
377
378
        //look for the default plan for this app
379 3
        $companyApps = new UserCompanyApps();
380 3
        $companyApps->companies_id = $this->getId();
381 3
        $companyApps->apps_id = $this->di->getApp()->getId();
382
        //$companyApps->subscriptions_id = 0;
383
384
        //we need to assign this company to a plan
385 3
        if (empty($this->appPlanId)) {
386 3
            $plan = AppsPlans::getDefaultPlan();
387 3
            $companyApps->stripe_id = $plan->stripe_id;
388
        }
389
390
        //If the newly created company is not the default then we create a new subscription with the same user
391 3
        if ($this->di->getUserData()->default_company != $this->getId()) {
392 3
            $this->setSettings(self::PAYMENT_GATEWAY_CUSTOMER_KEY, $this->startFreeTrial());
393
        }
394
395 3
        $companyApps->subscriptions_id = $this->subscription->getId();
0 ignored issues
show
Bug Best Practice introduced by
The property subscription does not exist on Gewaer\Models\Companies. Since you implemented __get, consider adding a @property annotation.
Loading history...
396 3
        $companyApps->created_at = date('Y-m-d H:i:s');
397 3
        $companyApps->is_deleted = 0;
398
399 3
        if (!$companyApps->save()) {
400
            throw new ServerErrorHttpException((string)current($companyApps->getMessages()));
401
        }
402 3
    }
403
404
    /**
405
     * Get the default company the users has selected
406
     *
407
     * @param  Users  $user
408
     * @return Companies
409
     */
410
    public static function getDefaultByUser(Users $user): Companies
411
    {
412
        //verify the user has a default company
413
        $defaultCompany = UserConfig::findFirst([
414
            'conditions' => 'users_id = ?0 and name = ?1',
415
            'bind' => [$user->getId(), self::DEFAULT_COMPANY],
416
        ]);
417
418
        //found it
419
        if (is_object($defaultCompany)) {
420
            return self::findFirst($defaultCompany->value);
421
        }
422
423
        //second try
424
        $defaultCompany = UsersAssociatedCompanies::findFirst([
425
            'conditions' => 'users_id = ?0 and user_active =?1',
426
            'bind' => [$user->getId(), 1],
427
        ]);
428
429
        if (is_object($defaultCompany)) {
430
            return self::findFirst($defaultCompany->companies_id);
431
        }
432
433
        throw new Exception(_("User doesn't have an active company"));
434
    }
435
436
    /**
437
     * After the model was update we need to update its custom fields
438
     *
439
     * @return void
440
     */
441 3
    public function afterUpdate()
442
    {
443
        //only clean and change custom fields if they are been sent
444 3
        if (!empty($this->customFields)) {
445
            //replace old custom with new
446 1
            $allCustomFields = $this->getAllCustomFields();
447 1
            if (is_array($allCustomFields)) {
448 1
                foreach ($this->customFields as $key => $value) {
449 1
                    $allCustomFields[$key] = $value;
450
                }
451
            }
452
453 1
            if (!empty($allCustomFields)) {
454
                //set
455 1
                $this->setCustomFields($allCustomFields);
456
                //clean old
457 1
                $this->cleanCustomFields($this->getId());
458
                //save new
459 1
                $this->saveCustomFields();
460
            }
461
        }
462 3
    }
463
464
    /**
465
     * Start a free trial for a new company
466
     *
467
     * @return string //the customer id
468
     */
469 3
    public function startFreeTrial() : ?string
470
    {
471 3
        $defaultPlan = AppsPlans::getDefaultPlan();
472 3
        $trialEndsAt = Carbon::now()->addDays($this->di->getApp()->plan->free_trial_dates);
473
474
        //Lets create a new default subscription without payment method
475 3
        $this->user->newSubscription($defaultPlan->name, $defaultPlan->stripe_id, $this, $this->di->getApp())
476 3
                ->trialDays($defaultPlan->free_trial_dates)
477 3
                ->create();
478
479
        //ook for the subscription and update the missing info
480 3
        $subscription = $this->subscription;
0 ignored issues
show
Bug Best Practice introduced by
The property subscription does not exist on Gewaer\Models\Companies. Since you implemented __get, consider adding a @property annotation.
Loading history...
481 3
        $subscription->apps_plans_id = $this->di->getApp()->default_apps_plan_id;
0 ignored issues
show
Bug introduced by
The property apps_plans_id does not seem to exist on Phalcon\Mvc\Model\Resultset.
Loading history...
482 3
        $subscription->trial_ends_days = $trialEndsAt->diffInDays(Carbon::now());
0 ignored issues
show
Bug introduced by
The property trial_ends_days does not seem to exist on Phalcon\Mvc\Model\Resultset.
Loading history...
483 3
        $subscription->is_freetrial = 1;
0 ignored issues
show
Bug introduced by
The property is_freetrial does not seem to exist on Phalcon\Mvc\Model\Resultset.
Loading history...
484 3
        $subscription->is_active = 1;
0 ignored issues
show
Bug introduced by
The property is_active does not seem to exist on Phalcon\Mvc\Model\Resultset.
Loading history...
485
486 3
        if (!$subscription->save()) {
0 ignored issues
show
Bug introduced by
The method save() does not exist on Phalcon\Mvc\Model\Resultset. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

486
        if (!$subscription->/** @scrutinizer ignore-call */ save()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
487
            throw new ServerErrorHttpException((string)'Subscription for new company couldnt be created ' . current($this->getMessages()));
488
        }
489
490 3
        return $this->user->stripe_id;
491
    }
492
}
493