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

MultiTenantRecord::resolveFields()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A MultiTenantRecord::beforeApplyTenant() 0 3 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