ExtendedPDO   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 7
Bugs 3 Features 3
Metric Value
wmc 6
eloc 15
c 7
b 3
f 3
dl 0
loc 63
ccs 16
cts 16
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A checkValue() 0 8 3
A queryWithParam() 0 18 2
A getLastOperationStatus() 0 3 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