Completed
Push — master ( 1c8e38...d7e61b )
by Leandro
02:16
created

MultiTenantQuery::qualifyTenantColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
namespace solutosoft\multitenant;
4
5
use Yii;
6
use yii\base\NotSupportedException;
7
use yii\db\ActiveQuery;
8
use yii\web\Application as WebApplication;
9
10
class MultiTenantQuery extends ActiveQuery
11
{
12
    private $_withTenant = true;
13
14
    /**
15
     * {@inheritDoc}
16
     */
17 3
    public function prepare($builder)
18
    {
19 3
        if ($this->_withTenant) {
20 3
            $this->addTenantCondition();
21 3
        }
22 3
        return parent::prepare($builder);
23
    }
24
25
    /**
26
     * Disables where tenant condition
27
     * @return $this
28
     */
29 3
    public function withoutTenant()
30
    {
31 3
        $this->_withTenant = false;
32 3
        return $this;
33
    }
34
35
    /**
36
     * Enables where tenant condition
37
     * @return $this
38
     */
39
    public function withTenant()
40
    {
41
        $this->_withTenant = true;
42
        return $this;
43
    }
44
45
    /**
46
     * Adds an additional WHERE tenant condition to the existing one.
47
     * @return void
48
     */
49 3
    private function addTenantCondition()
50
    {
51 3
        $identity = Yii::$app->user->identity;
52 3
        if ($identity instanceof TenantInterface) {
53 3
            $column = $this->qualifyTenantColumn();
54 3
            $this->andOnCondition([$column => $identity->getTenantId()]);
55 3
        } else if (Yii::$app instanceof WebApplication) {
56
            throw new NotSupportedException("Identity does not implements TenantInteface");
57
        }
58 3
    }
59
60
    /**
61
     * Qualify the tenant column name by the query's table.
62
     * @return string
63
     */
64 3
    private function qualifyTenantColumn() {
65 3
        list(,$alias) = $this->getTableNameAndAlias();
66 3
        return $alias . '.' . TenantInterface::ATTRIBUTE_NAME;
67
    }
68
}
69