Completed
Branch feature/pre-split (67216b)
by Anton
03:22
created

AliasLookup   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 10
c 0
b 0
f 0
wmc 7
lcom 1
cbo 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A tableAlias() 0 8 2
A databaseAlias() 0 13 4
1
<?php
2
/**
3
 * components
4
 *
5
 * @author    Wolfy-J
6
 */
7
namespace Spiral\Migrations\Atomizer;
8
9
use Spiral\Atomizer\Exceptions\AtomizerException;
10
use Spiral\Database\DatabaseManager;
11
use Spiral\Database\Schemas\Prototypes\AbstractTable;
12
13
/**
14
 * Provides ability to identify database and local table name based on given AbstractTable schema.
15
 * Utilizes DatabaseManager.
16
 */
17
class AliasLookup
18
{
19
    /**
20
     * @var DatabaseManager
21
     */
22
    private $dbal;
23
24
    /**
25
     * @param DatabaseManager $dbal
26
     */
27
    public function __construct(DatabaseManager $dbal)
28
    {
29
        $this->dbal = $dbal;
30
    }
31
32
    /**
33
     * Local database alias (no prefix included).
34
     *
35
     * @param AbstractTable $table
36
     * @param bool          $initial Request initial table name.
37
     *
38
     * @return string
39
     */
40
    public function tableAlias(AbstractTable $table, bool $initial = false): string
41
    {
42
        if ($initial) {
43
            return substr($table->getInitialName(), strlen($table->getPrefix()));
44
        }
45
46
        return substr($table->getName(), strlen($table->getPrefix()));
47
    }
48
49
    /**
50
     * Database associated with given table schema.
51
     *
52
     * @param AbstractTable $table
53
     *
54
     * @return string
55
     */
56
    public function databaseAlias(AbstractTable $table): string
57
    {
58
        foreach ($this->dbal->getDatabases() as $database) {
59
            if (
60
                $table->getDriver() == $database->getDriver()
61
                && $table->getPrefix() == $database->getPrefix()
62
            ) {
63
                return $database->getName();
64
            }
65
        }
66
67
        throw new AtomizerException("Unable to find database associated with {$table}");
68
    }
69
}