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::info([
|
56
|
|
|
'message' => sprintf('Sending HTTP request [%s] %s', $e->request->getMethod(), $e->request->getUrl()),
|
57
|
|
|
'data' => $e->request->getData(),
|
58
|
|
|
'user_id' => Yii::$app->user->id ?? null
|
59
|
|
|
], 'httpclient');
|
60
|
|
|
});
|
61
|
|
|
|
62
|
|
|
$this->client->on(Client::EVENT_AFTER_SEND, function (RequestEvent $e) {
|
63
|
|
|
Yii::info([
|
64
|
|
|
'message' => sprintf('Recieved HTTP response HTTP [%s] | [%s] %s', $e->response->getStatusCode(), $e->request->getMethod(), $e->request->getUrl()),
|
65
|
|
|
'data' => $e->response->getContent(),
|
66
|
|
|
'user_id' => Yii::$app->user->id ?? null
|
67
|
|
|
], 'httpclient');
|
68
|
|
|
});
|
69
|
|
|
}
|
70
|
|
|
} |
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: