Completed
Push — master ( 8ea8de...59eb2e )
by Charles
01:52
created

Activation::rules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
3
namespace yrc\forms;
4
5
use Base32\Base32;
6
use Yii;
7
8
use yrc\models\Code;
9
10
/**
11
 * @class Activation
12
 * The form for validating the activation form
13
 */
14
abstract class Activation extends \yii\base\Model
15
{
16
    /**
17
     * The activation code
18
     * @var string $activation_code
19
     */
20
    public $activation_code;
21
22
    /**
23
     * The user associated to the model
24
     * @var User $user
25
     */
26
    private $user;
27
28
    /**
29
     * Validation rules
30
     * @return array
31
     */
32
    public function rules()
33
    {
34
        return [
35
            [['activation_code'], 'required'],
36
            [['activation_code'], 'belongsToUserAndIsNotExpired']
37
        ];
38
    }
39
40
    /**
41
     * Validates that the activation code belongs to a user and is not expired
42
     * @param string $attribute
43
     * @param array $params
44
     */
45
    public function belongsToUserAndIsNotExpired($attribute, $params)
0 ignored issues
show
Unused Code introduced by
The parameter $attribute is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $params is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
46
    {
47
        if (!$this->hasErrors()) {
48
            $code = Code::find()->where([
49
                'hash' => hash('sha256', $this->activation_code . '_activation_token')
50
            ])->one();
51
            
52
            if ($code === null) {
53
                $this->addError('activation_code', Yii::t('yrc', 'The activation code provided is not valid.'));
54
                return;
55
            }
56
57
            $this->user = Yii::$app->yrc->userClass::find()->where(['id' => $code->user_id])->one();
58
59
            if ($this->user === null) {
60
                $this->addError('activation_code', Yii::t('yrc', 'The activation code provided is not valid.'));
61
            }
62
        }
63
    }
64
65
    /**
66
     * Activates the user
67
     * @return boolean
68
     */
69
    public function activate()
70
    {
71
        if ($this->validate()) {
72
            if ($this->user->activate()) {
73
                Code::deleteAll(['hash' => hash('sha256', $this->activation_code . '_activation_token')]);
74
75
                return true;
76
            }
77
        }
78
79
        return false;
80
    }
81
}
82