Completed
Pull Request — master (#12)
by
unknown
13:18
created

Client::saveAnalyticsData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

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