Statement::__toString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
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
It seems like $args can also be of type null; however, parameter $value of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

67
                $argc = count(/** @scrutinizer ignore-type */ $args);
Loading history...
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