ConfirmationTrait::setConfirmation()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 5
Bugs 2 Features 0
Metric Value
c 5
b 2
f 0
dl 0
loc 9
ccs 7
cts 7
cp 1
rs 9.6666
cc 2
eloc 6
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link http://vistart.name/
9
 * @copyright Copyright (c) 2016 vistart
10
 * @license http://vistart.name/license/
11
 */
12
13
namespace vistart\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 2.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 = 'confirm_time';
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
    public function applyConfirmation()
81
    {
82
        if (!$this->confirmCodeAttribute) {
83
            throw new \yii\base\NotSupportedException('This method is not implemented.');
84
        }
85
        $this->confirmCode = $this->generateConfirmationCode();
86
        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...
87
            return false;
88
        }
89
    }
90
91
    /**
92
     * Set confirm code.
93
     * @param string $code
94
     */
95 8
    public function setConfirmCode($code)
96
    {
97 8
        if (!$this->confirmCodeAttribute) {
98 6
            return;
99
        }
100 2
        $confirmCodeAttribute = $this->confirmCodeAttribute;
101 2
        $this->$confirmCodeAttribute = $code;
102 2
        if (!$this->confirmTimeAttribute) {
103
            return;
104
        }
105 2
        $confirmTimeAttribute = $this->confirmTimeAttribute;
106 2
        if (!empty($code)) {
107
            $this->$confirmTimeAttribute = date('Y-m-d H:i:s');
108
            return;
109
        }
110 2
        $this->$confirmTimeAttribute = $this->initConfirmTime;
111 2
    }
112
113
    /**
114
     * Get confirm code.
115
     * @return string
116
     */
117
    public function getConfirmCode()
118
    {
119
        $confirmCodeAttribute = $this->confirmCodeAttribute;
120
        return is_string($confirmCodeAttribute) ? $this->$confirmCodeAttribute : null;
121
    }
122
123
    /**
124
     * Confirm the current content.
125
     * @param string $code
126
     * @return boolean
127
     */
128
    public function confirm($code)
129
    {
130
        if (!$this->confirmationAttribute || !$this->validateConfirmationCode($code)) {
131
            return false;
132
        }
133
        $this->confirmation = self::$confirmTrue;
134
        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...
135
    }
136
137
    /**
138
     * Generate confirmation code.
139
     * @return string code
140
     */
141
    public function generateConfirmationCode()
142
    {
143
        return substr(sha1(Yii::$app->security->generateRandomString()), 0, 8);
144
    }
145
146
    /**
147
     * Validate the confirmation code.
148
     * @param string $code
149
     * @return boolean Whether the confirmation code is valid.
150
     */
151
    public function validateConfirmationCode($code)
152
    {
153
        $ccAttribute = $this->confirmCodeAttribute;
154
        if (!$ccAttribute) {
155
            return true;
156
        }
157
        return $this->$ccAttribute === $code;
158
    }
159
160
    /**
161
     * Get confirmation status of current model.
162
     * @return boolean Whether current model has been confirmed.
163
     */
164
    public function getIsConfirmed()
165
    {
166
        $cAttribute = $this->confirmationAttribute;
167
        return is_string($cAttribute) ? $this->$cAttribute > static::$confirmFalse : true;
168
    }
169
170
    /**
171
     * Initialize the confirmation status.
172
     * This method is ONLY used for being triggered by event. DO NOT call,
173
     * override or modify it directly, unless you know the consequences.
174
     * @param ModelEvent $event
175
     */
176 46
    public function onInitConfirmation($event)
177
    {
178 46
        $sender = $event->sender;
179 46
        if (!$sender->confirmationAttribute) {
180 38
            return;
181
        }
182 8
        $sender->confirmation = self::$confirmFalse;
183 8
        $sender->confirmCode = '';
184 8
    }
185
186
    /**
187
     * Set confirmation.
188
     * @param mixed $value
189
     */
190 10
    public function setConfirmation($value)
191
    {
192 10
        $cAttribute = $this->confirmationAttribute;
193 10
        if (!$cAttribute) {
194 2
            return;
195
        }
196 8
        $this->$cAttribute = $value;
197 8
        $this->trigger(self::$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...
198 8
    }
199
200
    /**
201
     * Get confirmation.
202
     * @return mixed
203
     */
204
    public function getConfirmation()
205
    {
206
        $cAttribute = $this->confirmationAttribute;
207
        return is_string($cAttribute) ? $this->$cAttribute : null;
208
    }
209
210
    /**
211
     * When confirmation status changed, this event will be triggered. If
212
     * confirmation succeeded, the confirm_time will be assigned to current time,
213
     * or the confirm_time will be assigned to initConfirmTime.
214
     * This method is ONLY used for being triggered by event. DO NOT call,
215
     * override or modify it directly, unless you know the consequences.
216
     * @param ModelEvent $event
217
     */
218 8
    public function onConfirmationChanged($event)
219
    {
220 8
        $sender = $event->sender;
221 8
        $cAttribute = $sender->confirmationAttribute;
222 8
        if (!$cAttribute) {
223
            return;
224
        }
225 8
        if ($sender->isAttributeChanged($cAttribute)) {
226 8
            $sender->confirmCode = '';
227 8
            if ($sender->$cAttribute == self::$confirmFalse) {
228 8
                $sender->trigger(self::$eventConfirmationCanceled);
229 8
                return;
230
            }
231
            $sender->trigger(self::$eventConfirmationSuceeded);
232
            $sender->resetOthersConfirmation();
233
        }
234
    }
235
236
    /**
237
     * Get rules associated with confirmation attributes.
238
     * if not enable confirmation feature, it will return empty array.
239
     * @return array
240
     */
241 15
    public function getConfirmationRules()
242
    {
243 15
        if (!$this->confirmationAttribute) {
244 13
            return [];
245
        }
246
        return [
247 2
            [[$this->confirmationAttribute], 'number', 'integerOnly' => true, 'min' => 0],
248 2
            [[$this->confirmTimeAttribute], 'safe'],
249 2
        ];
250
    }
251
252
    /**
253
     * When the content changed, reset confirmation status.
254
     */
255 15
    protected function resetConfirmation()
256
    {
257 15
        $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...
258 15
        if (!$contentAttribute) {
259 4
            return;
260
        }
261 11
        if (is_array($contentAttribute)) {
262
            foreach ($contentAttribute as $attribute) {
263
                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...
264
                    $this->confirmation = self::$confirmFalse;
265
                    break;
266
                }
267
            }
268 11
        } 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...
269 2
            $this->confirmation = self::$confirmFalse;
270 2
        }
271 11
    }
272
273
    /**
274
     * Reset others' confirmation when the others own the same content.
275
     */
276
    protected function resetOthersConfirmation()
277
    {
278
        if (!$this->confirmationAttribute || empty($this->userClass)) {
0 ignored issues
show
Bug introduced by
The property userClass 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...
279
            return;
280
        }
281
        $contents = self::find()
282
            ->where([$this->contentAttribute => $this->content])
0 ignored issues
show
Bug introduced by
The property content does not seem to exist. Did you mean contentAttribute?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
283
            ->andWhere(['not', $this->createdByAttribute, $this->creator])
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 creator 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...
284
            ->all();
285
        foreach ($contents as $content) {
286
            $content->confirmation = self::$confirmFalse;
287
            $content->save();
288
        }
289
    }
290
}
291