Test Failed
Pull Request — master (#66)
by Wilmer
18:24 queued 07:05
created

ConnectionPDOMssql::getPDO()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mssql\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;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Command\CommandInterface 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...
13
use Yiisoft\Db\Connection\Connection;
14
use Yiisoft\Db\Connection\ConnectionPDOInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Connection\ConnectionPDOInterface 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...
15
use Yiisoft\Db\Driver\PDODriver;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Driver\PDODriver 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...
16
use Yiisoft\Db\Exception\Exception;
17
use Yiisoft\Db\Exception\InvalidConfigException;
18
use Yiisoft\Db\Mssql\Quoter;
19
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...
20
use Yiisoft\Db\Schema\QuoterInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Schema\QuoterInterface 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...
21
use Yiisoft\Db\Schema\SchemaInterface;
22
use Yiisoft\Db\Transaction\TransactionInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Transaction\TransactionInterface 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...
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 ConnectionPDOMssql 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
    public function __construct(
36
        private PDODriver $driver,
37
        private QueryCache $queryCache,
38
        private SchemaCache $schemaCache
39
    ) {
40
        parent::__construct($queryCache);
0 ignored issues
show
Bug introduced by
The call to Yiisoft\Db\Connection\Connection::__construct() has too few arguments starting with queryCache. ( Ignorable by Annotation )

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

40
        parent::/** @scrutinizer ignore-call */ 
41
                __construct($queryCache);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
Bug introduced by
$queryCache of type Yiisoft\Db\Cache\QueryCache is incompatible with the type string expected by parameter $dsn of Yiisoft\Db\Connection\Connection::__construct(). ( Ignorable by Annotation )

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

40
        parent::__construct(/** @scrutinizer ignore-type */ $queryCache);
Loading history...
41
    }
42
43
    /**
44
     * Reset the connection after cloning.
45
     */
46
    public function __clone()
47
    {
48
        $this->master = null;
49
        $this->slave = null;
50
        $this->transaction = null;
51
52
        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
            $this->pdo = null;
55
        }
56
    }
57
58
    /**
59
     * Close the connection before serializing.
60
     *
61
     * @return array
62
     */
63
    public function __sleep(): array
64
    {
65
        $fields = (array) $this;
66
67
        unset(
68
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
69
            $fields["\000" . __CLASS__ . "\000" . 'master'],
70
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
71
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
72
            $fields["\000" . __CLASS__ . "\000" . 'schema']
73
        );
74
75
        return array_keys($fields);
76
    }
77
78
    public function createCommand(?string $sql = null, array $params = []): CommandInterface
79
    {
80
        $command = new CommandPDOMssql($this, $this->queryCache);
81
82
        if ($sql !== null) {
83
            $command->setSql($sql);
84
        }
85
86
        if ($this->logger !== null) {
87
            $command->setLogger($this->logger);
88
        }
89
90
        if ($this->profiler !== null) {
91
            $command->setProfiler($this->profiler);
92
        }
93
94
        return $command->bindValues($params);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $command->bindValues($params) returns the type Yiisoft\Db\Mssql\PDO\CommandPDOMssql which is incompatible with the type-hinted return Yiisoft\Db\Command\CommandInterface.
Loading history...
95
    }
96
97
    public function createTransaction(): TransactionInterface
98
    {
99
        return new TransactionPDOMssql($this);
100
    }
101
102
    public function close(): void
103
    {
104
        if (!empty($this->master)) {
105
            /** @var ConnectionPDOMssql */
106
            $db = $this->master;
107
108
            if ($this->pdo === $db->getPDO()) {
109
                $this->pdo = null;
110
            }
111
112
            $db->close();
113
            $this->master = null;
114
        }
115
116
        if ($this->pdo !== null) {
117
            $this->logger?->log(
118
                LogLevel::DEBUG,
119
                'Closing DB connection: ' . $this->driver->getDsn() . ' ' . __METHOD__,
120
            );
121
122
            $this->pdo = null;
123
            $this->transaction = null;
124
        }
125
126
        if (!empty($this->slave)) {
127
            $this->slave->close();
128
            $this->slave = null;
129
        }
130
    }
