Completed
Push — master ( 22227d...41329c )
by Andrii
03:15
created

Client::updateEmail()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 0
cp 0
rs 9.7333
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 20
1
<?php
2
/**
3
 * HIAM module for MRDP database compatibility
4
 *
5
 * @link      https://github.com/hiqdev/hiam-mrdp
6
 * @package   hiam-mrdp
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiam\mrdp\storage;
12
13
use Yii;
14
use yii\base\InvalidConfigException;
15
use yii\db\Exception;
16
use yii\db\Expression;
17
18
/**
19
 * Client model.
20
 *
21
 * @property integer $obj_id PK
22
 * @property integer $id synced with obj_id
23
 * @property integer $seller_id
24
 * @property string $password
25
 * @property string $email
26
 */
27
class Client extends \yii\db\ActiveRecord
28
{
29
    public $type;
30
    public $state;
31
    public $roles;
32
    public $seller;
33
    public $username;
34
    public $last_name;
35
    public $first_name;
36
37
    public $email_confirmed;
38
    public $allowed_ips;
39
    public $totp_secret;
40
41
    public $password_hash;
42
43
    public static function tableName()
44
    {
45
        return '{{zclient}}';
46
    }
47
48
    public static function primaryKey()
49
    {
50
        return ['obj_id'];
51
    }
52
53
    public function rules()
54
    {
55
        return [
56
            [['username', 'email', 'password', 'first_name', 'last_name'], 'trim'],
57
            [['username', 'email'], 'filter', 'filter' => 'strtolower'],
58
            [['seller_id'], 'integer'],
59
            [['state'], 'trim'],
60
            [['email_confirmed', 'allowed_ips', 'totp_secret'], 'trim'],
61
        ];
62
    }
63
64
    public function init()
65
    {
66
        parent::init();
67
        $this->on(static::EVENT_BEFORE_INSERT, [$this, 'onBeforeInsert']);
68
        $this->on(static::EVENT_BEFORE_UPDATE, [$this, 'onBeforeSave']);
69
        $this->on(static::EVENT_AFTER_INSERT,  [$this, 'onAfterSave']);
70
        $this->on(static::EVENT_AFTER_UPDATE,  [$this, 'onAfterSave']);
71
    }
72
73
    public function onBeforeInsert()
74
    {
75
        $seller = static::findOne(['username' => Yii::$app->params['user.seller']]);
76
        $this->login = $this->username ?: $this->email;
77
        $this->seller_id = $seller->id;
78
        $this->onBeforeSave();
79
    }
80
81
    public function onBeforeSave()
82
    {
83
        if (empty($this->password)) {
84
            unset($this->password);
85
        }
86
        if (!empty($this->state)) {
87
            $this->state_id = new Expression(
88
                "zref_id('state,client,{$this->state}')"
89
            );
90
        }
91
        if ($this->email_confirmed) {
92
            $this->email = $this->email_confirmed;
93
            $this->saveValue('contact:email_new', '');
94
            $this->saveValue('contact:email_confirmed', $this->email_confirmed);
95
            $this->saveValue('contact:email_confirm_date', new Expression("date_trunc('second', now()::timestamp)::text"));
96
        }
97
    }
98
99
    public function onAfterSave()
100
    {
101
        $this->id = $this->id ?: $this->getAgain()->id;
102
        $this->type = $this->type ?: $this->getAgain()->type;
103
104
        $contact = Contact::findOne($this->id);
105
        $contact->setAttributes($this->getAttributes($contact->safeAttributes()));
106
        $contact->save();
107
        $this->saveValue('client,access:totp_secret', $this->totp_secret);
108
        $this->saveValue('client,access:allowed_ips', $this->allowed_ips);
109
        $this->saveValue('login_ips:panel', $this->allowed_ips);
110
111
        $this->saveValue('contact:policy_consent', 1);
112
        $this->saveValue('contact:gdpr_consent', 1);
113
    }
114
115
    protected $_again;
116
117
    public function getAgain()
118
    {
119
        /// XXX this crutch is needed bacause we use `zclient` view (not table)
120
        /// XXX and yii ActiveRecord doesn't populate model properly in this case
121
        if ($this->_again === null) {
122
            $this->_again = static::find()->whereUsername($this->username)->one();
123
        }
124
125
        return $this->_again;
126
    }
127
128
    public function saveValue($prop, $value)
129
    {
130
        $params = [
131
            'id' => $this->id,
132
            'prop' => $prop,
133
            'value' => $value,
134
        ];
135
        $sub = ':value';
136
        if ($value instanceof Expression) {
0 ignored issues
show
Bug introduced by
The class yii\db\Expression does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
137
            $sub = (string)$value;
138
            unset($params['value']);
139
        }
140
        self::getDb()->createCommand("SELECT set_value(:id,:prop,$sub)", $params)->execute();
141
    }
142
143
    public static function find()
144
    {
145
        return new ClientQuery(get_called_class());
146
    }
147
148
    public function setId($value)
149
    {
150
        $this->obj_id = $value;
151
    }
152
153
    public function getId()
154
    {
155
        return $this->obj_id;
156
    }
157
158
    public function getSeller_id()
159
    {
160
        return $this->reseller_id;
161
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166
    public function getPasswordHash()
167
    {
168
        return $this->password_hash;
169
    }
170
171
    public function getPassword_hash()
172
    {
173
        return $this->getAuthKey();
174
    }
175
176
    /**
177
     * @param string $email
178
     * @return bool
179
     */
180
    public function updateEmail(string $email): bool
181
    {
182
        if ($this->username) {
183
            try {
184
                if (Yii::$app->db->createCommand()
185
                    ->update('zclient', ['email' => $email], 'login = :login')
186
                    ->bindValue(':login', $this->username)
187
                    ->execute()) {
188
                    return true;
189
                }
190
            } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
Bug introduced by
The class yii\db\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
191
            }
192
        }
193
194
        return false;
195
    }
196
197
    protected static function filterCondition(array $condition, array $aliases = [])
198
    {
199
        /// XXX skip condition filtering
200
        return $condition;
201
    }
202
}
203