Passed
Push — master ( 3e8ce4...b26523 )
by Leandro
02:02
created

MultiTenantRecord   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A beforeSave() 0 14 6
A find() 0 3 1
A beforeApplyTenant() 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->{TenantInterface::ATTRIBUTE_NAME} === null) {
19 1
                    $this->{TenantInterface::ATTRIBUTE_NAME} = $identity->getTenantId();
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
     * This method is invoked before assign the attribute tenant id
39
     * You may override this method to do preliminary checks before apply tenant id.
40
     * @return boolean whether the tenant id should be assigned. Defaults to true.
41
     */
42 1
    protected function beforeApplyTenant()
43
    {
44 1
        return true;
45
    }
46
47
    /**
48
     * This method is invoked after assign the attribute tenant id
49
     * You may override this method to do postprocessing after apply tenant id.
50
     */
51 1
    protected function afterApplyTenant()
52
    {
53
54 1
    }
55
}
56