ConnectionManager::buildFromConfig()   A
last analyzed

Complexity

Conditions 5
Paths 16

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.3888
c 0
b 0
f 0
cc 5
nc 16
nop 2
1
<?php
2
3
/**
4
 * @author Jared King <[email protected]>
5
 *
6
 * @see http://jaredtking.com
7
 *
8
 * @copyright 2015 Jared King
9
 * @license MIT
10
 */
11
12
namespace JAQB;
13
14
use InvalidArgumentException;
15
use JAQB\Exception\JAQBException;
16
use PDO;
17
18
/**
19
 * This class manages one or more PDO database connections.
20
 */
21
class ConnectionManager
22
{
23
    /**
24
     * @var array
25
     */
26
    private $config;
27
28
    /**
29
     * @var array
30
     */
31
    private $connections = [];
32
33
    /**
34
     * @var string|false
35
     */
36
    private $default;
37
38
    /**
39
     * @var array
40
     */
41
    private static $connectionParams = [
42
        'host' => 'host',
43
        'port' => 'port',
44
        'name' => 'dbname',
45
        'charset' => 'charset',
46
    ];
47
48
    /**
49
     * @param array $config
50
     */
51
    public function __construct(array $config = [])
52
    {
53
        $this->config = $config;
54
    }
55
56
    /**
57
     * Gets a database connection by ID.
58
     *
59
     * @param string $id
60
     *
61
     * @throws JAQBException if the connection does not exist
62
     *
63
     * @return QueryBuilder
64
     */
65
    public function get($id)
66
    {
67
        if (isset($this->connections[$id])) {
68
            return $this->connections[$id];
69
        }
70
71
        if (!isset($this->config[$id])) {
72
            throw new JAQBException('No configuration or connection has been supplied for the ID "'.$id.'".');
73
        }
74
75
        $this->connections[$id] = $this->buildFromConfig($this->config[$id], $id);
76
77
        return $this->connections[$id];
78
    }
79
80
    /**
81
     * Gets the default database connection.
82
     *
83
     * @throws JAQBException if there is not a default connection
84
     *
85
     * @return QueryBuilder
86
     */
87
    public function getDefault()
88
    {
89
        // get the memoized default
90
        if ($this->default) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->default of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
91
            return $this->get($this->default);
92
        }
93
94
        // no configurations available
95
        // check for existing connections
96
        if (0 === count($this->config)) {
97
            if (1 === count($this->connections)) {
98
                $this->default = array_keys($this->connections)[0];
0 ignored issues
show
Documentation Bug introduced by
It seems like array_keys($this->connections)[0] can also be of type integer. However, the property $default is declared as type string|false. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
99
100
                return $this->get($this->default);
101
            } elseif (count($this->connections) > 1) {
102
                throw new JAQBException('Could not determine the default connection because multiple connections were available and the default has not been set.');
103
            }
104
105
            throw new JAQBException('The default connection is not available because no configurations have been supplied.');
106
        }
107
108
        // handle the case where there is a single configuration
109
        if (1 === count($this->config)) {
110
            $this->default = array_keys($this->config)[0];
0 ignored issues
show
Documentation Bug introduced by
It seems like array_keys($this->config)[0] can also be of type integer. However, the property $default is declared as type string|false. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
111
112
            return $this->get($this->default);
113
        }
114
115
        // handle multiple configurations
116
        foreach ($this->config as $k => $v) {
117
            if (isset($v['default'])) {
118
                $this->default = $k;
0 ignored issues
show
Documentation Bug introduced by
It seems like $k can also be of type integer. However, the property $default is declared as type string|false. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
119
120
                return $this->get($this->default);
121
            }
122
        }
123
124
        throw new JAQBException('There is no default connection.');
125
    }
126
127
    /**
128
     * Adds a connection.
129
     *
130
     * @param string       $id
131
     * @param QueryBuilder $connection
132
     *
133
     * @throws InvalidArgumentException if a connection with the given ID already exists
134
     *
135
     * @return $this
136
     */
137
    public function add($id, QueryBuilder $connection)
138
    {
139
        if (isset($this->connections[$id])) {
140
            throw new InvalidArgumentException('A connection with the ID "'.$id.'" already exists.');
141
        }
142
143
        $this->connections[$id] = $connection;
144
        $this->default = false;
145
146
        return $this;
147
    }
148
149
    /**
150
     * Builds a new query builder instance from a configuration.
151
     * NOTE: This is not intended to be used outside of this class.
152
     *
153
     * @param array  $config
154
     * @param string $id
155
     *
156
     * @throws JAQBException
157
     *
158
     * @return QueryBuilder
159
     */
160
    public function buildFromConfig(array $config, $id)
161
    {
162
        // generate the dsn needed for PDO
163
        if (isset($config['dsn'])) {
164
            $dsn = $config['dsn'];
165
        } else {
166
            $dsn = $this->buildDsn($config, $id);
167
        }
168
169
        $user = isset($config['user']) ? $config['user'] : null;
170
        $password = isset($config['password']) ? $config['password'] : null;
171
        $options = isset($config['options']) ? $config['options'] : [];
172
173
        $pdo = new PDO($dsn, $user, $password, $options);
174
175
        return new QueryBuilder($pdo);
176
    }
177
178
    /**
179
     * Builds a PDO DSN string from a JAQB connection configuration.
180
     *
181
     * @param array  $config
182
     * @param string $id     configuration ID
183
     *
184
     * @throws JAQBException if the configuration is invalid
185
     *
186
     * @return string
187
     */
188
    public function buildDsn(array $config, $id)
189
    {
190
        if (!isset($config['type'])) {
191
            throw new JAQBException('Missing connection type for configuration "'.$id.'"!');
192
        }
193
194
        $dsn = $config['type'].':';
195
        $params = [];
196
        foreach (self::$connectionParams as $j => $k) {
197
            if (isset($config[$j])) {
198
                $params[] = $k.'='.$config[$j];
199
            }
200
        }
201
        $dsn .= implode(';', $params);
202
203
        return $dsn;
204
    }
205
}
206