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

MultiTenantRecord   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 46
ccs 13
cts 14
cp 0.9286
rs 10
c 0
b 0
f 0
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A beforeApplyTenant() 0 3 1
A beforeSave() 0 14 6
A find() 0 3 1
A afterApplyTenant() 0 2 1
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