Passed
Branch dev (d14b82)
by Wilmer
12:57
created

ConnectionPDOPgsql   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 255
Duplicated Lines 0 %

Test Coverage

Coverage 98.13%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 98
c 1
b 0
f 0
dl 0
loc 255
ccs 105
cts 107
cp 0.9813
rs 9.0399
wmc 42

18 Methods

Rating   Name   Duplication   Size   Complexity  
A isActive() 0 3 1
A getDriver() 0 3 1
A getPDO() 0 3 1
A getSchema() 0 7 2
A getDriverName() 0 3 1
A createCommand() 0 17 4
B open() 0 34 6
A __construct() 0 6 1
A __clone() 0 9 2
A initConnection() 0 16 5
A getQueryBuilder() 0 11 2
A getQuoter() 0 7 2
A getMasterPdo() 0 4 1
A __sleep() 0 13 1
A getServerVersion() 0 9 3
A getSlavePdo() 0 10 3
A createTransaction() 0 3 1
A close() 0 27 5

How to fix   Complexity   

Complex Class

Complex classes like ConnectionPDOPgsql often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ConnectionPDOPgsql, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql\PDO;
6
7
use PDO;
8
use PDOException;
9
use Psr\Log\LogLevel;
10
use Yiisoft\Db\Cache\QueryCache;
11
use Yiisoft\Db\Cache\SchemaCache;
12
use Yiisoft\Db\Command\CommandInterface;
13
use Yiisoft\Db\Connection\Connection;
14
use Yiisoft\Db\Connection\ConnectionPDOInterface;
15
use Yiisoft\Db\Driver\PDODriver;
16
use Yiisoft\Db\Exception\Exception;
17
use Yiisoft\Db\Exception\InvalidConfigException;
18
use Yiisoft\Db\Query\QueryBuilderInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\QueryBuilderInterface 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...
19
use Yiisoft\Db\Schema\Quoter;
20
use Yiisoft\Db\Schema\QuoterInterface;
21
use Yiisoft\Db\Schema\SchemaInterface;
22
use Yiisoft\Db\Transaction\TransactionInterface;
23
24
/**
25
 * The class Connection represents a connection to a database via [PDO](https://secure.php.net/manual/en/book.pdo.php).
26
 */
