Passed
Push — master ( 6df7c9...74bc2a )
by y
02:15
created

Statement::execute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 10
rs 10
cc 3
nc 3
nop 1
1
<?php
2
3
namespace Helix\DB;
4
5
use ArgumentCountError;
6
use Helix\DB;
7
use PDOStatement;
8
9
/**
10
 * Extends `PDOStatement` for fluency and logging.
11
 */
12
class Statement extends PDOStatement {
13
14
    /**
15
     * @var DB
16
     */
17
    protected $db;
18
19
    /**
20
     * PDO requires this to be protected.
21
     *
22
     * @param DB $db
23
     */
24
    protected function __construct (DB $db) {
25
        $this->db = $db;
26
    }
27
28
    /**
29
     * Fluent execution.
30
     *
31
     * @param array $args
32
     * @return $this
33
     */
34
    public function __invoke (array $args = null) {
35
        $this->execute($args);
36
        return $this;
37
    }
38
39
    /**
40
     * The query string.
41
     *
42
     * @return string
43
     */
44
    public function __toString () {
45
        return $this->queryString;
46
    }
47
48
    /**
49
     * Logs.
50
     * PHP returns `false` instead of throwing if too many arguments were given.
51
     * This checks for that and throws.
52
     *
53
     * @param array $args
54
     * @return bool
55
     * @throws ArgumentCountError
56
     */
57
    public function execute ($args = null) {
58
        $this->db->getLogger()->__invoke($this->queryString);
59
        if ($result = !parent::execute($args)) {
60
            $info = $this->errorInfo();
61
            if ($info[0] == 0) {
62
                $argc = count($args);
63
                throw new ArgumentCountError("Too many arguments given ({$argc})");
64
            }
65
        }
66
        return $result;
67
    }
68
69
    /**
70
     * `lastInsertId()`
71
     *
72
     * @return int
73
     */
74
    public function getId (): int {
75
        return (int)$this->db->lastInsertId();
76
    }
77
}
78