ConfirmationTrait::confirm()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 8
ccs 4
cts 5
cp 0.8
rs 9.4285
c 1
b 0
f 0
cc 3
eloc 5
nc 2
nop 1
crap 3.072
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 - 2017 vistart
10
 * @license https://vistart.me/license/
11
 */
12
13
namespace rhosocial\base\models\traits;
14
15
use Yii;
16
use yii\base\ModelEvent;
17
18
/**
19
 * This trait allow its owner to enable the entity to be blamed by user.
20
 * @property-read boolean $isConfirmed
21
 * @property integer $confirmation
22
 * @property-read array $confirmationRules
23
 * @property string $confirmCode the confirm code used for confirming the content.
24
 * You can disable this attribute and create a new model for storing confirm code as
25
 * its low-frequency usage.
26
 * @version 1.0
27
 * @author vistart <[email protected]>
28
 */
29
trait ConfirmationTrait
30
{
31
32
    /**
33
     * @var int Unconfirmed.
34
     */
35
    public static $confirmFalse = 0;
36
37
    /**
38
     * @var int Confirmed.
39
     */
40
    public static $confirmTrue = 1;
41
42
    /**
43
     * @var string|false attribute name of confirmation, or false if disable confirmation features.
44
     */
45
    public $confirmationAttribute = false;
46
47
    /**
48
     * @var string This attribute specify the name of confirm_code attribute, if
49
     * this attribute is assigned to false, this feature will be ignored.
50
     * if $confirmationAttribute is empty or false, this attribute will be skipped.
51
     */
52
    public $confirmCodeAttribute = 'confirm_code';
53
54
    /**
55
     * @var integer The expiration in seconds. If $confirmCodeAttribute is
56
     * specified, this attribute must be specified.
57
     */
58
    public $confirmCodeExpiration = 3600;
59
60
    /**
61
     * @var string This attribute specify the name of confirm_time attribute. if
62
     * this attribute is assigned to false, this feature will be ignored.
63
     * if $confirmationAttribute is empty or false, this attribute will be skipped.
64
     */
65
    public $confirmTimeAttribute = 'confirmed_at';
66
67
    /**
68
     * @var string initialization confirm time.
69
     */
70
    public $initConfirmTime = '1970-01-01 00:00:00';
71
    public static $eventConfirmationChanged = "confirmationChanged";
72
    public static $eventConfirmationCanceled = "confirmationCanceled";
73
    public static $eventConfirmationSuceeded = "confirmationSucceeded";
74
75
    /**
76
     * Apply confirmation.
77
     * @return boolean
78
     * @throws \yii\base\NotSupportedException
79
     */
80 3
    public function applyConfirmation()
81
    {
82 3
        if (!$this->confirmCodeAttribute || empty($this->confirmCodeAttribute)) {
83
            throw new \yii\base\NotSupportedException('This method is not implemented.');
84
        }
85 3
        $this->setConfirmCode($this->generateConfirmationCode());
86 3
        return $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...
87
    }
88
89
    /**
90
     * Set confirm code.
91
     * @param string $code
92
     */
93 26
    public function setConfirmCode($code)
94
    {
95 26
        if (!$this->confirmCodeAttribute || empty($this->confirmCodeAttribute)) {
96 6
            return;
97
        }
98 20
        $confirmCodeAttribute = $this->confirmCodeAttribute;
99 20
        $this->$confirmCodeAttribute = $code;
100 20
        if (!$this->confirmTimeAttribute) {
101
            return;
102
        }
103 20
        $confirmTimeAttribute = $this->confirmTimeAttribute;
104 20
        if (!empty($code)) {
105 3
            $this->$confirmTimeAttribute = date('Y-m-d H:i:s');
106 3
            return;
107
        }
108 20
        $this->$confirmTimeAttribute = $this->initConfirmTime;
109 20
    }
110
111
    /**
112
     * Get confirm code.
113
     * @return string
114
     */
115 3
    public function getConfirmCode()
116
    {
117 3
        $confirmCodeAttribute = $this->confirmCodeAttribute;
118 3
        return (is_string($confirmCodeAttribute) && !empty($confirmCodeAttribute)) ? $this->$confirmCodeAttribute : null;
119
    }
120
121
    /**
122
     * Confirm the current content.
123
     * @param string $code
124
     * @return boolean
125
     */
126 3
    public function confirm($code = '')
127
    {
128 3
        if (!$this->confirmationAttribute || !$this->validateConfirmationCode($code)) {
129
            return false;
130
        }
131 3
        $this->confirmation = static::$confirmTrue;
132 3
        return $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...
133
    }
134
135
    /**
136
     * Generate confirmation code.
137
     * @return string code
138
     */
139 3
    public function generateConfirmationCode()
140
    {
141 3
        return substr(sha1(Yii::$app->security->generateRandomString()), 0, 17);
142
    }
143
144
    /**
145
     * Validate the confirmation code.
146
     * @param string $code
147
     * @return boolean Whether the confirmation code is valid.
148
     */
149 3
    public function validateConfirmationCode($code)
150
    {
151 3
        $ccAttribute = $this->confirmCodeAttribute;
152 3
        if (!$ccAttribute || empty($ccAttribute)) {
153
            return true;
154
        }
155 3
        return $this->$ccAttribute === $code;
156
    }
157
158
    /**
159
     * Get confirmation status of current model.
160
     * @return boolean Whether current model has been confirmed.
161
     */
162 5
    public function getIsConfirmed()
163
    {
164 5
        $cAttribute = $this->confirmationAttribute;
165 5
        return (is_string($cAttribute) && !empty($cAttribute)) ? $this->$cAttribute > static::$confirmFalse : true;
166
    }
167
168
    /**
169
     * Initialize the confirmation status.
170
     * This method is ONLY used for being triggered by event. DO NOT call,
171
     * override or modify it directly, unless you know the consequences.
172
     * @param ModelEvent $event
173
     */
174 209
    public function onInitConfirmation($event)
175
    {
176 209
        $sender = $event->sender;
177
        /* @var $sender static */
178 209
        if (!$sender->confirmationAttribute || empty($sender->confirmationAttribute)) {
179 195
            return;
180
        }
181 26
        $sender->confirmation = static::$confirmFalse;
182 26
        $sender->confirmCode = '';
183 26
    }
184
185
    /**
186
     * Set confirmation.
187
     * @param mixed $value
188
     */
189 31
    public function setConfirmation($value)
190
    {
191 31
        $cAttribute = $this->confirmationAttribute;
192 31
        if (!$cAttribute || empty($cAttribute)) {
193 5
            return;
194
        }
195 26
        $this->$cAttribute = $value;
196 26
        $this->trigger(static::$eventConfirmationChanged);
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...
197 26
    }
198
199
    /**
200
     * Get confirmation.
201
     * @return mixed
202
     */
203 1
    public function getConfirmation()
204
    {
205 1
        $cAttribute = $this->confirmationAttribute;
206 1
        return (is_string($cAttribute) && !empty($cAttribute)) ? $this->$cAttribute : null;
207
    }
208
209
    /**
210
     * When confirmation status changed, this event will be triggered. If
211
     * confirmation succeeded, the confirm_time will be assigned to current time,
212
     * or the confirm_time will be assigned to initConfirmTime.
213
     * This method is ONLY used for being triggered by event. DO NOT call,
214
     * override or modify it directly, unless you know the consequences.
215
     * @param ModelEvent $event
216
     */
217 26
    public function onConfirmationChanged($event)
218
    {
219 26
        $sender = $event->sender;
220 26
        $cAttribute = $sender->confirmationAttribute;
221 26
        if (!$cAttribute || empty($cAttribute)) {
222
            return;
223
        }
224 26
        if ($sender->isAttributeChanged($cAttribute)) {
225 26
            $sender->confirmCode = '';
226 26
            if ($sender->$cAttribute == static::$confirmFalse) {
227 26
                $sender->trigger(static::$eventConfirmationCanceled);
228 26
                return;
229
            }
230 4
            $sender->trigger(static::$eventConfirmationSuceeded);
231 4
            $sender->resetOthersConfirmation();
232
        }
233 4
    }
234
235
    /**
236
     * Get rules associated with confirmation attributes.
237
     * if not enable confirmation feature, it will return empty array.
238
     * @return array
239
     */
240 199
    public function getConfirmationRules()
241
    {
242 199
        if (!$this->confirmationAttribute) {
243 179
            return [];
244
        }
245
        return [
246 20
            [[$this->confirmationAttribute], 'number', 'integerOnly' => true, 'min' => 0],
247 20
            [[$this->confirmTimeAttribute], 'safe'],
248
        ];
249
    }
250
251
    /**
252
     * When the content changed, reset confirmation status.
253
     */
254 58
    protected function resetConfirmation()
255
    {
256 58
        $contentAttribute = $this->contentAttribute;
0 ignored issues
show
Bug introduced by
The property contentAttribute 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...
257 58
        if (!$contentAttribute || empty($contentAttribute)) {
258 11
            return;
259
        }
260 47
        if (is_array($contentAttribute)) {
261
            foreach ($contentAttribute as $attribute) {
262
                if ($this->isAttributeChanged($attribute)) {
0 ignored issues
show
Bug introduced by
It seems like isAttributeChanged() 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...
263
                    $this->confirmation = static::$confirmFalse;
264
                    break;
265
                }
266
            }
267 47
        } elseif ($this->isAttributeChanged($contentAttribute)) {
0 ignored issues
show
Bug introduced by
It seems like isAttributeChanged() 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...
268 6
            $this->confirmation = static::$confirmFalse;
269
        }
270 47
    }
271
272
    /**
273
     * Reset others' confirmation when the others own the same content.
274
     */
275 4
    protected function resetOthersConfirmation()
276
    {
277 4
        if (!$this->confirmationAttribute || empty($this->hostClass)) {
0 ignored issues
show
Bug introduced by
The property hostClass 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...
278
            return;
279
        }
280 4
        $contents = static::find()
281 4
            ->where([$this->contentAttribute => $this->getContent()])
0 ignored issues
show
Bug introduced by
It seems like getContent() 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...
282 4
            ->andWhere(['not like', $this->createdByAttribute, $this->user->getGUID()])
0 ignored issues
show
Bug introduced by
The property createdByAttribute 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 property user 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...
283 4
            ->all();
284 4
        foreach ($contents as $content) {
285
            $content->confirmation = static::$confirmFalse;
286
            $content->save();
287
        }
288 4
    }
289
}
290