Test Failed
Pull Request — master (#82)
by Wilmer
24:21 queued 13:10
created

ConnectionPDOSqlite::close()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 27
rs 9.4555
c 1
b 0
f 0
cc 5
nc 12
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Sqlite\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\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;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Schema\Quoter 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
use function constant;
25
use function strncmp;
26
27
/**
28
 * Database connection class prefilled for MYSQL Server.
29
 */
30
final class ConnectionPDOSqlite extends Connection implements ConnectionPDOInterface
31
{
32
    private ?PDO $pdo = null;
33
    private ?QueryBuilderInterface $queryBuilder = null;
34
    private ?QuoterInterface $quoter = null;
35
    private ?SchemaInterface $schema = null;
36
    private string $serverVersion = '';
37
38
    public function __construct(
39
        private PDODriver $driver,
40
        private QueryCache $queryCache,
41
        private SchemaCache $schemaCache
42
    ) {
43
        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

43
        parent::/** @scrutinizer ignore-call */ 
44
                __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

43
        parent::__construct(/** @scrutinizer ignore-type */ $queryCache);
Loading history...
44
    }
45
46
    /**
47
     * Reset the connection after cloning.
48
     */
49
    public function __clone()
50
    {
51
        $this->master = null;
52
        $this->slave = null;
53
        $this->transaction = null;
54
55
        if (strncmp($this->driver->getDsn(), 'sqlite::memory:', 15) !== 0) {
56
            /** reset PDO connection, unless its sqlite in-memory, which can only have one connection */
57
            $this->pdo = null;
58
        }
59
    }
60
61
    /**
62
     * Close the connection before serializing.
63
     *
64
     * @return array
65
     */
66
    public function __sleep(): array
67
    {
68
        $fields = (array) $this;
69
70
        unset(
71
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
72
            $fields["\000" . __CLASS__ . "\000" . 'master'],
73
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
74
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
75
            $fields["\000" . __CLASS__ . "\000" . 'schema']
76
        );
77
78
        return array_keys($fields);
79
    }
80
81
    public function createCommand(?string $sql = null, array $params = []): CommandInterface
82
    {
83
        $command = new CommandPDOSqlite($this, $this->queryCache);
84
85
        if ($sql !== null) {
86
            $command->setSql($sql);
87
        }
88
89
        if ($this->logger !== null) {
90
            $command->setLogger($this->logger);
91
        }
92
93
        if ($this->profiler !== null) {
94
            $command->setProfiler($this->profiler);
95
        }
96
97
        return $command->bindValues($params);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $command->bindValues($params) returns the type Yiisoft\Db\Sqlite\PDO\CommandPDOSqlite which is incompatible with the type-hinted return Yiisoft\Db\Command\CommandInterface.
Loading history...
98
    }
99
100
    public function createTransaction(): TransactionInterface
101
    {
102
        return new TransactionPDOSqlite($this);
103
    }
104
105
    public function close(): void
106
    {
107
        if (!empty($this->master)) {
108
            /** @var ConnectionPDOSqlite */
109
            $db = $this->master;
110
111
            if ($this->pdo === $db->getPDO()) {
112
                $this->pdo = null;
113
            }
114
115
            $db->close();
116
            $this->master = null;
117
        }
118
119
        if ($this->pdo !== null) {
120
            $this->logger?->log(
121
                LogLevel::DEBUG,
122
                'Closing DB connection: ' . $this->driver->getDsn() . ' ' . __METHOD__,
123
            );
124
125
            $this->pdo = null;
126
            $this->transaction = null;
127
        }
128
129
        if (!empty($this->slave)) {
130
            $this->slave->close();
131
            $this->slave = null;
132
        }
133
    }
134
135
    public function getDriver(): PDODriver
136
    {
137
        return $this->driver;
138
    }
139
140
    public function getDriverName(): string
141
    {
142
        return 'sqlite';
143
    }
144
145
    public function getMasterPdo(): PDO|null
146
    {
147
        $this->open();
148
        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...
149
    }
150
151
    public function getPDO(): ?PDO
152
    {
153
        return $this->pdo;
154
    }
155
156
    public function getQueryBuilder(): QueryBuilderInterface
157
    {
158
        if ($this->queryBuilder === null) {
159
            $this->queryBuilder = new QueryBuilderPDOSqlite(
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 SchemaPDOSqlite($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 ConnectionPDOSqlite|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 ConnectionPDOSqlite|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
    private function initConnection(): void
267
    {
268
        $this->pdo = $this->driver->createConnection();
269
        $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

269
        $this->pdo->/** @scrutinizer ignore-call */ 
270
                    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...
270
271
        if ($this->getEmulatePrepare() !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
272
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->getEmulatePrepare());
273
        }
274
    }
275
}
276