1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace AlibabaCloud\Client\Traits; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use GuzzleHttp\Exception\RequestException; |
7
|
|
|
use GuzzleHttp\Handler\MockHandler; |
8
|
|
|
use GuzzleHttp\Psr7\Request; |
9
|
|
|
use GuzzleHttp\Psr7\Response; |
10
|
|
|
use Psr\Http\Message\RequestInterface; |
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Class MockTrait |
15
|
|
|
* |
16
|
|
|
* @package AlibabaCloud\Client\Request\Traits |
17
|
|
|
* @mixin Request |
18
|
|
|
*/ |
19
|
|
|
trait MockTrait |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var array |
23
|
|
|
*/ |
24
|
|
|
private static $mockQueue = []; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var MockHandler |
28
|
|
|
*/ |
29
|
|
|
private static $mock; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param integer $status |
33
|
|
|
* @param array $headers |
34
|
|
|
* @param array|string|object $body |
35
|
|
|
*/ |
36
|
|
|
public static function mockResponse($status = 200, array $headers = [], $body = null) |
37
|
|
|
{ |
38
|
|
|
if (is_array($body) || is_object($body)) { |
39
|
|
|
$body = json_encode($body); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
self::$mockQueue[] = new Response($status, $headers, $body); |
43
|
|
|
self::createHandlerStack(); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
private static function createHandlerStack() |
47
|
|
|
{ |
48
|
|
|
self::$mock = new MockHandler(self::$mockQueue); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param string $message |
53
|
|
|
* @param RequestInterface $request |
54
|
|
|
* @param ResponseInterface|null $response |
55
|
|
|
* @param Exception|null $previous |
56
|
|
|
* @param array $handlerContext |
57
|
|
|
*/ |
58
|
|
|
public static function mockRequestException( |
59
|
|
|
$message, |
60
|
|
|
RequestInterface $request, |
61
|
|
|
ResponseInterface $response = null, |
62
|
|
|
Exception $previous = null, |
63
|
|
|
array $handlerContext = [] |
64
|
|
|
) { |
65
|
|
|
self::$mockQueue[] = new RequestException( |
66
|
|
|
$message, |
67
|
|
|
$request, |
68
|
|
|
$response, |
69
|
|
|
$previous, |
70
|
|
|
$handlerContext |
71
|
|
|
); |
72
|
|
|
|
73
|
|
|
self::createHandlerStack(); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
public static function cancelMock() |
77
|
|
|
{ |
78
|
|
|
self::$mockQueue = []; |
79
|
|
|
self::$mock = null; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @return bool |
84
|
|
|
*/ |
85
|
|
|
public static function hasMock() |
86
|
|
|
{ |
87
|
|
|
return (bool)self::$mockQueue; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* @return MockHandler |
92
|
|
|
*/ |
93
|
|
|
public static function getMock() |
94
|
|
|
{ |
95
|
|
|
return self::$mock; |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|