Total Complexity | 11 |
Total Lines | 61 |
Duplicated Lines | 0 % |
Coverage | 95.65% |
Changes | 0 |
1 | <?php |
||
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() |
|
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)) { |
|
|
|||
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() |
|
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() |
|
69 | |||
70 | 1 | } |
|
71 | } |
||
72 |