Test Failed
Pull Request — master (#21)
by Maximo
04:55
created

Users::beforeCreate()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 4
nop 0
dl 0
loc 14
ccs 7
cts 7
cp 1
crap 3
rs 10
c 0
b 0
f 0
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\UnprocessableEntityHttpException;
10
use Carbon\Carbon;
11
12
/**
13
 * Class Users
14
 *
15
 * @package Gewaer\Models
16
 *
17
 * @property Users $user
18
 * @property Config $config
19
 * @property Apps $app
20
 * @property Companies $defaultCompany
21
 * @property \Phalcon\Di $di
22
 */
23
class Users extends \Baka\Auth\Models\Users
24
{
25
    use PermissionsTrait;
26
    use Billable;
1 ignored issue
show
introduced by
The trait Phalcon\Cashier\Billable requires some properties which are not provided by Gewaer\Models\Users: $stripe, $data, $brand, $last4, $paid, $customer, $secretKey, $card, $sources, $subscriptions
Loading history...
27
    use SubscriptionPlanLimitTrait;
0 ignored issues
show
introduced by
The trait Gewaer\Traits\SubscriptionPlanLimitTrait requires some properties which are not provided by Gewaer\Models\Users: $appPlan, $company
Loading history...
28
29
    public $default_company_branch;
30
    public $roles_id;
31
    public $stripe_id;
32
    public $card_last_four;
33
    public $card_brand;
34
    public $trial_ends_at;
35
36
    /**
37
     * Provide the app plan id
38
     * if the user is signing up a new company
39
     *
40
     * @var integer
41
     */
42
    public $appPlanId = null;
43
44
    /**
45
     * Initialize method for model.
46
     */
47 28
    public function initialize()
48
    {
49 28
        $this->setSource('users');
50
51
        //overwrite parent relationships
52 28
        $this->hasOne('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'session']);
53 28
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
54 28
        $this->hasMany('id', 'Baka\Auth\Models\SessionKeys', 'users_id', ['alias' => 'sessionKeys']);
55 28
        $this->hasMany('id', 'Baka\Auth\Models\Banlist', 'users_id', ['alias' => 'bans']);
56 28
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
57 28
        $this->hasMany('id', 'Gewaer\Models\UserConfig', 'users_id', ['alias' => 'config']);
58 28
        $this->hasMany('id', 'Gewaer\Models\UserLinkedSources', 'users_id', ['alias' => 'sources']);
59 28
        $this->hasMany('id', 'Baka\Auth\Models\UsersAssociatedCompany', 'users_id', ['alias' => 'companies']);
60 28
        $this->hasOne('default_company', 'Gewaer\Models\Companies', 'id', ['alias' => 'defaultCompany']);
61
62 28
        $this->hasOne(
63 28
            'id',
64 28
            'Gewaer\Models\UserRoles',
65 28
            'users_id',
66 28
            ['alias' => 'permission']
67
        );
68
69 28
        $this->hasMany(
70 28
            'id',
71 28
            'Gewaer\Models\UserRoles',
72 28
            'users_id',
73 28
            ['alias' => 'permissions']
74
        );
75
76 28
        $this->hasManyToMany(
77 28
            'id',
78 28
            'Gewaer\Models\UserRoles',
79 28
            'users_id',
80 28
            'roles_id',
81 28
            'Gewaer\Models\Roles',
82 28
            'id',
83
            [
84 28
                'alias' => 'roles',
85
                'params' => [
86 28
                    'limit' => 1,
87 28
                    'conditions' => 'Gewaer\Models\UserRoles.apps_id = ' . $this->di->getConfig()->app->id,
88
                ]
89
            ]
90
        );
91 28
    }
92
93
    /**
94
     * Returns table name mapped in the model.
95
     *
96
     * @return string
97
     */
98 24
    public function getSource() : string
99
    {
100 24
        return 'users';
101
    }
102
103
    /**
104
     * Get the User key for redis
105
     *
106
     * @return string
107
     */
108
    public function getKey() : string
109
    {
110
        return $this->id;
111
    }
112
113
    /**
114
     * Get all of the subscriptions for the user.
115
     */
116 3
    public function subscriptions()
117
    {
118 3
        $this->hasMany(
119 3
            'id',
120 3
            Subscription::class,
121 3
            'user_id',
122
            [
123 3
                'alias' => 'subscriptions',
124
                'params' => [
125 3
                    'conditions' => 'apps_id = ?0 and company_id = ?1',
126 3
                    'bind' => [$this->di->getApp()->getId(), $this->default_company],
127 3
                    'order' => 'id DESC'
128
                ]
129
            ]
130
        );
131 3
        return $this->getRelated('subscriptions');
132
    }
133
134
    /**
135
     * Strat a free trial
136
     *
137
     * @param Users $user
138
     * @return Subscription
139
     */
140 1
    public function startFreeTrial() : Subscription
141
    {
142 1
        $defaultPlan = AppsPlans::getDefaultPlan();
143
144 1
        $subscription = new Subscription();
145 1
        $subscription->user_id = $this->getId();
0 ignored issues
show
Bug Best Practice introduced by
The property user_id does not exist on Gewaer\Models\Subscription. Since you implemented __set, consider adding a @property annotation.
Loading history...
146 1
        $subscription->company_id = $this->default_company;
0 ignored issues
show
Bug Best Practice introduced by
The property company_id does not exist on Gewaer\Models\Subscription. Since you implemented __set, consider adding a @property annotation.
Loading history...
147 1
        $subscription->apps_id = $this->di->getApp()->getId();
0 ignored issues
show
Bug Best Practice introduced by
The property apps_id does not exist on Gewaer\Models\Subscription. Since you implemented __set, consider adding a @property annotation.
Loading history...
148 1
        $subscription->apps_plans_id = $this->di->getApp()->default_apps_plan_id;
149 1
        $subscription->name = $defaultPlan->name;
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist on Gewaer\Models\Subscription. Since you implemented __set, consider adding a @property annotation.
Loading history...
150 1
        $subscription->stripe_id = $defaultPlan->stripe_id;
0 ignored issues
show
Bug Best Practice introduced by
The property stripe_id does not exist on Gewaer\Models\Subscription. Since you implemented __set, consider adding a @property annotation.
Loading history...
151 1
        $subscription->stripe_plan = $defaultPlan->stripe_plan;
0 ignored issues
show
Bug Best Practice introduced by
The property stripe_plan does not exist on Gewaer\Models\Subscription. Since you implemented __set, consider adding a @property annotation.
Loading history...
152 1
        $subscription->quantity = 1;
0 ignored issues
show
Bug Best Practice introduced by
The property quantity does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
153 1
        $subscription->trial_ends_at = Carbon::now()->addDays($this->di->getApp()->plan->free_trial_dates)->toDateTimeString();
0 ignored issues
show
Bug Best Practice introduced by
The property trial_ends_at does not exist on Gewaer\Models\Subscription. Since you implemented __set, consider adding a @property annotation.
Loading history...
154
155 1
        if (!$subscription->save()) {
156
            throw new ServerErrorHttpException((string)current($this->getMessages()));
0 ignored issues
show
Bug introduced by
The type Gewaer\Models\ServerErrorHttpException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
157
        }
158
159 1
        $this->trial_ends_at = $subscription->trial_ends_at;
0 ignored issues
show
Bug Best Practice introduced by
The property trial_ends_at does not exist on Gewaer\Models\Subscription. Since you implemented __get, consider adding a @property annotation.
Loading history...
160 1
        $this->update();
161
162 1
        return $subscription;
163
    }
164
165
    /**
166
     * Before create
167
     *
168
     * @return void
169
     */
170 4
    public function beforeCreate()
171
    {
172 4
        parent::beforeCreate();
173
174
        //this is only empty when creating a new user
175 4
        if (!empty($this->default_company)) {
176
            //confirm if the app reach its limit
177 3
            $this->isAtLimit();
178
        }
179
180
        //Assign admin role to the system if we dont get a specify role
181 4
        if (empty($this->roles_id)) {
182 1
            $role = Roles::findFirstByName('Admins');
183 1
            $this->roles_id = $role->getId();
184
        }
185 4
    }
186
187
    /**
188
     * What to do after the creation of a new users
189
     *  - Assign default role
190
     *
191
     * @return void
192
     */
193 4
    public function afterCreate()
194
    {
195
        /**
196
         * User signing up for a new app / plan
197
         * How do we know? well he doesnt have a default_company
198
         */
199 4
        if (empty($this->default_company)) {
200 1
            $company = new Companies();
201 1
            $company->name = $this->defaultCompanyName;
202 1
            $company->users_id = $this->getId();
203
204 1
            if (!$company->save()) {
205
                throw new Exception(current($company->getMessages()));
0 ignored issues
show
Bug introduced by
The type Gewaer\Models\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
206
            }
207
208 1
            $this->default_company = $company->getId();
209
210 1
            if (!$this->update()) {
211
                throw new Exception(current($this->getMessages()));
212
            }
213
214 1
            $this->default_company_branch = $this->defaultCompany->branch->getId();
1 ignored issue
show
Bug introduced by
The method getId() 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

214
            /** @scrutinizer ignore-call */ 
215
            $this->default_company_branch = $this->defaultCompany->branch->getId();

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...
Bug Best Practice introduced by
The property branch does not exist on Gewaer\Models\Companies. Since you implemented __get, consider adding a @property annotation.
Loading history...
215 1
            $this->update();
216
217
            //update default subscription free trial
218 1
            $company->app->subscriptions_id = $this->startFreeTrial()->getId();
0 ignored issues
show
Bug Best Practice introduced by
The property subscriptions_id does not exist on Gewaer\Models\Apps. Since you implemented __set, consider adding a @property annotation.
Loading history...
219 1
            $company->update();
220
        } else {
221
            //we have the company id
222 3
            if (empty($this->default_company_branch)) {
223
                $this->default_company_branch = $this->defaultCompany->branch->getId();
224
            }
225
        }
226
227
        //Create new company associated company
228 4
        $newUserAssocCompany = new UsersAssociatedCompany();
229 4
        $newUserAssocCompany->users_id = $this->id;
230 4
        $newUserAssocCompany->company_id = $this->default_company;
231 4
        $newUserAssocCompany->identify_id = 1;
232 4
        $newUserAssocCompany->user_active = 1;
233 4
        $newUserAssocCompany->user_role = $this->roles_id == 1 ? 'admins' : 'users';
234
235 4
        if (!$newUserAssocCompany->save()) {
236
            throw new UnprocessableEntityHttpException((string)current($newUserAssocCompany->getMessages()));
237
        }
238
239
        //Insert record into user_roles
240 4
        $userRole = new UserRoles();
241 4
        $userRole->users_id = $this->id;
242 4
        $userRole->roles_id = $this->roles_id;
243 4
        $userRole->apps_id = $this->di->getApp()->getId();
244 4
        $userRole->company_id = $this->default_company;
245
246 4
        if (!$userRole->save()) {
247
            throw new UnprocessableEntityHttpException((string)current($userRole->getMessages()));
248
        }
249
250
        //update user activity when its not a empty user
251 4
        if (empty($this->default_company)) {
252
            $this->updateAppActivityLimit();
253
        }
254 4
    }
255
}
256