|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace DingRobot\Message; |
|
4
|
|
|
|
|
5
|
|
|
use DingRobot\Contract\RequesterContract; |
|
6
|
|
|
use DingRobot\Message\Traits\At; |
|
7
|
|
|
use DingRobot\Requester\CurlRequester; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Base Class |
|
11
|
|
|
* |
|
12
|
|
|
* @package DingRobot\Message |
|
13
|
|
|
*/ |
|
14
|
|
|
abstract class Base implements \JsonSerializable |
|
15
|
|
|
{ |
|
16
|
|
|
use At; |
|
17
|
|
|
/** |
|
18
|
|
|
* @var string |
|
19
|
|
|
*/ |
|
20
|
|
|
protected $bodyName; |
|
21
|
|
|
protected $at; |
|
22
|
|
|
protected $body; |
|
23
|
|
|
|
|
24
|
10 |
|
public function __construct() |
|
25
|
|
|
{ |
|
26
|
10 |
|
} |
|
27
|
|
|
|
|
28
|
6 |
|
public function jsonSerialize() |
|
29
|
|
|
{ |
|
30
|
|
|
return [ |
|
31
|
6 |
|
'msgtype' => $this->bodyName, |
|
32
|
6 |
|
$this->bodyName => $this->getBody(), |
|
33
|
6 |
|
] + $this->getAt() ?: []; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
abstract protected function getBody(); |
|
37
|
|
|
|
|
38
|
|
|
abstract protected function bodyFields(); |
|
39
|
|
|
|
|
40
|
|
|
abstract protected function validate(); |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* 发送 |
|
44
|
|
|
* send |
|
45
|
|
|
* |
|
46
|
|
|
* @param string $address 接口地址 |
|
47
|
|
|
* @param RequesterContract $requester |
|
48
|
|
|
* |
|
49
|
|
|
* @return mixed |
|
50
|
|
|
*/ |
|
51
|
8 |
|
public function send($address = '', RequesterContract $requester = null) |
|
52
|
|
|
{ |
|
53
|
8 |
|
$this->validate(); |
|
54
|
6 |
|
if ($requester) { |
|
55
|
6 |
|
return $requester->request($address, json_encode($this->jsonSerialize())); |
|
56
|
|
|
} else { |
|
57
|
|
|
return (new CurlRequester())->request($address, json_encode($this->jsonSerialize())); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
7 |
|
protected function check($name, $required = true, $type = 'string') |
|
62
|
|
|
{ |
|
63
|
7 |
|
$content = isset($this->body[$name]) ? $this->body[$name] : null; |
|
64
|
|
|
|
|
65
|
7 |
|
if ($required && !$content) { |
|
66
|
1 |
|
throw new \InvalidArgumentException("{$name} is required"); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
7 |
|
if ($type == 'string' && $content && !is_string($content)) { |
|
70
|
1 |
|
throw new \InvalidArgumentException("{$name} must be {$type}"); |
|
71
|
|
|
} |
|
72
|
7 |
|
} |
|
73
|
|
|
|
|
74
|
|
|
|
|
75
|
8 |
|
public function __call($name, $args) |
|
76
|
|
|
{ |
|
77
|
8 |
|
if (in_array($name, $this->bodyFields())) { |
|
78
|
7 |
|
$this->body[$name] = isset($args[0]) ? $args[0] : ''; |
|
79
|
|
|
} else { |
|
80
|
1 |
|
throw new \BadMethodCallException("field {$name} not found"); |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
7 |
|
return $this; |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
1 |
|
public static function __callStatic($name, $args) |
|
87
|
|
|
{ |
|
88
|
1 |
|
return (new static)->$name(...$args); |
|
89
|
|
|
} |
|
90
|
|
|
} |