Completed
Push — http-client-refactoring ( f253a2 )
by Vasily
04:08
created

Pool::head()   C

Complexity

Conditions 11
Paths 28

Size

Total Lines 25
Code Lines 17

Duplication

Lines 25
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 17
c 1
b 0
f 0
nc 28
nop 2
dl 25
loc 25
rs 5.2653

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace PHPDaemon\Clients\HTTP;
3
4
use PHPDaemon\Network\Client;
5
6
/**
7
 * @package    NetworkClients
8
 * @subpackage HTTPClient
9
 * @author     Vasily Zorin <[email protected]>
10
 */
11
class Pool extends Client
12
{
13
    /**
14
     * Setting default config options
15
     * Overriden from NetworkClient::getConfigDefaults
16
     * @return array|bool
17
     */
18
    protected function getConfigDefaults()
19
    {
20
        return [
21
            /* [integer] Default port */
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
22
            'port' => 80,
23
24
            /* [integer] Default SSL port */
25
            'sslport' => 443,
26
27
            /* [boolean] Send User-Agent header? */
28
            'expose' => 1,
29
        ];
30
    }
31
32
    /**
33
     * Perform a HEAD request
34
     * @param string $url
35
     * @param array $params
36
     * @param callable $resultcb
0 ignored issues
show
Bug introduced by
There is no parameter named $resultcb. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
37
     * @call  ( url $url, array $params )
38
     * @call  ( url $url, callable $resultcb )
39
     * @callback $resultcb ( Connection $conn, boolean $success )
40
     */
41 View Code Duplication
    public function head($url, $params)
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...
42
    {
43
        if (is_callable($params)) {
44
            $params = ['resultcb' => $params];
45
        }
46
        if (!isset($params['uri']) || !isset($params['host'])) {
47
            list($params['scheme'], $params['host'], $params['uri'], $params['port']) = static::parseUrl($url);
48
        }
49
        if (isset($params['connect'])) {
50
            $dest = $params['connect'];
51
        } elseif (isset($params['proxy']) && $params['proxy']) {
52
            if ($params['proxy']['type'] === 'http') {
53
                $dest = 'tcp://' . $params['proxy']['addr'];
54
            }
55
        } else {
56
            $dest = 'tcp://' . $params['host'] . (isset($params['port']) ? ':' . $params['port'] : null) . ($params['scheme'] === 'https' ? '#ssl' : '');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 153 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
57
        }
58
        $this->getConnection($dest, function ($conn) use ($url, $params) {
0 ignored issues
show
Bug introduced by
The variable $dest 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...
59
            if (!$conn->isConnected()) {
60
                $params['resultcb'](false);
61
                return;
62
            }
63
            $conn->head($url, $params);
64
        });
65
    }
66
67
68
    /**
69
     * Perform a GET request
70
     * @param string $url
71
     * @param array $params
72
     * @param callable $resultcb
0 ignored issues
show
Bug introduced by
There is no parameter named $resultcb. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
73
     * @call  ( url $url, array $params )
74
     * @call  ( url $url, callable $resultcb )
75
     * @callback $resultcb ( Connection $conn, boolean $success )
76
     */
77 View Code Duplication
    public function get($url, $params)
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...
78
    {
79
        if (is_callable($params)) {
80
            $params = ['resultcb' => $params];
81
        }
82
        if (!isset($params['uri']) || !isset($params['host'])) {
83
            list($params['scheme'], $params['host'], $params['uri'], $params['port']) = static::parseUrl($url);
84
        }
85
        if (isset($params['connect'])) {
86
            $dest = $params['connect'];
87
        } elseif (isset($params['proxy']) && $params['proxy']) {
88
            if ($params['proxy']['type'] === 'http') {
89
                $dest = 'tcp://' . $params['proxy']['addr'];
90
            }
91
        } else {
92
            $dest = 'tcp://' . $params['host'] . (isset($params['port']) ? ':' . $params['port'] : null) . ($params['scheme'] === 'https' ? '#ssl' : '');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 153 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
93
        }
94
        $this->getConnection($dest, function ($conn) use ($url, $params) {
0 ignored issues
show
Bug introduced by
The variable $dest 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...
95
            if (!$conn->isConnected()) {
96
                $params['resultcb'](false);
97
                return;
98
            }
99
            $conn->get($url, $params);
100
        });
101
    }
102
103
    /**
104
     * Perform a POST request
105
     * @param string $url
106
     * @param array $data
107
     * @param array $params
108
     * @param callable $resultcb
0 ignored issues
show
Bug introduced by
There is no parameter named $resultcb. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
109
     * @call  ( url $url, array $data, array $params )
110
     * @call  ( url $url, array $data, callable $resultcb )
111
     * @callback $resultcb ( Connection $conn, boolean $success )
112
     */
113
    public function post($url, $data, $params)
114
    {
115
        if (!$data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
116
            $data = [];
117
        }
118
119
        if (is_callable($params)) {
120
            $params = ['resultcb' => $params];
121
        }
122
        if (!isset($params['uri']) || !isset($params['host'])) {
123
            list($params['scheme'], $params['host'], $params['uri'], $params['port']) = static::parseUrl($url);
124
        }
125
        if (isset($params['connect'])) {
126
            $dest = $params['connect'];
127
        } elseif (isset($params['proxy']) && $params['proxy']) {
128
            if ($params['proxy']['type'] === 'http') {
129
                $dest = 'tcp://' . $params['proxy']['addr'];
130
            }
131
        } else {
132
            $dest = 'tcp://' . $params['host'] . (isset($params['port']) ? ':' . $params['port'] : null) . ($params['scheme'] === 'https' ? '#ssl' : '');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 153 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
133
        }
134
        $this->getConnection($dest, function ($conn) use ($url, $data, $params) {
0 ignored issues
show
Bug introduced by
The variable $dest 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...
135
            if (!$conn->isConnected()) {
136
                $params['resultcb'](false);
137
                return;
138
            }
139
            $conn->post($url, $data, $params);
140
        });
141
    }
142
143
    /**
144
     * Builds URL from array
145
     * @param string $mixed
146
     * @call  ( string $str )
147
     * @call  ( array $mixed )
148
     * @return string|false
149
     */
150
    public static function buildUrl($mixed)
151
    {
152
        if (is_string($mixed)) {
153
            return $mixed;
154
        }
155
        if (!is_array($mixed)) {
156
            return false;
157
        }
158
        $url = '';
159
        $buf = [];
160
        $queryDelimiter = '?';
161
        $mixed[] = '';
162
        foreach ($mixed as $k => $v) {
163
            if (is_int($k) || ctype_digit($k)) {
164
                if (sizeof($buf) > 0) {
165
                    if (mb_orig_strpos($url, '?') !== false) {
166
                        $queryDelimiter = '&';
167
                    }
168
                    $url .= $queryDelimiter . http_build_query($buf);
169
                    $queryDelimiter = '';
170
                }
171
                $url .= $v;
172
            } else {
173
                $buf[$k] = $v;
174
            }
175
        }
176
        return $url;
177
    }
178
179
    /**
180
     * Parse URL
181
     * @param string $mixed Look Pool::buildUrl()
182
     * @call  ( string $str )
183
     * @call  ( array $mixed )
184
     * @return array|bool
185
     */
186
    public static function parseUrl($mixed)
187
    {
188
        $url = static::buildUrl($mixed);
189
        if (false === $url) {
190
            return false;
191
        }
192
        $u = parse_url($url);
193
        $uri = '';
194
        if (isset($u['path'])) {
195
            $uri .= $u['path'];
196
            if (isset($u['query'])) {
197
                $uri .= '?' . $u['query'];
198
            }
199
        }
200
        return [$u['scheme'], $u['host'], $uri, isset($u['port']) ? $u['port'] : null];
201
    }
202
}
203