Completed
Push — master ( 7a6bdd...324ce1 )
by Sébastien
09:34
created

ConnectionRegistry::getDefaultConfiguration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Bdf\Prime\Connection;
4
5
use Bdf\Dsn\Dsn;
6
use Bdf\Prime\Configuration;
7
use Bdf\Prime\Connection\Factory\ConnectionFactory;
8
use Bdf\Prime\Connection\Factory\ConnectionFactoryInterface;
9
use Bdf\Prime\ConnectionRegistryInterface;
10
use Bdf\Prime\Exception\DBALException;
11
12
/**
13
 * ConnectionRegistry
14
 */
15
class ConnectionRegistry implements ConnectionRegistryInterface
16
{
17
    /**
18
     * The connection factory
19
     *
20
     * @var ConnectionFactoryInterface
21
     */
22
    private $connectionFactory;
0 ignored issues
show
Coding Style introduced by
Expected 1 blank line(s) before first member var; 0 found
Loading history...
23
24
    /**
25
     * Default configuration to use
26
     *
27
     * @var Configuration
28
     */
29
    private $defaultConfig;
30
31
    /**
32
     * The configuration map
33
     * Contains configuration of some connections
0 ignored issues
show
introduced by
Doc comment short description must be on a single line, further text should be a separate paragraph
Loading history...
34
     *
35
     * @var array
36
     */
37
    private $parametersMap;
38
39
    /**
40
     * The drive name alias
41
     *
42
     * @var array
43
     */
44
    static private $driverSchemeAliases = [
0 ignored issues
show
Coding Style introduced by
The static declaration must come after the visibility declaration
Loading history...
45
        'db2'        => 'ibm_db2',
46
        'mssql'      => 'pdo_sqlsrv',
47
        'mysql'      => 'pdo_mysql',
48
        'mysql2'     => 'pdo_mysql', // Amazon RDS, for some weird reason
0 ignored issues
show
Coding Style introduced by
Comments may not appear after statements
Loading history...
49
        'postgres'   => 'pdo_pgsql',
50
        'postgresql' => 'pdo_pgsql',
51
        'pgsql'      => 'pdo_pgsql',
52
        'sqlite'     => 'pdo_sqlite',
53
        'sqlite3'    => 'pdo_sqlite',
54
    ];
55
56
    /**
57
     * Set default configuration
58
     *
59
     * @param array $parametersMap
60
     * @param ConnectionFactoryInterface $connectionFactory
61
     * @param Configuration|null $defaultConfig
62
     */
63 181
    public function __construct(array $parametersMap = [], ConnectionFactoryInterface $connectionFactory = null, Configuration $defaultConfig = null)
64
    {
65 181
        $this->parametersMap = $parametersMap;
66 181
        $this->connectionFactory = $connectionFactory ?: new ConnectionFactory();
0 ignored issues
show
Coding Style introduced by
The value of a comparison must not be assigned to a variable
Loading history...
Coding Style introduced by
Inline IF statements are not allowed
Loading history...
Coding Style introduced by
Inline shorthand IF statement requires brackets around comparison
Loading history...
67 181
        $this->defaultConfig = $defaultConfig ?: new Configuration();
0 ignored issues
show
Coding Style introduced by
The value of a comparison must not be assigned to a variable
Loading history...
Coding Style introduced by
Inline IF statements are not allowed
Loading history...
Coding Style introduced by
Inline shorthand IF statement requires brackets around comparison
Loading history...
68 181
    }
69
    
70
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $name should have a doc-comment as per coding-style.
Loading history...
71
     * {@inheritDoc}
72
     */
73 142
    public function getConnection(string $name): ConnectionInterface
74
    {
75 142
        return $this->connectionFactory->create($name, $this->getConnectionParameters($name), $this->defaultConfig);
76
    }
77
78
    /**
79
     * Associate configuration to connection
80
     *
81
     * @param string $connectionName
82
     * @param string|array $parameters
83
     */
84 44
    public function declareConnection(string $connectionName, $parameters)
85
    {
86 44
        $this->parametersMap[$connectionName] = $parameters;
87 44
    }
88
89
    /**
90
     * {@inheritDoc}
91
     */
92 5
    public function getConnectionNames(): array
93
    {
94
        // TODO Legacy: will be removed
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
95 5
        if (empty($this->parametersMap)) {
96 2
            return array_keys($this->defaultConfig->getDbConfig()->all());
0 ignored issues
show
Deprecated Code introduced by
The function Bdf\Prime\Configuration::getDbConfig() has been deprecated: Since 1.1. Use ConnectionRegistry to declare your connections. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

96
            return array_keys(/** @scrutinizer ignore-deprecated */ $this->defaultConfig->getDbConfig()->all());

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
97
        }
98
99 3
        return array_keys($this->parametersMap);
100
    }
101
102
    /**
103
     * Get the global config
104
     *
105
     * @return Configuration
106
     */
107 147
    public function getDefaultConfiguration(): Configuration
108
    {
109 147
        return $this->defaultConfig;
110
    }
111
112
    /**
113
     * Create the doctrine config for the connection
114
     *
115
     * @param string $connectionName
116
     *
117
     * @return array
118
     */
0 ignored issues
show
Coding Style Documentation introduced by
Missing @throws tag in function comment
Loading history...
119 142
    private function getConnectionParameters(string $connectionName): array
0 ignored issues
show
Coding Style introduced by
Private method name "ConnectionRegistry::getConnectionParameters" must be prefixed with an underscore
Loading history...
120
    {
121
        // TODO Legacy: will be removed
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
122 142
        if (empty($this->parametersMap)) {
123 2
            $this->parametersMap = $this->defaultConfig->getDbConfig()->all();
0 ignored issues
show
Deprecated Code introduced by
The function Bdf\Prime\Configuration::getDbConfig() has been deprecated: Since 1.1. Use ConnectionRegistry to declare your connections. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

123
            $this->parametersMap = /** @scrutinizer ignore-deprecated */ $this->defaultConfig->getDbConfig()->all();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
124
        }
125
126 142
        if (!isset($this->parametersMap[$connectionName])) {
127 1
            throw new DBALException('Connection name "' . $connectionName . '" is not set');
128
        }
129
130 141
        $parameters = $this->parametersMap[$connectionName];
131
132
        // Manage string configuration as dsn
133 141
        if (is_string($parameters)) {
134 25
            $parameters = ['url' => $parameters];
135
        }
136
137
        //@todo move in factory ? Allows shard / slave to use url as parameter. Otherwise doctrine will evaluate the url
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
Coding Style introduced by
No space found before comment text; expected "// @todo move in factory ? Allows shard / slave to use url as parameter. Otherwise doctrine will evaluate the url" but found "//@todo move in factory ? Allows shard / slave to use url as parameter. Otherwise doctrine will evaluate the url"
Loading history...
138
        // Url key describe a dsn. Extract item from dsn and merge info the current config
139 141
        if (isset($parameters['url'])) {
140 28
            $parameters = array_merge($parameters, $this->parseDsn($parameters['url']));
141
            // Remove url: don't let doctrine parse the url
142 28
            unset($parameters['url']);
143
        }
144
145 141
        return $parameters;
146
    }
147
148
    /**
149
     * Parse the dsn string
150
     *
151
     * @param string $dsn
152
     *
153
     * @return array
154
     */
155 28
    private function parseDsn(string $dsn): array
0 ignored issues
show
Coding Style introduced by
Private method name "ConnectionRegistry::parseDsn" must be prefixed with an underscore
Loading history...
156
    {
157 28
        $request = Dsn::parse($dsn);
158
159 28
        $parameters = $request->getQuery() + [
0 ignored issues
show
Coding Style introduced by
Operation must be bracketed
Loading history...
160 28
                'host' => $request->getHost(),
0 ignored issues
show
Coding Style introduced by
Array key not indented correctly; expected 12 spaces but found 16
Loading history...
161 28
                'port' => $request->getPort(),
0 ignored issues
show
Coding Style introduced by
Array key not indented correctly; expected 12 spaces but found 16
Loading history...
162 28
                'user' => $request->getUser(),
0 ignored issues
show
Coding Style introduced by
Array key not indented correctly; expected 12 spaces but found 16
Loading history...
163 28
                'password' => $request->getPassword(),
0 ignored issues
show
Coding Style introduced by
Array key not indented correctly; expected 12 spaces but found 16
Loading history...
164
            ];
0 ignored issues
show
Coding Style introduced by
Array close brace not indented correctly; expected 8 spaces but found 12
Loading history...
introduced by
Array closing indentation error, expected 8 spaces but found 12
Loading history...
165
166
        // Get drive from alias or manage synthax 'pdo+mysql' because '_' are not allowed in scheme
167 28
        $parameters['driver'] = self::$driverSchemeAliases[$request->getScheme()] ?? str_replace('+', '_', $request->getScheme());
0 ignored issues
show
Coding Style introduced by
Operation must be bracketed
Loading history...
168
169
        // SQLite option: dont create dbname key use by many drivers
170
        // Sqlite drive needs memory or path key
171
        // Remove the 'path' if not used by sqlite
172 28
        if (strpos($parameters['driver'], 'sqlite') !== false) {
173 25
            if ($request->getPath() === ':memory:') {
174 24
                $parameters['memory'] = true;
175
            } else {
176 25
                $parameters['path'] = $request->getPath();
177
            }
178 3
        } elseif (!isset($parameters['dbname'])) {
0 ignored issues
show
Coding Style introduced by
Usage of ELSEIF not allowed; use ELSE IF instead
Loading history...
179 1
            $parameters['dbname'] = trim($request->getPath(), '/');
180
        }
181
182 28
        return $parameters;
183
    }
184
}
185