Test Setup Failed
Push — master ( e7f08b...ed817a )
by Lawrence
02:21
created

Core::send()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 24
rs 8.9713
cc 3
eloc 16
nc 4
nop 5
1
<?php
2
3
namespace ABM\Kilns\Module;
4
5
use GuzzleHttp\Psr7\Request;
6
use GuzzleHttp\Psr7\Response;
7
8
abstract class Core
9
{
10
    /**
11
     * $serverHost
12
     * 接口域名.
13
     *
14
     * @var string
15
     */
16
    protected $serverHost = '';
17
    /**
18
     * $secretKey
19
     * secretKey.
20
     *
21
     * @var string
22
     */
23
    protected $secretKey = '';
24
25
    /**
26
     * __construct.
27
     *
28
     * @param array $config [description]
29
     */
30
    public function __construct($config = [])
31
    {
32
        if (!empty($config)) {
33
            $this->setConfig($config);
34
        }
35
    }
36
37
    /**
38
     * setConfig
39
     * 设置配置.
40
     *
41
     * @param array $config 模块配置
42
     */
43
    public function setConfig($config)
44
    {
45
        if (!is_array($config) || !count($config)) {
46
            return false;
47
        }
48
        foreach ($config as $key => $val) {
49
            switch ($key) {
50
                case 'Subscription-Key':
51
                    $this->setConfigSecretKey($val);
52
                    break;
53
                case 'Content-Type':
54
                    $this->setConfigContentType($val);
55
                    break;
56
                case 'Request-Method':
57
                    $this->setConfigRequestMethod($val);
58
                    break;
59
                default:
60
                    break;
61
            }
62
        }
63
64
        return true;
65
    }
66
67
    /**
68
     * setConfigSecretKey
69
     * 设置secretKey.
70
     *
71
     * @param string $secretKey
72
     */
73
    public function setConfigSecretKey($secretKey)
74
    {
75
        $this->secretKey = $secretKey;
76
77
        return $this;
78
    }
79
80
    /**
81
     * setConfigRequestMethod
82
     * 设置请求方法.
83
     *
84
     * @param string $method
0 ignored issues
show
Bug introduced by
There is no parameter named $method. 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...
85
     */
86
    public function setConfigContentType($contentType)
87
    {
88
        $this->contentType = strtoupper($contentType);
0 ignored issues
show
Bug introduced by
The property contentType does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
89
90
        return $this;
91
    }
92
93
    /**
94
     * setConfigSecretKey
95
     * 设置secretKey.
96
     *
97
     * @param string $secretKey
0 ignored issues
show
Bug introduced by
There is no parameter named $secretKey. 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...
98
     */
99
    public function setConfigRequestMethod($requestMethod)
100
    {
101
        $this->requestMethod = $requestMethod;
0 ignored issues
show
Bug introduced by
The property requestMethod does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
102
103
        return $this;
104
    }
105
106
    /**
107
     * getLastRequest
108
     * 获取上次请求的url.
109
     *
110
     * @return
111
     */
112
    public function getLastRequest()
113
    {
114
        $response = new Response();
0 ignored issues
show
Unused Code introduced by
$response 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...
115
    }
116
117
    /**
118
     * getLastResponse
119
     * 获取请求的原始返回.
120
     *
121
     * @return
122
     */
123
    public function getLastResponse($response)
0 ignored issues
show
Unused Code introduced by
The parameter $response is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
124
    {
125
        $response = new Response();
126
127
        return $response;
128
    }
129
130
    /**
131
     * generateUrl
132
     * 生成请求的URL,不发起请求
133
     *
134
     * @param string $name   接口方法名
135
     * @param array  $params 请求参数
136
     * @param string $body   请求Body
137
     *
138
     * @return
139
     */
140
    public function generateUrl($name, $params, $body)
141
    {
142
        $action = ucfirst($name);
0 ignored issues
show
Unused Code introduced by
$action 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...
143
144
        return $this->generateUrlBody($params, $this->secretKey, $this->contentType, $this->requestMethod, $this->serverHost.$name, $body);
145
    }
146
147
    /**
148
     * generateUrlBody
149
     * 生成请求的URLBody.
150
     *
151
     * @param array  $paramArray    请求参数
152
     * @param string $secretKey     订阅密钥
153
     * @param string $ContentType   请求Body的类型
0 ignored issues
show
Documentation introduced by
There is no parameter named $ContentType. Did you maybe mean $contentType?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
154
     * @param string $requestMethod 请求方式,GET/POST
155
     * @param string $url           接口URL
156
     * @param string $body          请求Body
157
     *
158
     * @return
159
     */
160
    public static function generateUrlBody($paramArray, $secretKey, $contentType, $requestMethod, $url, $body)
161
    {
162
        $header = [];
163
        $urlBopy = [];
0 ignored issues
show
Unused Code introduced by
$urlBopy 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...
164
        if ($contentType) {
165
            $header[] = 'Content-Type:'.strtolower($contentType);
166
        }
167
168
        $header[] = 'Ocp-Apim-Subscription-Key:'.$secretKey;
169
        switch ($requestMethod) {
170
            case 'GET': 
171
                $url .= '&'.http_build_query($body);
172
                break;
173
            default:  
174
                $url .= '?'.http_build_query($paramArray);
175
                $urlBody['body'] = $body;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$urlBody was never initialized. Although not strictly required by PHP, it is generally a good practice to add $urlBody = 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...
176
                break;
177
        }
178
179
        $urlBody = array_merge(['url' => $url, 'method' => $requestMethod, 'header' => $header], $urlBody);
0 ignored issues
show
Bug introduced by
The variable $urlBody 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...
180
181
        return $urlBody;
182
    }
183
184
    /**
185
     * __call
186
     * 通过__call转发请求
187
     *
188
     * @param string $name      方法名
189
     * @param array  $arguments 参数
190
     *
191
     * @return
192
     */
193
    public function call($name, $arguments)
194
    {
195
        require_once Kilns_ROOT_PATH.'/Module/Core.php';
196
        $response = $this->dispatchRequest($name, $arguments);
197
198
        return $this->dealResponse($response);
0 ignored issues
show
Documentation introduced by
$response is of type object<GuzzleHttp\Psr7\Request>, but the function expects a array.

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...
199
    }
200
201
    /**
202
     * _dispatchRequest
203
     * 发起接口请求
204
     *
205
     * @param string $name      接口名
206
     * @param array  $arguments 接口参数
207
     *
208
     * @return
209
     */
210
    protected function dispatchRequest($name, $arguments)
211
    {
212
        $action = ucfirst($name);
213
        $params = [];
214
        if (is_array($arguments) && !empty($arguments)) {
215
            $params[0] = (array) $arguments[0];
216
        }
217
        if (is_array($arguments) && !empty($arguments)) {
218
            $params[1] = $arguments[1];
219
        }
220
221
        $response = $this->send($params, $this->_secretKey, $this->_contentType, $this->_requestMethod, $this->_serverHost.$action);
0 ignored issues
show
Bug introduced by
The property _secretKey does not seem to exist. Did you mean secretKey?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Bug introduced by
The property _serverHost does not seem to exist. Did you mean serverHost?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Bug introduced by
The property _contentType does not seem to exist. Did you mean contentType?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Bug introduced by
The property _requestMethod does not seem to exist. Did you mean requestMethod?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
222
223
        return $response;
224
    }
225
226
    /**
227
     * send
228
     * 发起请求
229
     *
230
     * @param array  $paramArray    请求参数
231
     * @param string $secretKey     订阅密钥
232
     * @param string $ContentType   请求Body的类型
0 ignored issues
show
Documentation introduced by
There is no parameter named $ContentType. Did you maybe mean $contentType?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
233
     * @param string $requestMethod 请求方式,GET/POST
234
     * @param string $url           接口URL
0 ignored issues
show
Bug introduced by
There is no parameter named $url. 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...
235
     * @param string $body          请求Body
0 ignored issues
show
Bug introduced by
There is no parameter named $body. 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...
236
     *
237
     * @return
238
     */
239
    public static function send($paramArray, $secretKey, $contentType, $requestMethod, $requestHost)
240
    {
241
        $param = $paramArray[0];
242
        $body = $paramArray[1];
243
        if ($contentType) {
244
            $header[] = 'Content-Type:'.strtolower($contentType);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$header was never initialized. Although not strictly required by PHP, it is generally a good practice to add $header = 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...
245
        }
246
247
        $header[] = 'Ocp-Apim-Subscription-Key:'.$secretKey;
0 ignored issues
show
Bug introduced by
The variable $header 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...
248
249
        $url = $requestHost;
250
251
        switch ($requestMethod) {
252
            case 'POST': 
253
                $url .= '?'.http_build_query($param);
254
                break;
255
            default: 
256
                $url .= '&'.http_build_query($body);
257
                break;
258
        }
259
        $request = new Request($requestMethod, $url, $header, $body);
260
261
        return $request;
262
    }
263
264
    /**
265
     * _dealResponse
266
     * 处理返回.
267
     *
268
     * @param array $response
269
     *
270
     * @return
271
     */
272
    protected function dealResponse($response)
273
    {
274
        $phrase = $response->getReasonPhrase();
0 ignored issues
show
Bug introduced by
The method getReasonPhrase cannot be called on $response (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
275
        if ($phrase !== 'OK') {
276
            echo $response->getStatusCode();
0 ignored issues
show
Bug introduced by
The method getStatusCode cannot be called on $response (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
277
            echo $response->getBody();
0 ignored issues
show
Bug introduced by
The method getBody cannot be called on $response (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
278
279
            return false;
280
        }
281
282
        if (count($response)) {
283
            return $response;
284
        } else {
285
            return true;
286
        }
287
    }
288
}
289