27
final class ConnectionPDOPgsql extends Connection implements ConnectionPDOInterface
28
{
29
    private ?PDO $pdo = null;
30
    private ?QueryBuilderInterface $queryBuilder = null;
31
    private ?QuoterInterface $quoter = null;
32
    private ?SchemaInterface $schema = null;
33
    private string $serverVersion = '';
34
35 452
    public function __construct(
36
        private PDODriver $driver,
37
        private QueryCache $queryCache,
38
        private SchemaCache $schemaCache
39
    ) {
40 452
        parent::__construct($queryCache);
41
    }
42
43
    /**
44
     * Reset the connection after cloning.
45
     */
46 1
    public function __clone()
47
    {
48 1
        $this->master = null;
49 1
        $this->slave = null;
50 1
        $this->transaction = null;
51
52 1
        if (strncmp($this->driver->getDsn(), 'sqlite::memory:', 15) !== 0) {
53
            /** reset PDO connection, unless its sqlite in-memory, which can only have one connection */
54 1
            $this->pdo = null;
55
        }
56
    }
57
58
    /**
59
     * Close the connection before serializing.
60
     *
61
     * @return array
62
     */
63 2
    public function __sleep(): array
64
    {
65 2
        $fields = (array) $this;
66
67
        unset(
68 2
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
69 2
            $fields["\000" . __CLASS__ . "\000" . 'master'],
70 2
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
71 2
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
72 2
            $fields["\000" . __CLASS__ . "\000" . 'schema']
73
        );
74
75 2
        return array_keys($fields);
76
    }
77
78 401
    public function createCommand(?string $sql = null, array $params = []): CommandInterface
79
    {
80 401
        $command = new CommandPDOPgsql($this, $this->queryCache);
81
82 401
        if ($sql !== null) {
83 191
            $command->setSql($sql);
84
        }
85
86 401
        if ($this->logger !== null) {
87 401
            $command->setLogger($this->logger);
88
        }
89
90 401
        if ($this->profiler !== null) {
91 401
            $command->setProfiler($this->profiler);
92
        }
93
94 401
        return $command->bindValues($params);
95
    }
96
97 8
    public function createTransaction(): TransactionInterface
98
    {
99 8
        return new TransactionPDOPgsql($this);
100
    }
101
102 452
    public function close(): void
103
    {
104 452
        if (!empty($this->master)) {
105
            /** @var ConnectionPDOPgsql */
106 2
            $db = $this->master;
107
108 2
            if ($this->pdo === $db->getPDO()) {
0 ignored issues
show
Bug introduced by
The method getPDO() does not exist on Yiisoft\Db\Connection\ConnectionInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Yiisoft\Db\Connection\Connection. Are you sure you never get one of those? ( Ignorable by Annotation )

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

108
            if ($this->pdo === $db->/** @scrutinizer ignore-call */ getPDO()) {
Loading history...
109 2
                $this->pdo = null;
110
            }
111
112 2
            $db->close();
113 2
            $this->master = null;
114
        }
115
116 452
        if ($this->pdo !== null) {
117 195
            $this->logger?->log(
118
                LogLevel::DEBUG,
119 193
                'Closing DB connection: ' . $this->driver->getDsn() . ' ' . __METHOD__,
120
            );
121
122 195
            $this->pdo = null;
123 195
            $this->transaction = null;
124
        }
125
126 452
        if (!empty($this->slave)) {
127 1
            $this->slave->close();
128 1
            $this->slave = null;
129
        }
130
    }
131
132 170
    public function getDriver(): PDODriver
133
    {
134 170
        return $this->driver;
135
    }
136
137 11
    public function getDriverName(): string
138
    {
139 11
        return 'pgsql';
140
    }
141
142 192
    public function getMasterPdo(): PDO|null
143
    {
144 192
        $this->open();
145 192
        return $this->pdo;
146
    }
147
148 48
    public function getPDO(): ?PDO
149
    {
150 48
        return $this->pdo;
151
    }
152
153
    /**
154
     * @throws Exception|InvalidConfigException
155
     */
156 401
    public function getQueryBuilder(): QueryBuilderInterface
157
    {
158 401
        if ($this->queryBuilder === null) {
159 401
            $this->queryBuilder = new QueryBuilderPDOPgsql(
160 401
                $this->createCommand(),
161 401
                $this->getQuoter(),
162 401
                $this->getSchema(),
163
            );
164
        }
165
166 401
        return $this->queryBuilder;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->queryBuilder could return the type null which is incompatible with the type-hinted return Yiisoft\Db\Query\QueryBuilderInterface. Consider adding an additional type-check to rule them out.
Loading history...
167
    }
168
169 405
    public function getQuoter(): QuoterInterface
170
    {
171 405
        if ($this->quoter === null) {
172 405
            $this->quoter = new Quoter('"', '"', $this->getTablePrefix());
173
        }
174
175 405
        return $this->quoter;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->quoter could return the type null which is incompatible with the type-hinted return Yiisoft\Db\Schema\QuoterInterface. Consider adding an additional type-check to rule them out.
Loading history...
176
    }
177
178
    /**
179
     * @throws Exception
180
     */
181 105
    public function getServerVersion(): string
182
    {
183 105
        if ($this->serverVersion === '') {
184
            /** @var mixed */
185 105
            $version = $this->getSlavePDO()?->getAttribute(PDO::ATTR_SERVER_VERSION);
186 105
            $this->serverVersion = is_string($version) ? $version : 'Version could not be determined.';
187
        }
188
189 105
        return $this->serverVersion;
190
    }
191
192 418
    public function getSchema(): SchemaInterface
193
    {
194 418
        if ($this->schema === null) {
195 418
            $this->schema = new SchemaPDOPgsql($this, $this->schemaCache);
196
        }
197
198 418
        return $this->schema;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->schema could return the type null which is incompatible with the type-hinted return Yiisoft\Db\Schema\SchemaInterface. Consider adding an additional type-check to rule them out.
Loading history...
199
    }
200
201 188
    public function getSlavePdo(bool $fallbackToMaster = true): ?PDO
202
    {
203
        /** @var ConnectionPDOPgsql|null $db */
204 188
        $db = $this->getSlave(false);
205
206 188
        if ($db === null) {
207 187
            return $fallbackToMaster ? $this->getMasterPdo() : null;
208
        }
209
210 1
        return $db->getPDO();
211
    }
212
213 12
    public function isActive(): bool
214
    {
215 12
        return $this->pdo !== null;
216
    }
217
218 198
    public function open(): void
219
    {
220 198
        if (!empty($this->pdo)) {
221 175
            return;
222
        }
223
224 198
        if (!empty($this->masters)) {
225
            /** @var ConnectionPDOPgsql|null */
226 2
            $db = $this->getMaster();
227
228 2
            if ($db !== null) {
229 2
                $this->pdo = $db->getPDO();
230 2
                return;
231
            }
232
233 2
            throw new InvalidConfigException('None of the master DB servers is available.');
234
        }
235
236 198
        if (empty($this->driver->getDsn())) {
237
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
238
        }
239
240 198
        $token = 'Opening DB connection: ' . $this->driver->getDsn();
241
242
        try {
243 198
            $this->logger?->log(LogLevel::INFO, $token);
244 198
            $this->profiler?->begin($token, [__METHOD__]);
245 198
            $this->initConnection();
246 198
            $this->profiler?->end($token, [__METHOD__]);
247 3
        } catch (PDOException $e) {
248 3
            $this->profiler?->end($token, [__METHOD__]);
249 3
            $this->logger?->log(LogLevel::ERROR, $token);
250
251 3
            throw new Exception($e->getMessage(), (array) $e->errorInfo, $e);
252
        }
253
    }
254
255
    /**
256
     * Initializes the DB connection.
257
     *
258
     * This method is invoked right after the DB connection is established.
259
     *
260
     * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`.
261
     *
262
     * if {@see emulatePrepare} is true, and sets the database {@see charset} if it is not empty.
263
     *
264
     * It then triggers an {@see EVENT_AFTER_OPEN} event.
265
     */
266 198
    protected function initConnection(): void
267
    {
268 198
        if ($this->pdo === null) {
269 198
            $this->pdo = $this->driver->createConnection();
270
        }
271
272 198
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
0 ignored issues
show
Bug introduced by
The method setAttribute() does not exist on null. ( Ignorable by Annotation )

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

272
        $this->pdo->/** @scrutinizer ignore-call */ 
273
                    setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
273
274 198
        if ($this->getEmulatePrepare() !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
275 1
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->getEmulatePrepare());
276
        }
277
278 198
        $charset = $this->driver->getCharset();
279
280 198
        if ($charset !== null) {
281
            $this->pdo->exec('SET NAMES ' . $this->pdo->quote($charset));
282
        }
283
    }
284
}
285