Completed
Push — master ( eec31e...9249bd )
by vistart
05:05
created

ConfirmationTrait::getConfirmation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 5
c 0
b 0
f 0
ccs 0
cts 3
cp 0
rs 9.4285
cc 2
eloc 3
nc 2
nop 0
crap 6
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
    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 3
    public function setConfirmCode($code)
96
    {
97 3
        if (!$this->confirmCodeAttribute) {
98 3
            return;
99
        }
100
        $confirmCodeAttribute = $this->confirmCodeAttribute;
101
        $this->$confirmCodeAttribute = $code;
102
        if (!$this->confirmTimeAttribute) {
103
            return;
104
        }
105
        $confirmTimeAttribute = $this->confirmTimeAttribute;
106
        if (!empty($code)) {
107
            $this->$confirmTimeAttribute = date('Y-m-d H:i:s');
108
            return;
109
        }
110
        $this->$confirmTimeAttribute = $this->initConfirmTime;
111
    }
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 12
    public function onInitConfirmation($event)
177
    {
178 12
        $sender = $event->sender;
179 12
        if (!$sender->confirmationAttribute) {
180 9
            return;
181
        }
182 3
        $sender->confirmation = self::$confirmFalse;
183 3
        $sender->confirmCode = '';
184 3
    }
185
186
    /**
187
     * Set confirmation.
188
     * @param mixed $value
189
     */
190 3
    public function setConfirmation($value)
191
    {
192 3
        $cAttribute = $this->confirmationAttribute;
193 3
        if (!$cAttribute) {
194
            return;
195
        }
196 3
        $this->$cAttribute = $value;
197 3
        $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 3
    }
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 3
    public function onConfirmationChanged($event)
219
    {
220 3
        $sender = $event->sender;
221 3
        $cAttribute = $sender->confirmationAttribute;
222 3
        if (!$cAttribute) {
223
            return;
224
        }
225 3
        if ($sender->isAttributeChanged($cAttribute)) {
226 3
            $sender->confirmCode = '';
227 3
            if ($sender->$cAttribute == self::$confirmFalse) {
228 3
                $sender->trigger(self::$eventConfirmationCanceled);
229 3
                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 12
    public function getConfirmationRules()
242
    {
243 12
        if (!$this->confirmationAttribute) {
244 9
            return [];
245
        }
246
        return [
247 3
            [[$this->confirmationAttribute], 'number', 'integerOnly' => true, 'min' => 0],
248 3
            [[$this->confirmTimeAttribute], 'safe'],
249 3
        ];
250
    }
251
252
    /**
253
     * When the content changed, reset confirmation status.
254
     */
255
    protected function resetConfirmation()
256
    {
257
        $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
        if (!$contentAttribute) {
259
            return;
260
        }
261
        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
        } 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
            $this->confirmation = self::$confirmFalse;
270
        }
271
    }
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