Blame view

vendor/alibabacloud/client/src/Traits/MockTrait.php 2.12 KB
f0d6cde5   xu   vendor
1
2
3
4
5
<?php

namespace AlibabaCloud\Client\Traits;

use Exception;
f0d6cde5   xu   vendor
6
7
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
0c34aba8   xu   更新阿里云短信接口
8
use GuzzleHttp\Handler\MockHandler;
f0d6cde5   xu   vendor
9
10
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
0c34aba8   xu   更新阿里云短信接口
11
use GuzzleHttp\Exception\RequestException;
f0d6cde5   xu   vendor
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

/**
 * Class MockTrait
 *
 * @package AlibabaCloud\Client\Request\Traits
 * @mixin Request
 */
trait MockTrait
{
    /**
     * @var array
     */
    private static $mockQueue = [];

    /**
     * @var MockHandler
     */
    private static $mock;

    /**
     * @param integer             $status
     * @param array               $headers
     * @param array|string|object $body
     */
    public static function mockResponse($status = 200, array $headers = [], $body = null)
    {
        if (is_array($body) || is_object($body)) {
            $body = json_encode($body);
        }

        self::$mockQueue[] = new Response($status, $headers, $body);
        self::createHandlerStack();
    }

    private static function createHandlerStack()
    {
        self::$mock = new MockHandler(self::$mockQueue);
    }

    /**
     * @param string                 $message
     * @param RequestInterface       $request
     * @param ResponseInterface|null $response
     * @param Exception|null         $previous
     * @param array                  $handlerContext
     */
    public static function mockRequestException(
        $message,
        RequestInterface $request,
        ResponseInterface $response = null,
        Exception $previous = null,
        array $handlerContext = []
    ) {
        self::$mockQueue[] = new RequestException(
            $message,
            $request,
            $response,
            $previous,
            $handlerContext
        );

        self::createHandlerStack();
    }

    public static function cancelMock()
    {
        self::$mockQueue = [];
        self::$mock      = null;
    }

    /**
     * @return bool
     */
    public static function hasMock()
    {
        return (bool)self::$mockQueue;
    }

    /**
     * @return MockHandler
     */
    public static function getMock()
    {
        return self::$mock;
    }
}