Completed
Push — master ( 443bff...94d0aa )
by Dmitry
13:27
created

Client   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 203
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 35
lcom 1
cbo 1
dl 0
loc 203
ccs 0
cts 111
cp 0
rs 9.6
c 0
b 0
f 0

19 Methods

Rating   Name   Duplication   Size   Complexity  
A tableName() 0 4 1
A primaryKey() 0 4 1
A rules() 0 11 1
A init() 0 8 1
A onBeforeInsert() 0 7 2
B onBeforeSave() 0 22 7
A isEmailConfirmAction() 0 6 2
A onAfterSave() 0 18 4
A getAgain() 0 10 2
A readValue() 0 8 1
A saveValue() 0 14 2
A find() 0 4 1
A setId() 0 4 1
A getId() 0 4 1
A getSeller_id() 0 4 1
A getPasswordHash() 0 4 1
A getPassword_hash() 0 4 1
A updateEmail() 0 16 4
A filterCondition() 0 5 1
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
    public $send_me_news;
37
38
    public $email_confirmed;
39
    public $email_new;
40
    public $allowed_ips;
41
    public $totp_secret;
42
43
    public $password_hash;
44
45
    public static function tableName()
46
    {
47
        return '{{zclient}}';
48
    }
49
50
    public static function primaryKey()
51
    {
52
        return ['obj_id'];
53
    }
54
55
    public function rules()
56
    {
57
        return [
58
            [['username', 'email', 'password', 'first_name', 'last_name', 'email_new'], 'trim'],
59
            [['username', 'email'], 'filter', 'filter' => 'strtolower'],
60
            [['seller_id'], 'integer'],
61
            [['state'], 'trim'],
62
            [['email_confirmed', 'allowed_ips', 'totp_secret'], 'trim'],
63
            ['send_me_news', 'boolean'],
64
        ];
65
    }
66
67
    public function init()
68
    {
69
        parent::init();
70
        $this->on(static::EVENT_BEFORE_INSERT, [$this, 'onBeforeInsert']);
71
        $this->on(static::EVENT_BEFORE_UPDATE, [$this, 'onBeforeSave']);
72
        $this->on(static::EVENT_AFTER_INSERT,  [$this, 'onAfterSave']);
73
        $this->on(static::EVENT_AFTER_UPDATE,  [$this, 'onAfterSave']);
74
    }
75
76
    public function onBeforeInsert()
77
    {
78
        $seller = static::findOne(['username' => Yii::$app->params['user.seller']]);
79
        $this->login = $this->username ?: $this->email;
80
        $this->seller_id = $seller->id;
81
        $this->onBeforeSave();
82
    }
83
84
    public function onBeforeSave()
85
    {
86
        if (empty($this->password)) {
87
            unset($this->password);
88
        }
89
        if (!empty($this->state)) {
90
            $this->state_id = new Expression("zref_id('state,client,{$this->state}')");
91
        }
92
93
        if ($this->isEmailConfirmAction()) {
94
            $double = static::findOne(['email' => $this->email_confirmed]);
95
            if (empty($double) || $this->obj_id === $double->obj_id) {
96
                $this->email = $this->email_confirmed;
97
            }
98
            $this->saveValue('contact:email_new', '');
99
            $this->saveValue('contact:email_confirmed', $this->email_confirmed);
100
            $this->saveValue('contact:email_confirm_date', new Expression("date_trunc('second', now()::timestamp)::text"));
101
        }
102
        if (!empty($this->email_new)) {
103
            $this->saveValue('contact:email_new', $this->email_new);
104
        }
105
    }
106
107
    private function isEmailConfirmAction(): bool
108
    {
109
        $currentConfirmedEmail = $this->readValue('contact:email_confirmed');
110
111
        return !empty($this->email_confirmed) && ($currentConfirmedEmail !== $this->email_confirmed);
112
    }
113
114
    public function onAfterSave()
115
    {
116
        $this->id = $this->id ?: $this->getAgain()->id;
117
        $this->type = $this->type ?: $this->getAgain()->type;
118
        $send_news = $this->send_me_news === '0' ? '' : 1;
119
120
        $contact = Contact::findOne($this->id);
121
        $contact->setAttributes($this->getAttributes($contact->safeAttributes()));
122
        $contact->save();
123
        $this->saveValue('client,access:totp_secret', $this->totp_secret);
124
        $this->saveValue('client,access:allowed_ips', $this->allowed_ips);
125
        $this->saveValue('login_ips:panel', $this->allowed_ips);
126
127
        $this->saveValue('contact:policy_consent', 1);
128
        $this->saveValue('contact:gdpr_consent', 1);
129
        $this->saveValue('client,mailing:commercial', $send_news);
130
        $this->saveValue('client,mailing:newsletters', $send_news);
131
    }
132
133
    protected $_again;
134
135
    public function getAgain()
136
    {
137
        /// XXX this crutch is needed bacause we use `zclient` view (not table)
138
        /// XXX and yii ActiveRecord doesn't populate model properly in this case
139
        if ($this->_again === null) {
140
            $this->_again = static::find()->whereUsername($this->username)->one();
141
        }
142
143
        return $this->_again;
144
    }
145
146
    private function readValue(string $prop): string
147
    {
148
        $params = [
149
            'id' => $this->id,
150
            'prop' => $prop,
151
        ];
152
        return self::getDb()->createCommand("SELECT get_value(:id,:prop)", $params)->queryScalar();
153
    }
154
155
    public function saveValue($prop, $value)
156
    {
157
        $params = [
158
            'id' => $this->id,
159
            'prop' => $prop,
160
            'value' => $value,
161
        ];
162
        $sub = ':value';
163
        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...
164
            $sub = (string)$value;
165
            unset($params['value']);
166
        }
167
        self::getDb()->createCommand("SELECT set_value(:id,:prop,$sub)", $params)->execute();
168
    }
169
170
    public static function find()
171
    {
172
        return new ClientQuery(get_called_class());
173
    }
174
175
    public function setId($value)
176
    {
177
        $this->obj_id = $value;
178
    }
179
180
    public function getId()
181
    {
182
        return $this->obj_id;
183
    }
184
185
    public function getSeller_id()
186
    {
187
        return $this->reseller_id;
188
    }
189
190
    /**
191
     * {@inheritdoc}
192
     */
193
    public function getPasswordHash()
194
    {
195
        return $this->password_hash;
196
    }
197
198
    public function getPassword_hash()
199
    {
200
        return $this->getAuthKey();
201
    }
202
203
    /**
204
     * @param string $email
205
     * @return bool
206
     */
207
    public function updateEmail(string $email): bool
208
    {
209
        if ($this->username) {
210
            try {
211
                if (Yii::$app->db->createCommand()
212
                    ->update('zclient', ['email' => $email], 'login = :login')
213
                    ->bindValue(':login', $this->username)
214
                    ->execute()) {
215
                    return true;
216
                }
217
            } 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...
218
            }
219
        }
220
221
        return false;
222
    }
223
224
    protected static function filterCondition(array $condition, array $aliases = [])
225
    {
226
        /// XXX skip condition filtering
227
        return $condition;
228
    }
229
}
230