|
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
|
13 |
|
public static function mockResponse($status = 200, array $headers = [], $body = null) |
|
32
|
|
|
{ |
|
33
|
13 |
|
if (is_array($body) || is_object($body)) { |
|
34
|
3 |
|
$body = json_encode($body); |
|
35
|
3 |
|
} |
|
36
|
|
|
|
|
37
|
13 |
|
self::$mockQueue[] = new Response($status, $headers, $body); |
|
38
|
13 |
|
} |
|
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
|
1 |
|
public static function mockRequestException( |
|
48
|
|
|
$message, |
|
49
|
|
|
RequestInterface $request, |
|
50
|
|
|
ResponseInterface $response = null, |
|
51
|
|
|
\Exception $previous = null, |
|
52
|
|
|
array $handlerContext = [] |
|
53
|
|
|
) { |
|
54
|
1 |
|
self::$mockQueue[] = new RequestException( |
|
55
|
1 |
|
$message, |
|
56
|
1 |
|
$request, |
|
57
|
1 |
|
$response, |
|
58
|
1 |
|
$previous, |
|
59
|
|
|
$handlerContext |
|
60
|
1 |
|
); |
|
61
|
1 |
|
} |
|
62
|
|
|
|
|
63
|
57 |
|
public static function clearMockQueue() |
|
64
|
|
|
{ |
|
65
|
57 |
|
self::$mockQueue = []; |
|
66
|
57 |
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* @return bool |
|
70
|
|
|
*/ |
|
71
|
62 |
|
public static function hasMockQueue() |
|
72
|
|
|
{ |
|
73
|
62 |
|
return (bool)self::$mockQueue; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* @return HandlerStack |
|
78
|
|
|
*/ |
|
79
|
13 |
|
public static function getMockQueue() |
|
80
|
|
|
{ |
|
81
|
13 |
|
$mock = new MockHandler(self::$mockQueue); |
|
82
|
|
|
|
|
83
|
13 |
|
return HandlerStack::create($mock); |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|