Completed
Push — master ( b26523...3e8ce4 )
by Leandro
01:35
created

MultiTenantRecord::resolveFields()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 2
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
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 1
                }
22 1
            } else {
23
                throw new NotSupportedException("Identity does not implements TenantInteface");
24
            }
25 1
        }
26 1
        return parent::beforeSave($insert);
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 3
    public static function find()
33
    {
34 3
        return Yii::createObject(MultiTenantQuery::class, [get_called_class()]);
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 1
    protected function resolveFields(array $fields, array $expand)
41
    {
42 1
        $fields = parent::resolveFields($fields, $expand);
43
44 1
        if ($this->hasAttribute(TenantInterface::ATTRIBUTE_NAME)) {
0 ignored issues
show
Bug introduced by
It seems like hasAttribute() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

44
        if ($this->/** @scrutinizer ignore-call */ hasAttribute(TenantInterface::ATTRIBUTE_NAME)) {
Loading history...
45 1
            unset($fields[TenantInterface::ATTRIBUTE_NAME]);
46 1
        }
47
48 1
        return $fields;
49
    }
50
51
52
53
    /**
54
     * This method is invoked before assign the attribute tenant id
55
     * You may override this method to do preliminary checks before apply tenant id.
56
     * @return boolean whether the tenant id should be assigned. Defaults to true.
57
     */
58 1
    protected function beforeApplyTenant()
59
    {
60 1
        return true;
61
    }
62
63
    /**
64
     * This method is invoked after assign the attribute tenant id
65
     * You may override this method to do postprocessing after apply tenant id.
66
     */
67 1
    protected function afterApplyTenant()
68
    {
69
70 1
    }
71
}
72