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 | /** |
||
16 | * @var DB |
||
17 | */ |
||
18 | protected $db; |
||
19 | |||
20 | /** |
||
21 | * PDO requires this to be protected. |
||
22 | * |
||
23 | * @param DB $db |
||
24 | */ |
||
25 | protected function __construct(DB $db) |
||
26 | { |
||
27 | $this->db = $db; |
||
28 | } |
||
29 | |||
30 | /** |
||
31 | * Fluent execution. |
||
32 | * |
||
33 | * @param array $args |
||
34 | * @return $this |
||
35 | */ |
||
36 | public function __invoke(array $args = null) |
||
37 | { |
||
38 | $this->execute($args); |
||
39 | return $this; |
||
40 | } |
||
41 | |||
42 | /** |
||
43 | * The query string. |
||
44 | * |
||
45 | * @return string |
||
46 | */ |
||
47 | public function __toString() |
||
48 | { |
||
49 | return $this->queryString; |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * Logs. |
||
54 | * PHP returns `false` instead of throwing if too many arguments were given. |
||
55 | * This checks for that and throws. |
||
56 | * |
||
57 | * @param array $args |
||
58 | * @return bool |
||
59 | * @throws ArgumentCountError |
||
60 | */ |
||
61 | public function execute($args = null) |
||
62 | { |
||
63 | $this->db->log($this->queryString); |
||
64 | if ($result = !parent::execute($args)) { |
||
65 | $info = $this->errorInfo(); |
||
66 | if ($info[0] == 0) { |
||
67 | $argc = count($args); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
68 | throw new ArgumentCountError("Too many arguments given ({$argc})"); |
||
69 | } |
||
70 | } |
||
71 | return $result; |
||
72 | } |
||
73 | |||
74 | /** |
||
75 | * `lastInsertId()` |
||
76 | * |
||
77 | * @return int |
||
78 | */ |
||
79 | public function getId(): int |
||
80 | { |
||
81 | return (int)$this->db->lastInsertId(); |
||
82 | } |
||
83 | } |
||
84 |