131
132
    public function getDriver(): PDODriver
133
    {
134
        return $this->driver;
135
    }
136
137
    public function getDriverName(): string
138
    {
139
        return 'sqlsrv';
140
    }
141
142
    public function getMasterPdo(): PDO|null
143
    {
144
        $this->open();
145
        return $this->pdo;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->pdo also could return the type null which is incompatible with the return type mandated by Yiisoft\Db\Connection\Connection::getMasterPdo() of PDO.
Loading history...
146
    }
147
148
    public function getPDO(): ?PDO
149
    {
150
        return $this->pdo;
151
    }
152
153
    /**
154
     * @throws Exception|InvalidConfigException
155
     */
156
    public function getQueryBuilder(): QueryBuilderInterface
157
    {
158
        if ($this->queryBuilder === null) {
159
            $this->queryBuilder = new QueryBuilderPDOMssql(
160
                $this->createCommand(),
161
                $this->getQuoter(),
162
                $this->getSchema(),
163
            );
164
        }
165
166
        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
    public function getQuoter(): QuoterInterface
170
    {
171
        if ($this->quoter === null) {
172
            $this->quoter = new Quoter(['[', ']'], ['[', ']'], $this->getTablePrefix());
173
        }
174
175
        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
    public function getServerVersion(): string
182
    {
183
        if ($this->serverVersion === '') {
184
            /** @var mixed */
185
            $version = $this->getSlavePDO()?->getAttribute(PDO::ATTR_SERVER_VERSION);
186
            $this->serverVersion = is_string($version) ? $version : 'Version could not be determined.';
187
        }
188
189
        return $this->serverVersion;
190
    }
191
192
    public function getSchema(): SchemaInterface
193
    {
194
        if ($this->schema === null) {
195
            $this->schema = new SchemaPDOMssql($this, $this->schemaCache);
196
        }
197
198
        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
    public function getSlavePdo(bool $fallbackToMaster = true): ?PDO
202
    {
203
        /** @var ConnectionPDOMssql|null $db */
204
        $db = $this->getSlave(false);
205
206
        if ($db === null) {
207
            return $fallbackToMaster ? $this->getMasterPdo() : null;
208
        }
209
210
        return $db->getPDO();
211
    }
212
213
    public function isActive(): bool
214
    {
215
        return $this->pdo !== null;
216
    }
217
218
    public function open(): void
219
    {
220
        if (!empty($this->pdo)) {
221
            return;
222
        }
223
224
        if (!empty($this->masters)) {
0 ignored issues
show
Bug introduced by
The property masters is declared private in Yiisoft\Db\Connection\Connection and cannot be accessed from this context.
Loading history...
225
            /** @var ConnectionPDOMssql|null */
226
            $db = $this->getMaster();
227
228
            if ($db !== null) {
229
                $this->pdo = $db->getPDO();
230
                return;
231
            }
232
233
            throw new InvalidConfigException('None of the master DB servers is available.');
234
        }
235
236
        if (empty($this->driver->getDsn())) {
237
            throw new InvalidConfigException('Connection::dsn cannot be empty.');
238
        }
239
240
        $token = 'Opening DB connection: ' . $this->driver->getDsn();
241
242
        try {
243
            $this->logger?->log(LogLevel::INFO, $token);
244
            $this->profiler?->begin($token, [__METHOD__]);
245
            $this->initConnection();
246
            $this->profiler?->end($token, [__METHOD__]);
247
        } catch (PDOException $e) {
248
            $this->profiler?->end($token, [__METHOD__]);
249
            $this->logger?->log(LogLevel::ERROR, $token);
250
251
            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
    protected function initConnection(): void
267
    {
268
        $this->pdo = $this->driver->createConnection();
269
270
        $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

270
        $this->pdo->/** @scrutinizer ignore-call */ 
271
                    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...
271
272
        if (in_array($this->getDriverName(), ['mssql', 'dblib'], true)) {
273
            $this->pdo->exec('SET ANSI_NULL_DFLT_ON ON');
274
        }
275
    }
276
}
277