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

MultiTenantQuery   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 75%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 47
ccs 12
cts 16
cp 0.75
rs 10
c 0
b 0
f 0
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A prepare() 0 6 2
A withoutTenant() 0 4 1
A addTenantCondition() 0 8 2
A withTenant() 0 4 1
1
<?php
2
3
namespace solutosoft\multitenant;
4
5
use Yii;
6
use yii\base\NotSupportedException;
7
use yii\db\ActiveQuery;
8
9
class MultiTenantQuery extends ActiveQuery
10
{
11
    private $_withTenant = true;
12
13
    /**
14
     * {@inheritDoc}
15
     */
16 2
    public function prepare($builder)
17
    {
18 2
        if ($this->_withTenant) {
19 2
            $this->addTenantCondition();
20
        }
21 2
        return parent::prepare($builder);
22
    }
23
24
    /**
25
     * Disables where tenant condition
26
     * @return $this
27
     */
28 2
    public function withoutTenant()
29
    {
30 2
        $this->_withTenant = false;
31 2
        return $this;
32
    }
33
34
    /**
35
     * Enables where tenant condition
36
     * @return $this
37
     */
38
    public function withTenant()
39
    {
40
        $this->_withTenant = true;
41
        return $this;
42
    }
43
44
    /**
45
     * Adds an additional WHERE tenant condition to the existing one.
46
     * @return void
47
     */
48 2
    private function addTenantCondition()
49
    {
50 2
        $identity = Yii::$app->user->identity;
51 2
        if ($identity instanceof TenantInterface) {
52 2
            list(,$alias) = $this->getTableNameAndAlias();
53 2
            $this->andOnCondition(["{$alias}.tenant_id" => $identity->getTenantId()]);
54
        } else {
55
            throw new NotSupportedException("Identity does not implements TenantInteface");
56
        }
57
    }
58
}