Passed
Push — master ( f9059e...f0992a )
by Leandro
01:40
created

MultiTenantRecord::beforeSave()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6.0493

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 4
nop 1
dl 0
loc 14
ccs 8
cts 9
cp 0.8889
crap 6.0493
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
namespace solutosoft\multitenant;
4
5
use Yii;
6
use yii\base\NotSupportedException;
7
8
trait MultiTenantRecord
9
{
10
    /**
11
     *@inheritdoc
12
     */
13 1
    public function beforeSave($insert)
14
    {
15 1
        if (!Yii::$app->user->isGuest) {
16 1
            $identity = Yii::$app->user->identity;
17 1
            if ($identity instanceof TenantInterface) {
18 1
                if ($insert && $this->beforeApplyTenant() && !$this->tenant_id) {
19 1
                    $this->tenant_id = $identity->getTenantId();
0 ignored issues
show
Bug Best Practice introduced by
The property tenant_id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
20 1
                    $this->afterApplyTenant();
21
                }
22
            } else {
23
                throw new NotSupportedException("Identity does not implements TenantInteface");
24
            }
25
        }
26 1
        return parent::beforeSave($insert);
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 2
    public static function find()
33
    {
34 2
        return Yii::createObject(MultiTenantQuery::class, [get_called_class()]);
35
    }
36
37
38
    /**
39
     * This method is invoked before assign the attribute tenant id
40
     * You may override this method to do preliminary checks before apply tenant id.
41
     * @return boolean whether the tenant id should be assigned. Defaults to true.
42
     */
43 1
    protected function beforeApplyTenant()
44
    {
45 1
        return true;
46
    }
47
48
    /**
49
     * This method is invoked after assign the attribute tenant id
50
     * You may override this method to do postprocessing after apply tenant id.
51
     */
52 1
    protected function afterApplyTenant()
53
    {
54
55 1
    }
56
}
57