1 | <?php |
||
12 | class HttpPlayback |
||
13 | { |
||
14 | protected $mode = 'live'; |
||
15 | |||
16 | protected $callList = []; |
||
17 | |||
18 | protected $recordLocation; |
||
19 | |||
20 | protected $recordFileName = 'saveState.json'; |
||
21 | |||
22 | private $shutdownRegistered = false; |
||
23 | |||
24 | private static $instances = []; |
||
25 | |||
26 | /** |
||
27 | * @var Client |
||
28 | */ |
||
29 | private $client; |
||
30 | |||
31 | 33 | public static function getInstance($options = []) |
|
48 | |||
49 | 30 | public function setPlaybackOptions($options = []) |
|
68 | |||
69 | /** |
||
70 | * Get the client for making calls |
||
71 | * |
||
72 | * @return Client |
||
73 | */ |
||
74 | 26 | public function getHttpClient() |
|
75 | { |
||
76 | 26 | if ($this->client == null) { |
|
77 | 26 | $handler = HandlerStack::create(); |
|
78 | |||
79 | 26 | if ($this->mode == 'record') { |
|
80 | $history = Middleware::history($this->callList); |
||
81 | $handler->push($history); |
||
82 | 26 | } elseif ($this->mode == 'playback') { |
|
83 | 26 | $recordings = $this->getRecordings(); |
|
84 | |||
85 | 26 | $playList = $recordings; |
|
86 | 26 | $mockedResponses = []; |
|
87 | 26 | foreach ($playList as $item) { |
|
88 | 26 | if (!$item['error']) { |
|
89 | 25 | $mockedResponses[] = new Response($item['statusCode'], $item['headers'], $item['body']); |
|
90 | } else { |
||
91 | 2 | $errorClass = $item['errorClass']; |
|
92 | 2 | $request = new Request( |
|
93 | 2 | $item['request']['method'], |
|
94 | 2 | $item['request']['uri'], |
|
95 | 2 | $item['request']['headers'], |
|
96 | 2 | $item['request']['body'] |
|
97 | ); |
||
98 | 26 | $mockedResponses[] = new $errorClass($item['errorMessage'], $request); |
|
99 | } |
||
100 | } |
||
101 | |||
102 | 26 | $mockHandler = new MockHandler($mockedResponses); |
|
103 | 26 | $handler = HandlerStack::create($mockHandler); |
|
104 | } |
||
105 | |||
106 | 26 | $this->client = new Client(['handler' => $handler]); |
|
107 | |||
108 | 26 | if (!$this->shutdownRegistered) { |
|
109 | 26 | register_shutdown_function(array($this, 'endRecord')); |
|
110 | 26 | $this->shutdownRegistered = true; |
|
111 | } |
||
112 | } |
||
113 | |||
114 | 26 | return $this->client; |
|
115 | } |
||
116 | |||
117 | /** |
||
118 | * Sets the client |
||
119 | * |
||
120 | * @param Client $client |
||
121 | * @return $this |
||
122 | */ |
||
123 | public function setHttpClient($client) |
||
129 | |||
130 | 27 | public function getRecordLocation() |
|
142 | |||
143 | 27 | public function getRecordFilePath() |
|
150 | |||
151 | 26 | public function getRecordings() |
|
158 | |||
159 | 1 | public function endRecord() |
|
201 | } |
||
202 |