Completed
Push — master ( 461049...43e826 )
by Andrii
02:39
created

Client::onBeforeSave()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 0
cts 19
cp 0
rs 8.9777
c 0
b 0
f 0
cc 6
nc 12
nop 0
crap 42
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
            $double = static::findOne([ 'email' => $this->email_confirmed ]);
93
            if (empty($double) || $this->obj_id === $double->obj_id) {
94
                $this->email = $this->email_confirmed;
95
            }
96
            $this->saveValue('contact:email_new', '');
97
            $this->saveValue('contact:email_confirmed', $this->email_confirmed);
98
            $this->saveValue('contact:email_confirm_date', new Expression("date_trunc('second', now()::timestamp)::text"));
99
        }
100
    }
101
102
    public function onAfterSave()
103
    {
104
        $this->id = $this->id ?: $this->getAgain()->id;
105
        $this->type = $this->type ?: $this->getAgain()->type;
106
107
        $contact = Contact::findOne($this->id);
108
        $contact->setAttributes($this->getAttributes($contact->safeAttributes()));
109
        $contact->save();
110
        $this->saveValue('client,access:totp_secret', $this->totp_secret);
111
        $this->saveValue('client,access:allowed_ips', $this->allowed_ips);
112
        $this->saveValue('login_ips:panel', $this->allowed_ips);
113
114
        $this->saveValue('contact:policy_consent', 1);
115
        $this->saveValue('contact:gdpr_consent', 1);
116
    }
117
118
    protected $_again;
119
120
    public function getAgain()
121
    {
122
        /// XXX this crutch is needed bacause we use `zclient` view (not table)
123
        /// XXX and yii ActiveRecord doesn't populate model properly in this case
124
        if ($this->_again === null) {
125
            $this->_again = static::find()->whereUsername($this->username)->one();
126
        }
127
128
        return $this->_again;
129
    }
130
131
    public function saveValue($prop, $value)
132
    {
133
        $params = [
134
            'id' => $this->id,
135
            'prop' => $prop,
136
            'value' => $value,
137
        ];
138
        $sub = ':value';
139
        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...
140
            $sub = (string)$value;
141
            unset($params['value']);
142
        }
143
        self::getDb()->createCommand("SELECT set_value(:id,:prop,$sub)", $params)->execute();
144
    }
145
146
    public static function find()
147
    {
148
        return new ClientQuery(get_called_class());
149
    }
150
151
    public function setId($value)
152
    {
153
        $this->obj_id = $value;
154
    }
155
156
    public function getId()
157
    {
158
        return $this->obj_id;
159
    }
160
161
    public function getSeller_id()
162
    {
163
        return $this->reseller_id;
164
    }
165
166
    /**
167
     * {@inheritdoc}
168
     */
169
    public function getPasswordHash()
170
    {
171
        return $this->password_hash;
172
    }
173
174
    public function getPassword_hash()
175
    {
176
        return $this->getAuthKey();
177
    }
178
179
    /**
180
     * @param string $email
181
     * @return bool
182
     */
183
    public function updateEmail(string $email): bool
184
    {
185
        if ($this->username) {
186
            try {
187
                if (Yii::$app->db->createCommand()
188
                    ->update('zclient', ['email' => $email], 'login = :login')
189
                    ->bindValue(':login', $this->username)
190
                    ->execute()) {
191
                    return true;
192
                }
193
            } 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...
194
            }
195
        }
196
197
        return false;
198
    }
199
200
    protected static function filterCondition(array $condition, array $aliases = [])
201
    {
202
        /// XXX skip condition filtering
203
        return $condition;
204
    }
205
}
206