Passed
Pull Request — dev (#46)
by Def
08:14
created

ConnectionPDOOracle::isActive()   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 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Oracle\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\Connection\Connection;
13
use Yiisoft\Db\Connection\ConnectionPDOInterface;
14
use Yiisoft\Db\Driver\PDODriver;
15
use Yiisoft\Db\Exception\Exception;
16
use Yiisoft\Db\Exception\InvalidConfigException;
17
use Yiisoft\Db\Query\Query;
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
use function constant;
25
26
/**
27
 * The class Connection represents a connection to a database via [PDO](https://secure.php.net/manual/en/book.pdo.php).
28
 */
29
final class ConnectionPDOOracle extends Connection implements ConnectionPDOInterface
30
{
31
    private ?PDO $pdo = null;
32
    private ?Query $query = null;
33
    private ?QueryBuilderInterface $queryBuilder = null;
34
    private ?QuoterInterface $quoter = null;
35
    private ?SchemaInterface $schema = null;
36
    private string $serverVersion = '';
37
38 379
    public function __construct(
39
        private PDODriver $driver,
40
        private QueryCache $queryCache,
41
        private SchemaCache $schemaCache
42
    ) {
43 379
        parent::__construct($queryCache);
44
    }
45
46
    /**
47
     * Reset the connection after cloning.
48
     */
49 1
    public function __clone()
50
    {
51 1
        $this->master = null;
52 1
        $this->slave = null;
53 1
        $this->transaction = null;
54
55 1
        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 1
            $this->pdo = null;
58
        }
59
    }
60
61
    /**
62
     * Close the connection before serializing.
63
     *
64
     * @return array
65
     */
66 1
    public function __sleep(): array
67
    {
68 1
        $fields = (array) $this;
69
70
        unset(
71 1
            $fields["\000" . __CLASS__ . "\000" . 'pdo'],
72 1
            $fields["\000" . __CLASS__ . "\000" . 'master'],
73 1
            $fields["\000" . __CLASS__ . "\000" . 'slave'],
74 1
            $fields["\000" . __CLASS__ . "\000" . 'transaction'],
75 1
            $fields["\000" . __CLASS__ . "\000" . 'schema']
76
        );
77
78 1
        return array_keys($fields);
79
    }
80
81 329
    public function createCommand(?string $sql = null, array $params = []): CommandPDOOracle
82
    {
83 329
        $command = new CommandPDOOracle($this, $this->queryCache);
84
85 329
        if ($sql !== null) {
86 167
            $command->setSql($sql);
87
        }
88
89 329
        if ($this->logger !== null) {
90 329
            $command->setLogger($this->logger);
91
        }
92
93 329
        if ($this->profiler !== null) {
94 329
            $command->setProfiler($this->profiler);
95
        }
96
97 329
        return $command->bindValues($params);
98
    }
99
100 8
    public function createTransaction(): TransactionInterface
101
    {
102 8
        return new TransactionPDOOracle($this);
103
    }
104
105 379
    public function close(): void
106
    {
107 379
        if (!empty($this->master)) {
108
            /** @var ConnectionPDOOracle */
109 2
            $db = $this->master;
110
111 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

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