Completed
Push — 9.0-dev ( 007112...d6cf5f )
by Radu
01:33
created

MysqliDatabase::executeTransaction()   B

Complexity

Conditions 5
Paths 13

Size

Total Lines 18
Code Lines 13

Duplication

Lines 18
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 18
loc 18
rs 8.8571
cc 5
eloc 13
nc 13
nop 1
1
<?php
2
namespace WebServCo\Framework\Libraries;
3
4
final class MysqliDatabase extends \WebServCo\Framework\AbstractDatabase implements
5
    \WebServCo\Framework\Interfaces\DatabaseInterface
6
{
7
    use \WebServCo\Framework\Traits\DatabaseTrait;
8
    use \WebServCo\Framework\Traits\MysqlDatabaseTrait;
9
    
10
    protected $mysqliResult;
11
    
12
    public function __construct($config)
13
    {
14
        parent::__construct($config);
15
        
16
        $driver = new \mysqli_driver();
17
        $driver->report_mode = MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT;
18
        
19
        try {
20
            $this->db = new \mysqli(
21
                $this->setting('connection/host', '127.0.0.1'),
0 ignored issues
show
Documentation introduced by
'127.0.0.1' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
22
                $this->setting('connection/username', 'root'),
0 ignored issues
show
Documentation introduced by
'root' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
23
                $this->setting('connection/passwd', ''),
0 ignored issues
show
Documentation introduced by
'' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
24
                $this->setting('connection/dbname', 'test'),
0 ignored issues
show
Documentation introduced by
'test' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
25
                $this->setting('connection/port', 3306)
0 ignored issues
show
Documentation introduced by
3306 is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
26
            );
27
            $this->db->set_charset('utf8mb4');
28
        } catch (\Exception $e) {
29
            throw new \ErrorException($e->getMessage());
30
        }
31
    }
32
    
33
    public function escape($string)
34
    {
35
        return $this->db->real_escape_string($string);
0 ignored issues
show
Bug introduced by
The method real_escape_string does only exist in mysqli, but not in PDO.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
36
    }
37
    
38
    public function executeQuery($query, $params = [])
39
    {
40
        if (empty($query)) {
41
            throw new \ErrorException('No query specified');
42
        }
43
        /**
44
         * For simplicity use statements even for simple queries.
45
         */
46
        $this->stmt = $this->db->prepare($query);
47
        $this->bindParams($params);
48
        $this->stmt->execute();
49
        $this->setLastInsertId();
50
        return true;
51
    }
52
    
53 View Code Duplication
    public function executeTransaction($data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
54
    {
55
        try {
56
            $this->db->autocommit(false);
0 ignored issues
show
Bug introduced by
The method autocommit does only exist in mysqli, but not in PDO.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
57
            foreach ($data as $item) {
58
                if (!isset($item[0])) {
59
                    throw new \ErrorException('No query specified');
60
                }
61
                $params = isset($item[1]) ? $item[1] : [];
62
                $this->executeQuery($item[0], $params);
63
            }
64
            $this->db->commit();
65
            return true;
66
        } catch (\Exception $e) {
67
            $this->db->rollback();
68
            throw new \ErrorException($e->getMessage());
69
        }
70
    }
71
    
72
    public function numRows()
73
    {
74
        /**
75
         * @TODO Fix.
76
         * "$this->stmt->num_rows" will be 0 because we can't use
77
         * "$this->stmt->store_result();"
78
         * We could count "$this->mysqliResult" but that would mean
79
         * the method will only work if getRow*() was called before.
80
         */
81
        throw new \ErrorException('Method not implemented.');
82
    }
83
    
84
    public function affectedRows()
85
    {
86
        if (!is_object($this->stmt)) {
87
            throw new \ErrorException('No Statement object available.');
88
        }
89
        return $this->stmt->affected_rows;
90
    }
91
    
92
    public function getRows($query, $params = [])
93
    {
94
        $this->executeQuery($query, $params);
95
        $this->mysqliResult = $this->stmt->get_result();
96
        $this->rows = $this->mysqliResult->fetch_all(MYSQLI_ASSOC);
97
        return $this->rows;
98
    }
99
    
100
    public function getRow($query, $params = [])
101
    {
102
        $this->executeQuery($query, $params);
103
        $this->mysqliResult = $this->stmt->get_result();
104
        return $this->mysqliResult->fetch_assoc();
105
    }
106
    
107
    public function getColumn($query, $params = [], $columnNumber = 0)
108
    {
109
        $this->executeQuery($query, $params);
110
        $this->mysqliResult = $this->stmt->get_result();
111
        $row = $this->mysqliResult->fetch_array(MYSQLI_NUM);
112
        return array_key_exists($columnNumber, $row) ? $row[$columnNumber] : false;
113
    }
114
    
115
    protected function bindParams($params = [])
116
    {
117
        if (empty($params)) {
118
            return false;
119
        }
120
        
121
        $types = [];
122
        $values = [];
123
        foreach ($params as $item) {
124
            if (is_array($item)) {
125
                foreach ($item as $value) {
126
                    $types[] = $this->getDataType($value);
127
                    $values[] = $value;
128
                }
129
            } else {
130
                $types[] = $this->getDataType($item);
131
                $values[] = $item;
132
            }
133
        }
134
        
135
        $typeString = implode(null, $types);
136
        $args = [
137
            0 => &$typeString,
138
        ];
139
        foreach ($values as &$v) {
140
            $args[] = &$v;
141
        }
142
        
143
        return call_user_func_array([$this->stmt, 'bind_param'], $args);
144
    }
145
    
146
    protected function getDataType($variable)
147
    {
148
        $type = gettype($variable);
149
        
150
        switch ($type) {
151
            case 'integer':
152
                return 'i';
153
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
154
            case 'double':
155
                return 'd';
156
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
157
            case 'string':
158
            case 'boolean':
159
            case 'NULL':
160
            case 'array':
161
            case 'object':
162
            case 'resource':
163
            case 'resource (closed)':
164
            case 'unknown type':
165
                return 's';
166
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
167
        }
168
    }
169
    
170
    protected function setLastInsertId()
171
    {
172
        $this->lastInsertId = $this->db->insert_id;
173
    }
174
}
175