Passed
Pull Request — master (#368)
by Sergei
02:42
created

CustomConnectionTrait   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 8
c 1
b 0
f 0
dl 0
loc 21
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A withConnectionName() 0 5 1
A db() 0 7 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\ActiveRecord\Trait;
6
7
use Yiisoft\ActiveRecord\AbstractActiveRecord;
8
use Yiisoft\ActiveRecord\ConnectionProvider;
9
use Yiisoft\Db\Connection\ConnectionInterface;
10
11
/**
12
 * Trait to implement custom connection name for ActiveRecord.
13
 *
14
 * @see AbstractActiveRecord::db()
15
 */
16
trait CustomConnectionTrait
17
{
18
    private string $connectionName;
19
20
    /**
21
     * Sets the connection name for the ActiveRecord.
22
     */
23
    public function withConnectionName(string $connectionName): static
24
    {
25
        $new = clone $this;
26
        $new->connectionName = $connectionName;
27
        return $new;
28
    }
29
30
    public function db(): ConnectionInterface
31
    {
32
        if (!empty($this->connectionName)) {
33
            return ConnectionProvider::get($this->connectionName);
34
        }
35
36
        return parent::db();
37
    }
38
}
39