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

Users   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 252
Duplicated Lines 0 %

Test Coverage

Coverage 83.33%

Importance

Changes 0
Metric Value
eloc 111
dl 0
loc 252
ccs 90
cts 108
cp 0.8333
rs 10
c 0
b 0
f 0
wmc 22

9 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize() 0 41 1
A getKey() 0 3 1
A getSource() 0 3 1
A beforeCreate() 0 14 3
A isOwner() 0 3 2
A subscriptions() 0 16 1
B afterCreate() 0 60 9
A startFreeTrial() 0 23 2
A hasRole() 0 3 2
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, $subscriptionPlanLimitKey, $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
     * A company owner is the first person that register this company
115
     * This only ocurres when signing up the first time, after that all users invites
116
     * come with a default_company id attached
117
     *
118
     * @return boolean
119
     */
120 4
    public function isOwner(): bool
121
    {
122 4
        return empty($this->default_company) ? true : false;
123
    }
124
125
    /**
126
     * Does the user have a role assign to him?
127
     *
128
     * @return boolean
129
     */
130 3
    public function hasRole(): bool
131
    {
132 3
        return !empty($this->roles_id) ? true : false;
133
    }
134
135
    /**
136
     * Get all of the subscriptions for the user.
137
     */
138
    public function subscriptions()
139
    {
140
        $this->hasMany(
141
            'id',
142
            Subscription::class,
143
            'user_id',
144
            [
145
                'alias' => 'subscriptions',
146
                'params' => [
147
                    'conditions' => 'apps_id = ?0 and company_id = ?1',
148
                    'bind' => [$this->di->getApp()->getId(), $this->default_company],
149
                    'order' => 'id DESC'
150
                ]
151
            ]
152
        );
153
        return $this->getRelated('subscriptions');
154
    }
155
156
    /**
157
     * Strat a free trial
158
     *
159
     * @param Users $user
160
     * @return Subscription
161
     */
162 1
    public function startFreeTrial() : Subscription
163
    {
164 1
        $defaultPlan = AppsPlans::getDefaultPlan();
165
166 1
        $subscription = new Subscription();
167 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...
168 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...
169 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...
170 1
        $subscription->apps_plans_id = $this->di->getApp()->default_apps_plan_id;
171 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...
172 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...
173 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...
174 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...
175 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...
176
177 1
        if (!$subscription->save()) {
178
            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...
179
        }
180
181 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...
182 1
        $this->update();
183
184 1
        return $subscription;
185
    }
186
187
    /**
188
     * Before create
189
     *
190
     * @return void
191
     */
192 4
    public function beforeCreate()
193
    {
194 4
        parent::beforeCreate();
195
196
        //this is only empty when creating a new user
197 4
        if (!$this->isOwner()) {
198
            //confirm if the app reach its limit
199 3
            $this->isAtLimit();
200
        }
201
202
        //Assign admin role to the system if we dont get a specify role
203 2
        if (!$this->hasRole()) {
204 1
            $role = Roles::findFirstByName('Admins');
205 1
            $this->roles_id = $role->getId();
206
        }
207 2
    }
208
209
    /**
210
     * What to do after the creation of a new users
211
     *  - Assign default role
212
     *
213
     * @return void
214
     */
215 2
    public function afterCreate()
216
    {
217
        /**
218
         * User signing up for a new app / plan
219
         * How do we know? well he doesnt have a default_company
220
         */
221 2
        if ($this->isOwner()) {
222 1
            $company = new Companies();
223 1
            $company->name = $this->defaultCompanyName;
224 1
            $company->users_id = $this->getId();
225
226 1
            if (!$company->save()) {
227
                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...
228
            }
229
230 1
            $this->default_company = $company->getId();
231
232 1
            if (!$this->update()) {
233
                throw new Exception(current($this->getMessages()));
234
            }
235
236 1
            $this->default_company_branch = $this->defaultCompany->branch->getId();
1 ignored issue
show
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...
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

236
            /** @scrutinizer ignore-call */ 
237
            $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...
237 1
            $this->update();
238
239
            //update default subscription free trial
240 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...
241 1
            $company->update();
242
        } else {
243
            //we have the company id
244 1
            if (empty($this->default_company_branch)) {
245
                $this->default_company_branch = $this->defaultCompany->branch->getId();
246
            }
247
        }
248
249
        //Create new company associated company
250 2
        $newUserAssocCompany = new UsersAssociatedCompany();
251 2
        $newUserAssocCompany->users_id = $this->id;
252 2
        $newUserAssocCompany->company_id = $this->default_company;
253 2
        $newUserAssocCompany->identify_id = 1;
254 2
        $newUserAssocCompany->user_active = 1;
255 2
        $newUserAssocCompany->user_role = $this->roles_id == 1 ? 'admins' : 'users';
256
257 2
        if (!$newUserAssocCompany->save()) {
258
            throw new UnprocessableEntityHttpException((string)current($newUserAssocCompany->getMessages()));
259
        }
260
261
        //Insert record into user_roles
262 2
        $userRole = new UserRoles();
263 2
        $userRole->users_id = $this->id;
264 2
        $userRole->roles_id = $this->roles_id;
265 2
        $userRole->apps_id = $this->di->getApp()->getId();
266 2
        $userRole->company_id = $this->default_company;
267
268 2
        if (!$userRole->save()) {
269
            throw new UnprocessableEntityHttpException((string)current($userRole->getMessages()));
270
        }
271
272
        //update user activity when its not a empty user
273 2
        if (!$this->isOwner()) {
274 2
            $this->updateAppActivityLimit();
275
        }
276 2
    }
277
}
278