Completed
Push — master ( ca99e9...18d42b )
by Rasmus
02:33
created

PDOConnection::lastInsertId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 0
cts 5
cp 0
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 6
1
<?php
2
3
namespace mindplay\sql\pdo;
4
5
use Exception;
6
use LogicException;
7
use mindplay\sql\framework\Connection;
8
use mindplay\sql\framework\Executable;
9
use mindplay\sql\framework\Result;
10
use mindplay\sql\framework\ReturningExecutable;
11
use PDO;
12
use UnexpectedValueException;
13
14
/**
15
 * This class implements a Connection adapter for a PDO connection.
16
 */
17
class PDOConnection implements Connection
18
{
19
    /**
20
     * @var PDO
21
     */
22
    private $pdo;
23
24
    /**
25
     * @var int number of nested calls to transact()
26
     *
27
     * @see transact()
28
     */
29
    private $transaction_level = 0;
30
31
    /**
32
     * @var bool net result of nested calls to transact()
33
     *
34
     * @see transact()
35
     */
36
    private $transaction_result;
37
38
    /**
39
     * @param PDO $pdo
40
     */
41 1
    public function __construct(PDO $pdo)
42
    {
43 1
        $this->pdo = $pdo;
44 1
    }
45
46
    /**
47
     * @inheritdoc
48
     */
49 1
    public function prepare(Executable $statement)
50
    {
51 1
        $params = $statement->getParams();
52
53 1
        $sql = $this->expandPlaceholders($statement->getSQL(), $params);
54
55 1
        $prepared_statement = new PreparedPDOStatement($this->pdo->prepare($sql));
56
        
57 1
        foreach ($params as $name => $value) {
58 1
            if (is_array($value)) {
59 1
                $index = 1; // use a base-1 offset consistent with expandPlaceholders()
60
61 1
                foreach ($value as $item) {
62
                    // NOTE: we deliberately ignore the array indices here, as using them could result in broken SQL!
63
64 1
                    $prepared_statement->bind("{$name}_{$index}", $item);
65
66 1
                    $index += 1;
67
                }
68
            } else {
69 1
                $prepared_statement->bind($name, $value);
70
            }
71
        }
72
73 1
        return $prepared_statement;
74
    }
75
76
    /**
77
     * @inheritdoc
78
     */
79 1
    public function fetch(ReturningExecutable $statement, $batch_size = 1000, array $mappers = [])
80
    {
81 1
        return new Result(
82 1
            $this->prepare($statement),
83
            $batch_size,
84 1
            array_merge($statement->getMappers(), $mappers)
85
        );
86
    }
87
88
    /**
89
     * @inheritdoc
90
     */
91
    public function execute(Executable $statement)
92
    {
93
        $prepared_statement = $this->prepare($statement);
94
95
        $prepared_statement->execute();
96
        
97
        return $prepared_statement;
98
    }
99
100
    /**
101
     * @inheritdoc
102
     */
103 1
    public function transact(callable $func)
104
    {
105 1
        if ($this->transaction_level === 0) {
106
            // starting a new stack of transactions - assume success:
107 1
            $this->pdo->beginTransaction();
108 1
            $this->transaction_result = true;
109
        }
110
111 1
        $this->transaction_level += 1;
112
113
        /** @var mixed $commit return type of $func isn't guaranteed, therefore mixed rather than bool */
114
115
        try {
116 1
            $commit = call_user_func($func);
117 1
        } catch (Exception $exception) {
118 1
            $commit = false;
119
        }
120
121 1
        $this->transaction_result = ($commit === true) && $this->transaction_result;
122
123 1
        $this->transaction_level -= 1;
124
125 1
        if ($this->transaction_level === 0) {
126 1
            if ($this->transaction_result === true) {
127 1
                $this->pdo->commit();
128
129 1
                return true; // the net transaction is a success!
130
            } else {
131 1
                $this->pdo->rollBack();
132
            }
133
        }
134
135 1
        if (isset($exception)) {
136
            // re-throw unhandled Exception as a LogicException:
137 1
            throw new LogicException("unhandled Exception during transaction", 0, $exception);
138
        }
139
140 1
        if (! is_bool($commit)) {
141 1
            throw new UnexpectedValueException("\$func must return TRUE (to commit) or FALSE (to roll back)");
142
        }
143
144 1
        return $this->transaction_result;
145
    }
146
147
    /**
148
     * Internally expand SQL placeholders (for array-types)
149
     *
150
     * @param string $sql    SQL with placeholders
151
     * @param array  $params placeholder name/value pairs
152
     *
153
     * @return string SQL with expanded placeholders
154
     */
155 1
    private function expandPlaceholders($sql, array $params)
156
    {
157 1
        $replace_pairs = [];
158
159 1
        foreach ($params as $name => $value) {
160 1
            if (is_array($value)) {
161
                // TODO: QA! For empty arrays, the resulting SQL is e.g.: "SELECT * FROM foo WHERE foo.bar IN (null)"
162
163 1
                $replace_pairs[":{$name}"] = count($value) === 0
164 1
                    ? "(null)" // empty set
165 1
                    : "(" . implode(', ', array_map(function ($i) use ($name) {
166 1
                        return ":{$name}_{$i}";
167 1
                    }, range(1, count($value)))) . ")";
168
            }
169
        }
170
171 1
        return count($replace_pairs)
172 1
            ? strtr($sql, $replace_pairs)
173 1
            : $sql; // no arrays found in the given parameters
174
    }
175
176
    /**
177
     * @param string|null $sequence_name auto-sequence name (or NULL for e.g. MySQL which supports only one auto-key)
178
     *
179
     * @return int|string
180
     */
181
    public function lastInsertId($sequence_name = null)
182
    {
183
        $id = $this->pdo->lastInsertId($sequence_name);
184
        
185
        return is_numeric($id)
186
            ? (int) $id
187
            : $id;
188
    }
189
}
190