Completed
Push — master ( 81b65f...3c6407 )
by vistart
07:48
created

ConfirmationTrait::resetOthersConfirmation()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.3244

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 14
ccs 8
cts 11
cp 0.7272
rs 9.2
c 1
b 0
f 0
cc 4
eloc 10
nc 3
nop 0
crap 4.3244
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 2
    public function applyConfirmation()
81
    {
82 2
        if (!$this->confirmCodeAttribute || empty($this->confirmCodeAttribute)) {
83
            throw new \yii\base\NotSupportedException('This method is not implemented.');
84
        }
85 2
        $this->setConfirmCode($this->generateConfirmationCode());
86 2
        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 20
    public function setConfirmCode($code)
94
    {
95 20
        if (!$this->confirmCodeAttribute || empty($this->confirmCodeAttribute)) {
96 5
            return;
97
        }
98 15
        $confirmCodeAttribute = $this->confirmCodeAttribute;
99 15
        $this->$confirmCodeAttribute = $code;
100 15
        if (!$this->confirmTimeAttribute) {
101
            return;
102
        }
103 15
        $confirmTimeAttribute = $this->confirmTimeAttribute;
104 15
        if (!empty($code)) {
105 2
            $this->$confirmTimeAttribute = date('Y-m-d H:i:s');
106 2
            return;
107
        }
108 15
        $this->$confirmTimeAttribute = $this->initConfirmTime;
109 15
    }
110
111
    /**
112
     * Get confirm code.
113
     * @return string
114
     */
115 2
    public function getConfirmCode()
116
    {
117 2
        $confirmCodeAttribute = $this->confirmCodeAttribute;
118 2
        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 2
    public function confirm($code)
127
    {
128 2
        if (!$this->confirmationAttribute || !$this->validateConfirmationCode($code)) {
129
            return false;
130
        }
131 2
        $this->confirmation = static::$confirmTrue;
132 2
        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 2
    public function generateConfirmationCode()
140
    {
141 2
        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 2
    public function validateConfirmationCode($code)
150
    {
151 2
        $ccAttribute = $this->confirmCodeAttribute;
152 2
        if (!$ccAttribute || empty($ccAttribute)) {
153
            return true;
154
        }
155 2
        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 4
    public function getIsConfirmed()
163
    {
164 4
        $cAttribute = $this->confirmationAttribute;
165 4
        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 184
    public function onInitConfirmation($event)
175
    {
176 184
        $sender = $event->sender;
177
        /* @var $sender static */
178 184
        if (!$sender->confirmationAttribute || empty($sender->confirmationAttribute)) {
179 173
            return;
180
        }
181 20
        $sender->confirmation = static::$confirmFalse;
182 20
        $sender->confirmCode = '';
183 20
    }
184
185
    /**
186
     * Set confirmation.
187
     * @param mixed $value
188
     */
189 25
    public function setConfirmation($value)
190
    {
191 25
        $cAttribute = $this->confirmationAttribute;
192 25
        if (!$cAttribute || empty($cAttribute)) {
193 5
            return;
194
        }
195 20
        $this->$cAttribute = $value;
196 20
        $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 20
    }
198
199
    /**
200
     * Get confirmation.
201
     * @return mixed
202
     */
203
    public function getConfirmation()
204
    {
205
        $cAttribute = $this->confirmationAttribute;
206
        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 20
    public function onConfirmationChanged($event)
218
    {
219 20
        $sender = $event->sender;
220 20
        $cAttribute = $sender->confirmationAttribute;
221 20
        if (!$cAttribute || empty($cAttribute)) {
222
            return;
223
        }
224 20
        if ($sender->isAttributeChanged($cAttribute)) {
225 20
            $sender->confirmCode = '';
226 20
            if ($sender->$cAttribute == static::$confirmFalse) {
227 20
                $sender->trigger(static::$eventConfirmationCanceled);
228 20
                return;
229
            }
230 3
            $sender->trigger(static::$eventConfirmationSuceeded);
231 3
            $sender->resetOthersConfirmation();
232
        }
233 3
    }
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 168
    public function getConfirmationRules()
241
    {
242 168
        if (!$this->confirmationAttribute) {
243 151
            return [];
244
        }
245
        return [
246 17
            [[$this->confirmationAttribute], 'number', 'integerOnly' => true, 'min' => 0],
247 17
            [[$this->confirmTimeAttribute], 'safe'],
248
        ];
249
    }
250
251
    /**
252
     * When the content changed, reset confirmation status.
253
     */
254 54
    protected function resetConfirmation()
255
    {
256 54
        $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 54
        if (!$contentAttribute || empty($contentAttribute)) {
258 9
            return;
259
        }
260 45
        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 45
        } 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 45
    }
271
272
    /**
273
     * Reset others' confirmation when the others own the same content.
274
     */
275 3
    protected function resetOthersConfirmation()
276
    {
277 3
        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 3
        $contents = static::find()
281 3
            ->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 3
            ->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 3
            ->all();
284 3
        foreach ($contents as $content) {
285
            $content->confirmation = static::$confirmFalse;
286
            $content->save();
287
        }
288 3
    }
289
}
290