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

MultiTenantRecord::beforeApplyTenant()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace solutosoft\multitenant;
4
5
use Yii;
6
use yii\base\NotSupportedException;
7
use yii\db\ActiveRecord;
8
9
class MultiTenantRecord extends ActiveRecord
10
{
11
    /**
12
     *@inheritdoc
13
     */
14 1
    public function beforeSave($insert)
15
    {
16 1
        if (!Yii::$app->user->isGuest) {
17 1
            $identity = Yii::$app->user->identity;
18 1
            if ($identity instanceof TenantInterface) {
19 1
                if ($insert && $this->beforeApplyTenant() && $this->{TenantInterface::ATTRIBUTE_NAME} === null) {
20 1
                    $this->{TenantInterface::ATTRIBUTE_NAME} = $identity->getTenantId();
21 1
                    $this->afterApplyTenant();
22
                }
23
            } else {
24
                throw new NotSupportedException("Identity does not implements TenantInteface");
25
            }
26
        }
27 1
        return parent::beforeSave($insert);
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 3
    public static function find()
34
    {
35 3
        return Yii::createObject(MultiTenantQuery::class, [get_called_class()]);
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41 1
    protected function resolveFields(array $fields, array $expand)
42
    {
43 1
        $fields = parent::resolveFields($fields, $expand);
44
45 1
        if ($this->hasAttribute(TenantInterface::ATTRIBUTE_NAME)) {
46 1
            unset($fields[TenantInterface::ATTRIBUTE_NAME]);
47
        }
48
49 1
        return $fields;
50
    }
51
52
53
54
    /**
55
     * This method is invoked before assign the attribute tenant id
56
     * You may override this method to do preliminary checks before apply tenant id.
57
     * @return boolean whether the tenant id should be assigned. Defaults to true.
58
     */
59 1
    protected function beforeApplyTenant()
60
    {
61 1
        return true;
62
    }
63
64
    /**
65
     * This method is invoked after assign the attribute tenant id
66
     * You may override this method to do postprocessing after apply tenant id.
67
     */
68 1
    protected function afterApplyTenant()
69
    {
70
71 1
    }
72
}
73