1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace yrc\components; |
4
|
|
|
|
5
|
|
|
use yii\base\BaseObject; |
6
|
|
|
use yii\httpclient\Client; |
7
|
|
|
use yii\httpclient\Request; |
8
|
|
|
use yii\httpclient\RequestEvent; |
9
|
|
|
use Yii; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class HttpClientComponent |
13
|
|
|
* Abstracts HTTP requests with request & response logging |
14
|
|
|
* @package app\components |
15
|
|
|
*/ |
16
|
|
|
final class HttpClientComponent extends BaseObject |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Options to pass to yii\httpclient\Client; |
20
|
|
|
* @var string $clientOptions |
21
|
|
|
*/ |
22
|
|
|
public $clientOptions; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* HttpOptions |
26
|
|
|
* @var array $options |
27
|
|
|
*/ |
28
|
|
|
public $options; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* The HTTP client |
32
|
|
|
* @var Client $client |
33
|
|
|
*/ |
34
|
|
|
private $client; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Returns the client instance |
38
|
|
|
* @return Client |
39
|
|
|
*/ |
40
|
|
|
public function getClient() |
41
|
|
|
{ |
42
|
|
|
return $this->client; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Initializes the HttpClient with a transport and a given set of options, and pre-loads events |
47
|
|
|
* @return void |
48
|
|
|
*/ |
49
|
|
|
public function init() |
50
|
|
|
{ |
51
|
|
|
parent::init(); |
52
|
|
|
$this->client = new Client($this->clientOptions); |
|
|
|
|
53
|
|
|
|
54
|
|
|
$this->client->on(Client::EVENT_BEFORE_SEND, function (RequestEvent $e) { |
55
|
|
|
Yii::debug([ |
56
|
|
|
'message' => sprintf('Sending HTTP request [%s] %s', $e->request->getMethod(), $e->request->getFullUrl()), |
57
|
|
|
'data' => $e->request->getData(), |
58
|
|
|
'user_id' => Yii::$app->user->id ?? null |
59
|
|
|
], 'yrc\components\HttpClientComponent:beforeSendEvent'); |
60
|
|
|
}); |
61
|
|
|
|
62
|
|
|
$this->client->on(Client::EVENT_AFTER_SEND, function (RequestEvent $e) { |
63
|
|
|
Yii::debug([ |
64
|
|
|
'message' => sprintf('Recieved HTTP response HTTP [%s] | [%s] %s', $e->response->getStatusCode(), $e->request->getMethod(), $e->request->getFullUrl()), |
|
|
|
|
65
|
|
|
'data' => (function () use ($e) { |
66
|
|
|
$content = $e->response->getContent(); |
67
|
|
|
if (preg_match('~[^\x20-\x7E\t\r\n]~', $content) > 0) { |
68
|
|
|
return '[binary data]'; |
69
|
|
|
} |
70
|
|
|
return $content; |
71
|
|
|
})(), |
72
|
|
|
'user_id' => Yii::$app->user->id ?? null |
73
|
|
|
], 'yrc\components\HttpClientComponent:afterSendEvent'); |
74
|
|
|
}); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|