ExtendedPDO::getLastOperationStatus()   A
last analyzed

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 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
/**
4
 * Linna Framework.
5
 *
6
 * @author Sebastian Rapetti <[email protected]>
7
 * @copyright (c) 2018, Sebastian Rapetti
8
 * @license http://opensource.org/licenses/MIT MIT License
9
 */
10
declare(strict_types=1);
11
12
namespace Linna\Storage;
13
14
use PDO;
15
use PDOStatement;
16
use InvalidArgumentException;
17
18
/**
19
 * Extended PDO
20
 */
21
class ExtendedPDO extends PDO
22
{
23
    /**
24
     * @var bool Status for last operation.
25
     */
26
    private bool $lastOperationStatus = false;
27
28
    /**
29
     * Executes an SQL statement with parameters,
30
     * returning a result set as a PDOStatement object
31
     *
32
     * @param string       $query SQL statement
33
     * @param array<mixed> $param Parameter as array as PDOStatement::bindParam
34
     *
35
     * @return PDOStatement<mixed>
36
     */
37 21
    public function queryWithParam(string $query, array $param): PDOStatement
38
    {
39 21
        $statement = $this->prepare($query);
40
41 21
        foreach ($param as $value) {
42 20
            $this->checkValue($value);
43
44
            //reassign as reference
45
            //because bindParam need it as reference
46 18
            $ref = $value;
47 18
            $ref[1] = &$value[1];
48
49 18
            \call_user_func_array([$statement, "bindParam"], $ref);
50
        }
51
52 19
        $this->lastOperationStatus = $statement->execute();
53
54 18
        return $statement;
55
    }
56
57
    /**
58
     * Return the last opration status.
59
     *
60
     * @return bool
61
     */
62 15
    public function getLastOperationStatus(): bool
63
    {
64 15
        return $this->lastOperationStatus;
65
    }
66
67
    /**
68
     * Check values passed to queryWithParam.
69
     *
70
     * @param array<mixed> $value
71
     *
72
     * @return void
73
     *
74
     * @throws InvalidArgumentException
75
     */
76 20
    private function checkValue(array &$value): void
77
    {
78 20
        if (\count($value) < 2) {
79 1
            throw new InvalidArgumentException('Parameters array must contain at least two elements with this form: [\':name\', \'value\'].');
80
        }
81
82 19
        if (\strpos($value[0], ':') !== 0) {
83 1
            throw new InvalidArgumentException('Parameter name will be in the form :name.');
84
        }
85 18
    }
86
}
87