Passed
Push — master ( 741573...865dac )
by Luiz Kim
13:17 queued 04:55
created

DatabaseSwitchService::getDomain()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 21
rs 9.8333
cc 2
nc 2
nop 1
1
<?php
2
3
namespace ControleOnline\Service;
4
5
use Doctrine\DBAL\Connection;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Connection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Doctrine\DBAL\Platforms\SQLServer2012Platform;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Platforms\SQLServer2012Platform was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Doctrine\DBAL\Platforms\MySqlPlatform;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Platforms\MySqlPlatform was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use InvalidArgumentException;
9
10
class DatabaseSwitchService
11
{
12
    /**
13
     * @var Connection
14
     */
15
    private $connection;
16
    /**
17
     * @var array
18
     */
19
    private static $originalDbParams;
20
21
22
    /**
23
     * DatabaseSwitchService constructor.
24
     * @param Connection $connection
25
     */
26
    public function __construct(Connection $connection)
27
    {
28
        $this->connection = $connection;
29
        if (!self::$originalDbParams)
0 ignored issues
show
Bug Best Practice introduced by
The expression self::originalDbParams of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
30
            self::$originalDbParams = $connection->getParams();
31
    }
32
33
    /* @param string $domain
34
     * @throws \Doctrine\DBAL\Driver\Exception
35
     * @throws \Doctrine\DBAL\Exception
36
     */
37
    public function switchDatabaseByDomain($domain)
38
    {
39
        $this->switchDatabase($this->getDbData($domain));
40
    }
41
42
    /**
43
     * @param string $domain
44
     * @return bool
45
     */
46
    public function switchBackToOriginalDatabase()
47
    {
48
        $this->switchDatabase(self::$originalDbParams);
49
    }
50
51
    /**
52
     * @param array $dbData
53
     */
54
    private function switchDatabase($dbData)
55
    {
56
        if ($this->connection->isConnected())
57
            $this->connection->close();
58
59
        $this->connection->__construct(
60
            $dbData,
61
            $this->getDriverClass($dbData),
62
            $this->connection->getConfiguration(),
63
            $this->connection->getEventManager()
64
        );
65
66
        $this->connection->connect();
67
    }
68
69
    /**
70
     * @param string $domain
71
     * @return array
72
     * @throws \Doctrine\DBAL\Driver\Exception
73
     * @throws \Doctrine\DBAL\Exception
74
     * @throws \Doctrine\DBAL\Driver\Exception
75
     */
76
    private function getDbData($domain)
77
    {
78
        $this->switchBackToOriginalDatabase();
79
        $params = $this->connection->getParams();
80
        $sql = 'SELECT db_host, db_name, db_port, db_user, db_driver, db_instance, 
81
            AES_DECRYPT(db_password, :tenancy_secret) AS db_password
82
            FROM `databases` WHERE app_host = :app_host';
83
84
        $statement = $this->connection->executeQuery(
85
            $sql,
86
            [
87
                'app_host' => $domain,
88
                'tenancy_secret' => $_ENV['TENENCY_SECRET']
89
            ],
90
            ['app_host' => \PDO::PARAM_STR, 'tenancy_secret' => \PDO::PARAM_STR]
91
        );
92
93
        $result = $statement->fetchAssociative();
94
        $params['platform'] = $this->getPlatform($result['db_driver']);
95
        $params['host'] = $result['db_host'];
96
        $params['port'] = $result['db_port'];
97
        $params['dbname'] = $result['db_name'];
98
        $params['user'] = $result['db_user'];
99
        $params['password'] = $result['db_password'];
100
        $params['driver'] = $result['db_driver'];
101
        $params['instancename'] = $result['db_instance'];
102
        return  $params;
103
    }
104
105
    /**
106
     * @return array
107
     * @throws \Doctrine\DBAL\Driver\Exception
108
     * @throws \Doctrine\DBAL\Exception
109
     */
110
    public function getAllDomains()
111
    {
112
        $this->switchBackToOriginalDatabase();
113
        $sql = 'SELECT app_host FROM `databases`';
114
        $statement = $this->connection->executeQuery($sql);
115
        $results = $statement->fetchAllAssociative();
116
        $domains = array_column($results, 'app_host');
117
        return $domains;
118
    }
119
120
    /**
121
     * @param array $dbData
122
     * @return mixed
123
     */
124
    private function getDriverClass($dbData)
125
    {
126
        $driverClass = null;
127
        switch ($dbData['driver']) {
128
            case 'pdo_mysql':
129
                $driverClass = \Doctrine\DBAL\Driver\PDO\MySql\Driver::class;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Driver\PDO\MySql\Driver was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
130
                break;
131
            case 'pdo_sqlsrv':
132
                $driverClass = \Doctrine\DBAL\Driver\PDO\SQLSrv\Driver::class;
0 ignored issues
show
Bug introduced by
The type Doctrine\DBAL\Driver\PDO\SQLSrv\Driver was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
133
                break;
134
            default:
135
                throw new InvalidArgumentException('Driver not supported: ' . $dbData['driver']);
136
        }
137
138
        // Construa a instância do driver
139
        return new $driverClass();
140
    }
141
142
    /**
143
     * @param string $db_driver
144
     * @return MySqlPlatform|SQLServer2012Platform
145
     */
146
    private function getPlatform($db_driver)
147
    {
148
        switch ($db_driver) {
149
            case 'pdo_mysql':
150
                return new MySqlPlatform();
151
            case 'pdo_sqlsrv':
152
                return new SQLServer2012Platform();
153
            default:
154
                throw new InvalidArgumentException('Driver not supported: ' . $db_driver);
155
        }
156
    }
157
158
  
159
}
160