scratch – Blame information for rev 87

Subversion Repositories:
Rev:
Rev Author Line No. Line
87 office 1 <?php
2  
3 namespace GuzzleHttp\Adapter;
4  
5 use GuzzleHttp\Event\RequestEvents;
6 use GuzzleHttp\Message\ResponseInterface;
7  
8 /**
9 * Adapter that can be used to associate mock responses with a transaction
10 * while still emulating the event workflow of real adapters.
11 */
12 class MockAdapter implements AdapterInterface
13 {
14 private $response;
15  
16 /**
17 * @param ResponseInterface|callable $response Response to serve or function
18 * to invoke that handles a transaction
19 */
20 public function __construct($response = null)
21 {
22 $this->setResponse($response);
23 }
24  
25 /**
26 * Set the response that will be served by the adapter
27 *
28 * @param ResponseInterface|callable $response Response to serve or
29 * function to invoke that handles a transaction
30 */
31 public function setResponse($response)
32 {
33 $this->response = $response;
34 }
35  
36 public function send(TransactionInterface $transaction)
37 {
38 RequestEvents::emitBefore($transaction);
39 if (!$transaction->getResponse()) {
40  
41 $response = is_callable($this->response)
42 ? call_user_func($this->response, $transaction)
43 : $this->response;
44 if (!$response instanceof ResponseInterface) {
45 throw new \RuntimeException('Invalid mocked response');
46 }
47  
48 // Read the request body if it is present
49 if ($transaction->getRequest()->getBody()) {
50 $transaction->getRequest()->getBody()->__toString();
51 }
52  
53 $transaction->setResponse($response);
54 RequestEvents::emitHeaders($transaction);
55 RequestEvents::emitComplete($transaction);
56 }
57  
58 return $transaction->getResponse();
59 }
60 }