RegistrationTrait::onInitSourceAttribute()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.name/
9
 * @copyright Copyright (c) 2016 vistart
10
 * @license https://vistart.name/license/
11
 */
12
13
namespace vistart\Models\traits;
14
15
use Yii;
16
use yii\base\ModelEvent;
17
use yii\db\Exception;
18
use yii\db\IntegrityException;
19
use yii\rbac\BaseManager;
20
use yii\rbac\Role;
21
22
/**
23
 * User features concerning registration.
24
 *
25
 * @property array $sourceRules rules associated with source attribute.
26
 * @version 2.0
27
 * @author vistart <[email protected]>
28
 */
29
trait RegistrationTrait
30
{
31
32
    /**
33
     * @event Event an event that is triggered after user is registered successfully.
34
     */
35
    public static $eventAfterRegister = "afterRegister";
36
37
    /**
38
     * @event Event an event that is triggered before registration.
39
     */
40
    public static $eventBeforeRegister = "beforeRegister";
41
42
    /**
43
     * @event Event an event that is triggered when registration failed.
44
     */
45
    public static $eventRegisterFailed = "registerFailed";
46
47
    /**
48
     * @event Event an event that is triggered after user is deregistered successfully.
49
     */
50
    public static $eventAfterDeregister = "afterDeregister";
51
52
    /**
53
     * @event Event an event that is triggered before deregistration.
54
     */
55
    public static $eventBeforeDeregister = "beforeDeregister";
56
57
    /**
58
     * @event Event an event that is triggered when deregistration failed.
59
     */
60
    public static $eventDeregisterFailed = "deregisterFailed";
61
62
    /**
63
     * @var string name of attribute which store the source. if you don't want to
64
     * record source, please assign false.
65
     */
66
    public $sourceAttribute = 'source';
67
    private $_sourceRules = [];
68
    public static $sourceSelf = '0';
69
70
    /**
71
     * @var string auth manager component id.
72
     */
73
    public $authManagerId = 'authManager';
74
75
    /**
76
     * Get auth manager. If auth manager not configured, Yii::$app->authManager
77
     * will be given.
78
     * @return BaseManager
79
     */
80 56
    public function getAuthManager()
81
    {
82 56
        $authManagerId = $this->authManagerId;
83 56
        return empty($authManagerId) ? Yii::$app->authManager : Yii::$app->$authManagerId;
84
    }
85
86
    /**
87
     * Register new user.
88
     * It is equivalent to store the current user and its associated models into
89
     * database synchronously. The registration will be terminated immediately
90
     * if any errors occur in the process, and all the earlier steps succeeded
91
     * are rolled back.
92
     * If auth manager configured, and auth role(s) provided, it(they) will be
93
     * assigned to user after registration.
94
     * If current user is not a new one(isNewRecord = false), the registration
95
     * will be skipped and return false.
96
     * The $eventBeforeRegister will be triggered before registration starts.
97
     * If registration finished, the $eventAfterRegister will be triggered. or
98
     * $eventRegisterFailed will be triggered when any errors occured.
99
     * @param array $associatedModels The models associated with user to be stored synchronously.
100
     * @param string|array $authRoles auth name, auth instance, auth name array or auth instance array.
101
     * @return boolean Whether the registration succeeds or not.
102
     * @throws IntegrityException when inserting user and associated models failed.
103
     */
104 56
    public function register($associatedModels = [], $authRoles = [])
105
    {
106 56
        if (!$this->isNewRecord) {
0 ignored issues
show
Bug introduced by
The property isNewRecord does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
107
            return false;
108
        }
109 56
        $this->trigger(static::$eventBeforeRegister);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
110 56
        $transaction = $this->getDb()->beginTransaction();
0 ignored issues
show
Bug introduced by
It seems like getDb() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
111
        try {
112 56
            if (!$this->save()) {
0 ignored issues
show
Bug introduced by
It seems like save() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
113 1
                throw new IntegrityException('Registration Error(s) Occured.', $this->errors);
0 ignored issues
show
Bug introduced by
The property errors does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
114
            }
115 56
            if ($authManager = $this->getAuthManager() && !empty($authRoles)) {
116
                if (is_string($authRoles) || $authRoles instanceof Role || !is_array($authRoles)) {
117
                    $authRoles = [$authRoles];
118
                }
119
                foreach ($authRoles as $role) {
120
                    if (is_string($role)) {
121
                        $role = $authManager->getRole($role);
0 ignored issues
show
Bug introduced by
The method getRole cannot be called on $authManager (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
122
                    }
123
                    if ($role instanceof Role) {
124
                        $authManager->assign($role, $this->guid);
0 ignored issues
show
Bug introduced by
The property guid does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The method assign cannot be called on $authManager (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
125
                    }
126
                }
127
            }
128 56
            if (!empty($associatedModels) && is_array($associatedModels)) {
129 8
                foreach ($associatedModels as $model) {
130 8
                    if (!$model->save()) {
131
                        throw new IntegrityException('Registration Error(s) Occured.', $model->errors);
132
                    }
133 8
                }
134 8
            }
135 56
            $transaction->commit();
136 56
        } catch (Exception $ex) {
137 1
            $transaction->rollBack();
138 1
            $this->trigger(static::$eventRegisterFailed);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
139 1
            if (YII_DEBUG || YII_ENV !== YII_ENV_PROD) {
140 1
                Yii::error($ex->errorInfo, static::className() . '\register');
0 ignored issues
show
Documentation introduced by
$ex->errorInfo is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
141 1
                return $ex;
142
            }
143
            Yii::warning($ex->errorInfo, static::className() . '\register');
0 ignored issues
show
Documentation introduced by
$ex->errorInfo is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
144
            return false;
145
        }
146 56
        $this->trigger(static::$eventAfterRegister);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
147 56
        return true;
148
    }
149
150
    /**
151
     * Deregister current user itself.
152
     * It is equivalent to delete current user and its associated models. BUT it
153
     * deletes current user ONLY, the associated models will not be deleted
154
     * forwardly. So you should set the foreign key of associated models' table
155
     * referenced from primary key of user table, and their association mode is
156
     * 'on update cascade' and 'on delete cascade'.
157
     * the $eventBeforeDeregister will be triggered before deregistration starts.
158
     * if deregistration finished, the $eventAfterDeregister will be triggered. or
159
     * $eventDeregisterFailed will be triggered when any errors occured.
160
     * @return boolean Whether deregistration succeeds or not.
161
     * @throws IntegrityException when deleting user failed.
162
     */
163 56
    public function deregister()
164
    {
165 56
        if ($this->isNewRecord) {
166
            return false;
167
        }
168 56
        $this->trigger(static::$eventBeforeDeregister);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
169 56
        $transaction = $this->getDb()->beginTransaction();
0 ignored issues
show
Bug introduced by
It seems like getDb() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
170
        try {
171 56
            $result = $this->delete();
0 ignored issues
show
Bug introduced by
It seems like delete() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
172 56
            if ($result != 1) {
173
                throw new IntegrityException('Deregistration Error(s) Occured.', $this->errors);
174
            }
175 56
            $transaction->commit();
176 56
        } catch (Exception $ex) {
177
            $transaction->rollBack();
178
            $this->trigger(static::$eventDeregisterFailed);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
179
            if (YII_DEBUG || YII_ENV !== YII_ENV_PROD) {
180
                Yii::error($ex->errorInfo, static::className() . '\deregister');
0 ignored issues
show
Documentation introduced by
$ex->errorInfo is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
181
                return $ex;
182
            }
183
            Yii::warning($ex->errorInfo, static::className() . '\deregister');
0 ignored issues
show
Documentation introduced by
$ex->errorInfo is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
184
            return false;
185
        }
186 56
        $this->trigger(static::$eventAfterDeregister);
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
187 56
        return $result == 1;
188
    }
189
190
    /**
191
     * Get source.
192
     * @return string
193
     */
194
    public function getSource()
195
    {
196
        $sourceAttribute = $this->sourceAttribute;
197
        return is_string($sourceAttribute) ? $this->$sourceAttribute : null;
198
    }
199
200
    /**
201
     * Set source.
202
     * @param string $source
203
     */
204
    public function setSource($source)
205
    {
206
        $sourceAttribute = $this->sourceAttribute;
207
        return is_string($sourceAttribute) ? $this->$sourceAttribute = $source : null;
208
    }
209
210
    /**
211
     * Get the rules associated with source attribute.
212
     * @return array rules.
213
     */
214 56
    public function getSourceRules()
215
    {
216 56
        if (empty($this->_sourceRules)) {
217 56
            $this->_sourceRules = [
218 56
                [[$this->sourceAttribute], 'required'],
219 56
                [[$this->sourceAttribute], 'string'],
220
            ];
221 56
        }
222 56
        return $this->_sourceRules;
223
    }
224
225
    /**
226
     * Set the rules associated with source attribute.
227
     * @param array $rules
228
     */
229
    public function setSourceRules($rules)
230
    {
231
        if (!empty($rules) && is_array($rules)) {
232
            $this->_sourceRules = $rules;
233
        }
234
    }
235
236
    /**
237
     * Initialize the source attribute with $sourceSelf.
238
     * This method is ONLY used for being triggered by event. DO NOT call,
239
     * override or modify it directly, unless you know the consequences.
240
     * @param ModelEvent $event
241
     */
242 60
    public function onInitSourceAttribute($event)
243
    {
244 60
        $sender = $event->sender;
245 60
        $sourceAttribute = $sender->sourceAttribute;
246 60
        $sender->$sourceAttribute = static::$sourceSelf;
247 60
    }
248
}
249