Completed
Push — master ( 7ea6d5...25a7f6 )
by Andrii
02:57
created

Client::onBeforeInsert()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 6
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
crap 6
1
<?php
2
3
/*
4
 * HIAM module for MRDP database compatibility
5
 *
6
 * @link      https://github.com/hiqdev/hiam-mrdp
7
 * @package   hiam-mrdp
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hiam\mrdp\storage;
13
14
use Yii;
15
16
/**
17
 * Client model.
18
 *
19
 * @property integer $obj_id PK
20
 * @property integer $seller_id
21
 * @property string $password
22
 * @property string $email
23
 */
24
class Client extends \yii\db\ActiveRecord
25
{
26
    public $id;
27
    public $type;
28
    public $state;
29
    public $seller;
30
    public $username;
31
    public $last_name;
32
    public $first_name;
33
34
    public $allowed_ips;
35
    public $totp_secret;
36
37
    public function rules()
38
    {
39
        return [
40
            [['username', 'email', 'password', 'first_name', 'last_name'], 'trim'],
41
            [['allowed_ips', 'totp_secret'], 'trim'],
42
        ];
43
    }
44
45
    public function init()
46
    {
47
        parent::init();
48
        $this->on(static::EVENT_BEFORE_INSERT, [$this, 'onBeforeInsert']);
49
        $this->on(static::EVENT_AFTER_INSERT,  [$this, 'onAfterSave']);
50
        $this->on(static::EVENT_AFTER_UPDATE,  [$this, 'onAfterSave']);
51
    }
52
53
    public function onBeforeInsert()
54
    {
55
        $seller = static::findOne(['username' => Yii::$app->params['user.seller']]);
56
        $this->login = $this->username ?: $this->email;
57
        $this->seller_id = $seller->id;
58
    }
59
60
    public function onAfterSave()
61
    {
62
        $this->id = $this->id ?: $this->obj_id;
63
        $this->type = $this->type ?: 'client';
64
        $contact = Contact::findOne($this->id);
65
        $contact->setAttributes($this->getAttributes());
66
        $contact->save();
67
        $this->saveValue('client,access:allowed_ips', $this->allowed_ips);
68
        $this->saveValue('client,access:totp_secret', $this->totp_secret);
69
    }
70
71
    public function saveValue($prop, $value)
72
    {
73
        self::getDb()->createCommand('SELECT set_value(:id,:prop,:value)', [
74
            'id' => $this->id,
75
            'prop' => $prop,
76
            'value' => $value,
77
        ])->execute();
78
    }
79
80
    public static function find()
81
    {
82
        return new ClientQuery(get_called_class());
83
    }
84
}
85