PDOAdapter::prepare()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
namespace BenTools\SimpleDBAL\Model\Adapter\PDO;
4
5
use BenTools\SimpleDBAL\Contract\AdapterInterface;
6
use BenTools\SimpleDBAL\Contract\CredentialsInterface;
7
use BenTools\SimpleDBAL\Contract\ReconnectableAdapterInterface;
8
use BenTools\SimpleDBAL\Contract\StatementInterface;
9
use BenTools\SimpleDBAL\Contract\ResultInterface;
10
use BenTools\SimpleDBAL\Contract\TransactionAdapterInterface;
11
use BenTools\SimpleDBAL\Model\ConfigurableTrait;
12
use BenTools\SimpleDBAL\Model\Exception\AccessDeniedException;
13
use BenTools\SimpleDBAL\Model\Exception\DBALException;
14
use BenTools\SimpleDBAL\Model\Exception\MaxConnectAttempsException;
15
use BenTools\SimpleDBAL\Model\Exception\ParamBindingException;
16
use GuzzleHttp\Promise\Promise;
17
use GuzzleHttp\Promise\PromiseInterface;
18
use PDO;
19
use PDOException;
20
use Throwable;
21
22
class PDOAdapter implements AdapterInterface, TransactionAdapterInterface, ReconnectableAdapterInterface
23
{
24
    use ConfigurableTrait;
25
26
    /**
27
     * @var PDO
28
     */
29
    private $cnx;
30
31
    /**
32
     * @var CredentialsInterface
33
     */
34
    private $credentials;
35
36
    /**
37
     * @var int
38
     */
39
    private $reconnectAttempts = 0;
40
41
    /**
42
     * PDOAdapter constructor.
43
     * @param PDO $cnx
44
     * @param CredentialsInterface|null $credentials
45
     * @param array|null $options
46
     */
47
    protected function __construct(PDO $cnx, CredentialsInterface $credentials = null, array $options = null)
48
    {
49
        $this->cnx = $cnx;
50
        if (PDO::ERRMODE_EXCEPTION !== $this->cnx->getAttribute(PDO::ATTR_ERRMODE)) {
51
            $this->cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
52
        }
53
        $this->credentials = $credentials;
54
        if (null !== $options) {
55
            $this->options     = array_replace($this->getDefaultOptions(), $options);
56
        }
57
    }
58
59
    /**
60
     * @inheritDoc
61
     */
62
    public function getWrappedConnection(): PDO
63
    {
64
        return $this->cnx;
65
    }
66
67
    /**
68
     * @inheritDoc
69
     */
70
    public function getCredentials(): ?CredentialsInterface
71
    {
72
        return $this->credentials;
73
    }
74
75
    /**
76
     * @inheritDoc
77
     */
78
    public function isConnected(): bool
79
    {
80
        try {
81
            self::wrapWithErrorHandler(function () {
82
                $this->cnx->getAttribute(PDO::ATTR_SERVER_INFO);
83
            });
84
            return true;
85
        } catch (Throwable $e) {
86
            return false;
87
        }
88
    }
89
90
    /**
91
     * @inheritDoc
92
     */
93
    public function shouldReconnect(): bool
94
    {
95
        return !$this->isConnected() && $this->reconnectAttempts < (int) $this->getOption(self::OPT_MAX_RECONNECT_ATTEMPTS);
96
    }
97
98
    /**
99
     * Tries to reconnect to database.
100
     */
101
    private function reconnect()
102
    {
103
        if (0 === (int) $this->getOption(self::OPT_MAX_RECONNECT_ATTEMPTS)) {
104
            throw new MaxConnectAttempsException("Connection lost.");
105
        } elseif ($this->reconnectAttempts === (int) $this->getOption(self::OPT_MAX_RECONNECT_ATTEMPTS)) {
106
            throw new MaxConnectAttempsException("Max attempts to connect to database has been reached.");
107
        }
108
109
        if (null === $this->credentials) {
110
            throw new AccessDeniedException("Unable to reconnect: credentials not provided.");
111
        }
112
113
        try {
114
            if (0 !== $this->reconnectAttempts) {
115
                usleep((int) $this->getOption(self::OPT_USLEEP_AFTER_FIRST_ATTEMPT));
116
            }
117
            $this->cnx = self::createLink($this->getCredentials(), $this->options);
118
            if ($this->isConnected()) {
119
                $this->reconnectAttempts = 0;
120
            } else {
121
                $this->reconnect();
122
            }
123
        } catch (Throwable $e) {
124
            $this->reconnectAttempts++;
125
        }
126
    }
127
128
    /**
129
     * @inheritDoc
130
     */
131
    public function prepare(string $query, array $values = null): StatementInterface
132
    {
133
        try {
134
            $wrappedStmt = $this->cnx->prepare($query);
135
        } catch (PDOException $e) {
136
            if (!$this->isConnected()) {
137
                $this->reconnect();
138
                return $this->prepare($query, $values);
139
            }
140
            throw new DBALException($e->getMessage(), (int) $e->getCode(), $e);
141
        }
142
        return new Statement($this, $wrappedStmt, $values);
143
    }
144
145
    /**
146
     * @inheritDoc
147
     */
148
    public function execute($stmt, array $values = null): ResultInterface
149
    {
150
        if (is_string($stmt)) {
151
            $stmt = $this->prepare($stmt);
152
        }
153
        if (!$stmt instanceof Statement) {
154
            throw new \InvalidArgumentException(sprintf('Expected %s object, got %s', Statement::class, get_class($stmt)));
155
        }
156
        if (null !== $values) {
157
            $stmt = $stmt->withValues($values);
158
        }
159
        try {
160
            $this->runStmt($stmt);
161
            $result = $stmt->createResult();
162
        } catch (Throwable $e) {
163
            if (!$this->isConnected()) {
164
                $this->reconnect();
165
                return $this->execute($this->prepare((string) $stmt, $stmt->getValues()));
166
            }
167
            throw $e;
168
        }
169
        return $result;
170
    }
171
172
    /**
173
     * @inheritDoc
174
     */
175
    public function executeAsync($stmt, array $values = null): PromiseInterface
176
    {
177
        $promise = new Promise(function () use (&$promise, $stmt, $values) {
178
            try {
179
                $promise->resolve($this->execute($stmt, $values));
180
            } catch (DBALException $e) {
181
                $promise->reject($e);
182
            }
183
        });
184
        return $promise;
185
    }
186
187
    /**
188
     * @param \PDOStatement $wrappedStmt
0 ignored issues
show
Bug introduced by
There is no parameter named $wrappedStmt. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
189
     */
190
    private function runStmt(Statement $stmt)
191
    {
192
        $wrappedStmt = $stmt->getWrappedStatement();
193
        try {
194
            self::wrapWithErrorHandler(function () use ($stmt, $wrappedStmt) {
195
                $stmt->bind();
196
                $wrappedStmt->execute();
197
            });
198
        } catch (\PDOException $e) {
199
            if (false !== strpos($e->getMessage(), 'no parameters were bound')) {
200
                throw new ParamBindingException($e->getMessage(), (int) $e->getCode(), $e, $stmt);
201
            }
202
            if (false !== strpos($e->getMessage(), 'number of bound variables does not match number')) {
203
                throw new ParamBindingException($e->getMessage(), (int) $e->getCode(), $e, $stmt);
204
            }
205
            throw new DBALException($e->getMessage(), (int) $e->getCode(), $e);
206
        }
207
    }
208
209
    /**
210
     * @inheritDoc
211
     */
212
    public function beginTransaction(): void
213
    {
214
        $this->getWrappedConnection()->beginTransaction();
0 ignored issues
show
Bug introduced by
The method beginTransaction does only exist in PDO, but not in mysqli.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
215
    }
216
217
    /**
218
     * @inheritDoc
219
     */
220
    public function commit(): void
221
    {
222
        $this->getWrappedConnection()->commit();
223
    }
224
225
    /**
226
     * @inheritDoc
227
     */
228
    public function rollback(): void
229
    {
230
        $this->getWrappedConnection()->rollBack();
231
    }
232
233
    /**
234
     * @inheritDoc
235
     */
236
    public function getDefaultOptions(): array
237
    {
238
        return [
239
            self::OPT_MAX_RECONNECT_ATTEMPTS => self::DEFAULT_MAX_RECONNECT_ATTEMPTS,
240
            self::OPT_USLEEP_AFTER_FIRST_ATTEMPT => self::DEFAULT_USLEEP_AFTER_FIRST_ATTEMPT,
241
        ];
242
    }
243
244
    /**
245
     * @param CredentialsInterface $credentials
246
     * @return PDOAdapter
247
     */
248
    public static function factory(CredentialsInterface $credentials, array $options = null): self
249
    {
250
        return new static(self::createLink($credentials, $options), $credentials, $options);
251
    }
252
253
    /**
254
     * @param PDO                       $link
255
     * @param CredentialsInterface|null $credentials
256
     * @return PDOAdapter
257
     */
258
    public static function createFromLink(PDO $link, CredentialsInterface $credentials = null): self
259
    {
260
        return new static($link, $credentials);
261
    }
262
263
    /**
264
     * @param CredentialsInterface $credentials
265
     * @return PDO
266
     */
267
    private static function createLink(CredentialsInterface $credentials, array $options = null): PDO
268
    {
269
        $dsn = sprintf('%s:', $credentials->getPlatform());
270
        $dsn .= sprintf('host=%s;', $credentials->getHostname());
271
        if (null !== $credentials->getPort()) {
272
            $dsn .= sprintf('port=%s;', $credentials->getPort());
273
        }
274
        if (null !== $credentials->getDatabase()) {
275
            $dsn .= sprintf('dbname=%s;', $credentials->getDatabase());
276
        }
277
        try {
278
            $pdoOptions = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
279
            if (isset($options['charset'])) {
280
                $pdoOptions[PDO::MYSQL_ATTR_INIT_COMMAND] = sprintf('SET NAMES %s', $options['charset']);
281
            }
282
            return new PDO($dsn, $credentials->getUser(), $credentials->getPassword(), $pdoOptions);
283
        } catch (\PDOException $e) {
284
            throw new AccessDeniedException($e->getMessage(), (int) $e->getCode(), $e);
285
        }
286
    }
287
288
289
    /**
290
     * @param callable $run
291
     * @return mixed|void
292
     */
293
    private static function wrapWithErrorHandler(callable $run)
294
    {
295
        $errorHandler = function ($errno, $errstr) {
296
            throw new PDOException($errstr, $errno);
297
        };
298
        set_error_handler($errorHandler, E_WARNING);
299
        $result = $run();
300
        restore_error_handler();
301
        return $result;
302
    }
303
}
304