Completed
Pull Request — master (#12)
by
unknown
14:29
created

Client::saveAnaliticsData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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