1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace AlibabaCloud\Client\Traits; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Exception\RequestException; |
6
|
|
|
use GuzzleHttp\Handler\MockHandler; |
7
|
|
|
use GuzzleHttp\HandlerStack; |
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
|
|
|
* @param integer $status |
28
|
|
|
* @param array $headers |
29
|
|
|
* @param array|string|object $body |
30
|
|
|
*/ |
31
|
|
|
public static function mockResponse($status = 200, array $headers = [], $body = null) |
32
|
|
|
{ |
33
|
|
|
if (is_array($body) || is_object($body)) { |
34
|
|
|
$body = json_encode($body); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
self::$mockQueue[] = new Response($status, $headers, $body); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param string $message |
42
|
|
|
* @param RequestInterface $request |
43
|
|
|
* @param ResponseInterface|null $response |
44
|
|
|
* @param \Exception|null $previous |
45
|
|
|
* @param array $handlerContext |
46
|
|
|
*/ |
47
|
|
|
public static function mockRequestException( |
48
|
|
|
$message, |
49
|
|
|
RequestInterface $request, |
50
|
|
|
ResponseInterface $response = null, |
51
|
|
|
\Exception $previous = null, |
52
|
|
|
array $handlerContext = [] |
53
|
|
|
) { |
54
|
|
|
self::$mockQueue[] = new RequestException( |
55
|
|
|
$message, |
56
|
|
|
$request, |
57
|
|
|
$response, |
58
|
|
|
$previous, |
59
|
|
|
$handlerContext |
60
|
|
|
); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public static function clearMockQueue() |
64
|
|
|
{ |
65
|
|
|
self::$mockQueue = []; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @return bool |
70
|
|
|
*/ |
71
|
|
|
public static function hasMockQueue() |
72
|
|
|
{ |
73
|
|
|
return (bool)self::$mockQueue; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @return HandlerStack |
78
|
|
|
*/ |
79
|
|
|
public static function getMockQueue() |
80
|
|
|
{ |
81
|
|
|
$mock = new MockHandler(self::$mockQueue); |
82
|
|
|
|
83
|
|
|
return HandlerStack::create($mock); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|