Passed
Pull Request — master (#21)
by Maximo
04:23
created

Users::hasRole()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
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\ServerErrorHttpException;
10
use Exception;
11
use Carbon\Carbon;
12
13
/**
14
 * Class Users
15
 *
16
 * @package Gewaer\Models
17
 *
18
 * @property Users $user
19
 * @property Config $config
20
 * @property Apps $app
21
 * @property Companies $defaultCompany
22
 * @property \Phalcon\Di $di
23
 */
24
class Users extends \Baka\Auth\Models\Users
25
{
26
    use PermissionsTrait;
27
    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...
28
    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...
29
30
    public $default_company_branch;
31
    public $roles_id;
32
    public $stripe_id;
33
    public $card_last_four;
34
    public $card_brand;
35
    public $trial_ends_at;
36
37
    /**
38
     * Provide the app plan id
39
     * if the user is signing up a new company
40
     *
41
     * @var integer
42
     */
43
    public $appPlanId = null;
44
45
    /**
46
     * Initialize method for model.
47
     */
48 28
    public function initialize()
49
    {
50 28
        $this->setSource('users');
51
52
        //overwrite parent relationships
53 28
        $this->hasOne('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'session']);
54 28
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
55 28
        $this->hasMany('id', 'Baka\Auth\Models\SessionKeys', 'users_id', ['alias' => 'sessionKeys']);
56 28
        $this->hasMany('id', 'Baka\Auth\Models\Banlist', 'users_id', ['alias' => 'bans']);
57 28
        $this->hasMany('id', 'Baka\Auth\Models\Sessions', 'users_id', ['alias' => 'sessions']);
58 28
        $this->hasMany('id', 'Gewaer\Models\UserConfig', 'users_id', ['alias' => 'config']);
59 28
        $this->hasMany('id', 'Gewaer\Models\UserLinkedSources', 'users_id', ['alias' => 'sources']);
60 28
        $this->hasMany('id', 'Baka\Auth\Models\UsersAssociatedCompany', 'users_id', ['alias' => 'companies']);
61 28
        $this->hasOne('default_company', 'Gewaer\Models\Companies', 'id', ['alias' => 'defaultCompany']);
62
63 28
        $this->hasOne(
64 28
            'id',
65 28
            'Gewaer\Models\UserRoles',
66 28
            'users_id',
67 28
            ['alias' => 'permission']
68
        );
69
70 28
        $this->hasMany(
71 28
            'id',
72 28
            'Gewaer\Models\UserRoles',
73 28
            'users_id',
74 28
            ['alias' => 'permissions']
75
        );
76
77 28
        $this->hasManyToMany(
78 28
            'id',
79 28
            'Gewaer\Models\UserRoles',
80 28
            'users_id',
81 28
            'roles_id',
82 28
            'Gewaer\Models\Roles',
83 28
            'id',
84
            [
85 28
                'alias' => 'roles',
86
                'params' => [
87 28
                    'limit' => 1,
88 28
                    'conditions' => 'Gewaer\Models\UserRoles.apps_id = ' . $this->di->getConfig()->app->id,
89
                ]
90
            ]
91
        );
92 28
    }
93
94
    /**
95
     * Returns table name mapped in the model.
96
     *
97
     * @return string
98
     */
99 24
    public function getSource() : string
100
    {
101 24
        return 'users';
102
    }
103
104
    /**
105
     * Get the User key for redis
106
     *
107
     * @return string
108
     */
109
    public function getKey() : string
110
    {
111
        return $this->id;
112
    }
113
114
    /**
115
     * A company owner is the first person that register this company
116
     * This only ocurres when signing up the first time, after that all users invites
117
     * come with a default_company id attached
118
     *
119
     * @return boolean
120
     */
121 4
    public function isOwner(): bool
122
    {
123 4
        return empty($this->default_company) ? true : false;
124
    }
125
126
    /**
127
     * Does the user have a role assign to him?
128
     *
129
     * @return boolean
130
     */
131 4
    public function hasRole(): bool
132
    {
133 4
        return !empty($this->roles_id) ? true : false;
134
    }
135
136
    /**
137
     * Get all of the subscriptions for the user.
138
     */
139 3
    public function subscriptions()
140
    {
141 3
        $this->hasMany(
142 3
            'id',
143 3
            Subscription::class,
144 3
            'user_id',
145
            [
146 3
                'alias' => 'subscriptions',
147
                'params' => [
148 3
                    'conditions' => 'apps_id = ?0 and company_id = ?1',
149 3
                    'bind' => [$this->di->getApp()->getId(), $this->default_company],
150 3
                    'order' => 'id DESC'
151
                ]
152
            ]
153
        );
154 3
        return $this->getRelated('subscriptions');
155
    }
156
157
    /**
158
     * Strat a free trial
159
     *
160
     * @param Users $user
161
     * @return Subscription
162
     */
163 1
    public function startFreeTrial() : Subscription
164
    {
165 1
        $defaultPlan = AppsPlans::getDefaultPlan();
166
167 1
        $subscription = new Subscription();
168 1
        $subscription->user_id = $this->getId();
169 1
        $subscription->company_id = $this->default_company;
170 1
        $subscription->apps_id = $this->di->getApp()->getId();
171 1
        $subscription->apps_plans_id = $this->di->getApp()->default_apps_plan_id;
172 1
        $subscription->name = $defaultPlan->name;
173 1
        $subscription->stripe_id = $defaultPlan->stripe_id;
174 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...
175 1
        $subscription->quantity = 1;
176 1
        $subscription->trial_ends_at = Carbon::now()->addDays($this->di->getApp()->plan->free_trial_dates)->toDateTimeString();
177
178 1
        if (!$subscription->save()) {
179
            throw new ServerErrorHttpException((string)current($this->getMessages()));
180
        }
181
182 1
        $this->trial_ends_at = $subscription->trial_ends_at;
183 1
        $this->update();
184
185 1
        return $subscription;
186
    }
187
188
    /**
189
     * Before create
190
     *
191
     * @return void
192
     */
193 4
    public function beforeCreate()
194
    {
195 4
        parent::beforeCreate();
196
197
        //this is only empty when creating a new user
198 4
        if (!$this->isOwner()) {
199
            //confirm if the app reach its limit
200 3
            $this->isAtLimit();
201
        }
202
203
        //Assign admin role to the system if we dont get a specify role
204 3
        if (!$this->hasRole()) {
205 1
            $role = Roles::findFirstByName('Admins');
206 1
            $this->roles_id = $role->getId();
207
        }
208 3
    }
209
210
    /**
211
     * What to do after the creation of a new users
212
     *  - Assign default role
213
     *
214
     * @return void
215
     */
216 3
    public function afterCreate()
217
    {
218
        /**
219
         * User signing up for a new app / plan
220
         * How do we know? well he doesnt have a default_company
221
         */
222 3
        if ($this->isOwner()) {
223 1
            $company = new Companies();
224 1
            $company->name = $this->defaultCompanyName;
225 1
            $company->users_id = $this->getId();
226
227 1
            if (!$company->save()) {
228
                throw new Exception(current($company->getMessages()));
229
            }
230
231 1
            $this->default_company = $company->getId();
232
233 1
            if (!$this->update()) {
234
                throw new ServerErrorHttpException(current($this->getMessages()));
235
            }
236
237 1
            $this->default_company_branch = $this->defaultCompany->branch->getId();
0 ignored issues
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...
238 1
            $this->update();
239
240
            //update default subscription free trial
241 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...
242 1
            $company->update();
243
        } else {
244
            //we have the company id
245 2
            if (empty($this->default_company_branch)) {
246
                $this->default_company_branch = $this->defaultCompany->branch->getId();
247
            }
248
        }
249
250
        //Create new company associated company
251 3
        $newUserAssocCompany = new UsersAssociatedCompany();
252 3
        $newUserAssocCompany->users_id = $this->id;
253 3
        $newUserAssocCompany->company_id = $this->default_company;
254 3
        $newUserAssocCompany->identify_id = 1;
255 3
        $newUserAssocCompany->user_active = 1;
256 3
        $newUserAssocCompany->user_role = $this->roles_id == 1 ? 'admins' : 'users';
257
258 3
        if (!$newUserAssocCompany->save()) {
259
            throw new ServerErrorHttpException((string)current($newUserAssocCompany->getMessages()));
260
        }
261
262
        //Insert record into user_roles
263 3
        $userRole = new UserRoles();
264 3
        $userRole->users_id = $this->id;
265 3
        $userRole->roles_id = $this->roles_id;
266 3
        $userRole->apps_id = $this->di->getApp()->getId();
267 3
        $userRole->company_id = $this->default_company;
268
269 3
        if (!$userRole->save()) {
270
            throw new ServerErrorHttpException((string)current($userRole->getMessages()));
271
        }
272
273
        //update user activity when its not a empty user
274 3
        if (!$this->isOwner()) {
275 3
            $this->updateAppActivityLimit();
276
        }
277 3
    }
278
}
279