Completed
Push — master ( 0ef884...67a9c4 )
by Christopher
02:54
created

MySQLConnection::connect()   C

Complexity

Conditions 7
Paths 14

Size

Total Lines 35
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 35
ccs 0
cts 29
cp 0
rs 6.7273
cc 7
eloc 20
nc 14
nop 1
crap 56
1
<?php
2
3
namespace AsyncPHP\Icicle\Database\Connection;
4
5
use AsyncPHP\Icicle\Database\Connection;
6
use Icicle\Loop;
7
use Icicle\Promise\Deferred;
8
use Icicle\Promise\PromiseInterface;
9
use InvalidArgumentException;
10
use MySQLi;
11
12
final class MySQLConnection implements Connection
13
{
14
    /**
15
     * @var null|MySQLi
16
     */
17
    private $connection = null;
18
19
    /**
20
     * @var bool
21
     */
22
    private $ready = true;
23
24
    /**
25
     * @var float
26
     */
27
    private $poll = 0.000001;
28
29
    /**
30
     * @inheritdoc
31
     *
32
     * @param array $config
33
     *
34
     * @return bool
35
     *
36
     * @throws InvalidArgumentException
37
     */
38
    public function connect(array $config)
39
    {
40
        if (!isset($config["host"])) {
41
            $options["host"] = "127.0.0.1";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
42
        }
43
44
        if (!isset($config["username"])) {
45
            throw new InvalidArgumentException("Undefined connection username");
46
        }
47
48
        if (!isset($config["password"])) {
49
            throw new InvalidArgumentException("Undefined connection password");
50
        }
51
52
        if (!isset($config["database"])) {
53
            throw new InvalidArgumentException("Undefined connection database");
54
        }
55
56
        if (!isset($config["port"])) {
57
            $options["port"] = 3306;
0 ignored issues
show
Bug introduced by
The variable $options does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
58
        }
59
60
        if (!isset($config["socket"])) {
61
            $options["socket"] = null;
62
        }
63
64
        $this->connection = mysqli_connect(
65
            $config["host"],
66
            $config["username"],
67
            $config["password"],
68
            $config["database"],
69
            $config["port"],
70
            $config["socket"]
71
        );
72
    }
73
74
    /**
75
     * @inheritdoc
76
     *
77
     * @param string $query
78
     *
79
     * @return PromiseInterface
80
     */
81
    public function query($query)
82
    {
83
        $deferred = new Deferred();
84
85
        $links = $errors = $rejects = [
86
            $this->connection,
87
        ];
88
89
        $outer = Loop\periodic($this->poll, function () use (&$outer, $links, $errors, $rejects, $query, $deferred) {
0 ignored issues
show
Unused Code introduced by
$outer is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
90
            if ($this->ready) {
91
                $this->ready = false;
92
                $outer->stop();
93
94
                $result = $this->connection->query($query, MYSQLI_ASYNC);
95
96 View Code Duplication
                if ($result === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
97
                    $this->ready = true;
98
                    return $deferred->reject($this->connection->error);
99
                }
100
101
                $inner = Loop\periodic($this->poll, function () use (&$inner, $links, $errors, $rejects, $deferred) {
0 ignored issues
show
Unused Code introduced by
$inner is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
102
                    if (mysqli_poll($links, $errors, $rejects, $this->poll)) {
103
                        $inner->stop();
104
105
                        $result = $this->connection->reap_async_query();
106
107 View Code Duplication
                        if ($result === false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
108
                            $this->ready = true;
109
                            return $deferred->reject($this->connection->error);
110
                        }
111
112
                        if ($result === true) {
113
                            $this->ready = true;
114
                            return $deferred->resolve();
115
                        }
116
117
                        $rows = $result->fetch_all();
118
                        $result->free();
119
120
                        $this->ready = true;
121
                        return $deferred->resolve($rows);
122
                    }
123
                });
124
            }
125
        });
126
127
        return $deferred->getPromise();
128
    }
129
}
130