Completed
Push — master ( 44576f...38f82a )
by Sebastian
02:14
created

ExtendedPDO::queryWithParam()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 2
crap 2
1
<?php
2
3
/**
4
 * Linna Framework.
5
 *
6
 * @author Sebastian Rapetti <[email protected]>
7
 * @copyright (c) 2017, 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
     * Executes an SQL statement with parameters,
25
     * returning a result set as a PDOStatement object
26
     *
27
     * @param string $query SQL statement
28
     * @param array $param Parameter as array as PDOStatement::bindParam
29
     *
30
     * @return PDOStatement
31
     */
32 6
    public function queryWithParam(string $query, array $param) : PDOStatement
33
    {
34 6
        $statment = $this->prepare($query);
35
36 6
        foreach ($param as $value) {
37
38 5
            $this->checkValue($value);
39
40
            //reassign as reference
41
            //because bindParam need it as reference
42 3
            $ref = $value;
43 3
            $ref[1] = &$value[1];
44
45 3
            call_user_func_array([$statment, "bindParam"], $ref);
46
        }
47
48 4
        $statment->execute();
49
50 3
        return $statment;
51
    }
52
53
    /**
54
     * Check values passed to queryWithParam.
55
     *
56
     * @param array $value
57
     * @throws InvalidArgumentException
58
     */
59 5
    private function checkValue(array &$value)
60
    {
61 5
        if (count($value) < 2) {
62 1
            throw new InvalidArgumentException(__METHOD__.': Parameters array must contain at least two elements with this form: [\':name\', \'value\']');
63
        }
64
65 4
        if (strpos($value[0], ':') !== 0) {
66 1
            throw new InvalidArgumentException(__METHOD__.': Parameter name will be in the form :name');
67
        }
68 3
    }
69
}
70