AbstractPdoGateway::executePrepared()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.3332

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 2
nop 3
dl 0
loc 9
ccs 4
cts 6
cp 0.6667
crap 3.3332
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\RfcLinc\DataGateway\Pdo;
6
7
use PDO;
8
use PDOStatement;
9
use PhpCfdi\RfcLinc\DataGateway\PersistenceException;
10
11
abstract class AbstractPdoGateway
12
{
13
    /** @var PDO */
14
    private $pdo;
15
16
    /** @var PDOStatement[] */
17
    private $preparedStatements;
18
19 23
    public function __construct(PDO $pdo)
20
    {
21 23
        $this->pdo = $pdo;
22 23
        $this->preparedStatements = [];
23 23
    }
24
25 20
    public function preparedStatements(string $query): PDOStatement
26
    {
27 20
        $statement = $this->preparedStatements[$query] ?? null;
28 20
        if ($statement instanceof PDOStatement) {
29 9
            return $statement;
30
        }
31
32 20
        $statement = $this->pdo->prepare($query);
33 20
        if (false === $statement) {
34
            throw new \LogicException("Cannot prepare the statement: $query");
35
        }
36 20
        $this->preparedStatements[$query] = $statement;
37
38 20
        return $statement;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $statement could return the type true which is incompatible with the type-hinted return PDOStatement. Consider adding an additional type-check to rule them out.
Loading history...
39
    }
40
41 20
    public function executePrepared(string $query, array $arguments = [], string $exceptionMessage = ''): PDOStatement
42
    {
43 20
        $statement = $this->preparedStatements($query);
44 20
        if (! $statement->execute($arguments)) {
45
            $exceptionMessage = $exceptionMessage ? : 'Error retrieving data from database';
46
            throw new PersistenceException($exceptionMessage);
47
        }
48
49 20
        return $statement;
50
    }
51
52 8
    public function queryValue(string $query, array $arguments = [], $defaultValue = null)
53
    {
54 8
        $stmt = $this->executePrepared($query, $arguments);
55 8
        $values = $stmt->fetch(PDO::FETCH_NUM);
56 8
        if (is_array($values) && array_key_exists(0, $values)) {
57 8
            return $values[0];
58
        }
59
60
        return $defaultValue;
61
    }
62
}
63