|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Vicens\Alidayu\Request; |
|
4
|
|
|
|
|
5
|
|
|
use Vicens\Alidayu\Alidayu; |
|
6
|
|
|
use Vicens\Alidayu\Response; |
|
7
|
|
|
|
|
8
|
|
|
abstract class AbstractRequest |
|
9
|
|
|
{ |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* 接口所需的请求参数 |
|
13
|
|
|
* @var array |
|
14
|
|
|
*/ |
|
15
|
|
|
protected $params = []; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* 返回Api名 |
|
19
|
|
|
* @return mixed |
|
20
|
|
|
*/ |
|
21
|
|
|
abstract public function getMethod(); |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* 返回请求参数 |
|
25
|
|
|
* @return array |
|
26
|
|
|
*/ |
|
27
|
|
|
public function getParams() |
|
28
|
|
|
{ |
|
29
|
|
|
return $this->params; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* 设置请求参数 |
|
34
|
|
|
* @param array $params |
|
35
|
|
|
* @return $this |
|
36
|
|
|
*/ |
|
37
|
|
|
public function setParams(array $params = []) |
|
38
|
|
|
{ |
|
39
|
|
|
$this->params = array_merge($this->params, $params); |
|
40
|
|
|
|
|
41
|
|
|
return $this; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* 发送请求 |
|
46
|
|
|
* @return Response |
|
47
|
|
|
*/ |
|
48
|
|
|
public function send() |
|
49
|
|
|
{ |
|
50
|
|
|
return Alidayu::send($this); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* 辅助函数: 获取或设置参数 |
|
55
|
|
|
* @param $key |
|
56
|
|
|
* @param mixed|null $value |
|
57
|
|
|
* @return $this|mixed |
|
58
|
|
|
*/ |
|
59
|
|
|
protected function getOrSetParam($key, $value = null) |
|
60
|
|
|
{ |
|
61
|
|
|
if (is_null($value)) { |
|
62
|
|
|
return $this->params[$key]; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
$this->params[$key] = $value; |
|
66
|
|
|
|
|
67
|
|
|
return $this; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* 解析数据 |
|
72
|
|
|
* @param array $response |
|
73
|
|
|
* @return mixed |
|
74
|
|
|
*/ |
|
75
|
|
|
public function parseData(array $response) |
|
76
|
|
|
{ |
|
77
|
|
|
$key = str_replace('.', '_', $this->getMethod()) . '_response'; |
|
78
|
|
|
return array_key_exists($key, $response) ? $response[$key] : null; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
/** |
|
82
|
|
|
* 自动设置参数 |
|
83
|
|
|
* @param $name |
|
84
|
|
|
* @param $arguments |
|
85
|
|
|
* @return $this|string|mixed|null |
|
86
|
|
|
*/ |
|
87
|
|
|
public function __call($name, $arguments) |
|
88
|
|
|
{ |
|
89
|
|
|
|
|
90
|
|
|
// 将驼峰字符串转换成下划线 |
|
91
|
|
|
$key = preg_replace('/\s+/u', '', ucwords($name)); |
|
92
|
|
|
$key = preg_replace('/(.)(?=[A-Z])/u', '$1' . '_', $key); |
|
93
|
|
|
$key = mb_strtolower($key, 'UTF-8'); |
|
94
|
|
|
|
|
95
|
|
|
if (count($arguments) === 0) { |
|
96
|
|
|
return isset($this->params[$key]) ? $this->params[$key] : null; |
|
97
|
|
|
} |
|
98
|
|
|
|
|
99
|
|
|
$this->params[$key] = $arguments[0]; |
|
100
|
|
|
|
|
101
|
|
|
return $this; |
|
102
|
|
|
} |
|
103
|
|
|
} |
|
104
|
|
|
|