Completed
Push — master ( e4682c...780945 )
by vistart
69:05 queued 63:09
created

ConfirmationTrait::setConfirmation()   A

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