XpressEngine Core  1.11.2
 All Classes Namespaces Files Functions Variables Pages
Mock.php
Go to the documentation of this file.
1 <?php
24 require_once 'HTTP/Request2/Adapter.php';
25 
51 {
56  protected $responses = array();
57 
72  {
73  $requestUrl = (string)$request->getUrl();
74  $response = null;
75  foreach ($this->responses as $k => $v) {
76  if (!$v[1] || $requestUrl == $v[1]) {
77  $response = $v[0];
78  array_splice($this->responses, $k, 1);
79  break;
80  }
81  }
82  if (!$response) {
83  return self::createResponseFromString("HTTP/1.1 400 Bad Request\r\n\r\n");
84 
85  } elseif ($response instanceof HTTP_Request2_Response) {
86  return $response;
87 
88  } else {
89  // rethrow the exception
90  $class = get_class($response);
91  $message = $response->getMessage();
92  $code = $response->getCode();
93  throw new $class($message, $code);
94  }
95  }
96 
107  public function addResponse($response, $url = null)
108  {
109  if (is_string($response)) {
110  $response = self::createResponseFromString($response);
111  } elseif (is_resource($response)) {
112  $response = self::createResponseFromFile($response);
113  } elseif (!$response instanceof HTTP_Request2_Response &&
114  !$response instanceof Exception
115  ) {
116  throw new HTTP_Request2_Exception('Parameter is not a valid response');
117  }
118  $this->responses[] = array($response, $url);
119  }
120 
129  public static function createResponseFromString($str)
130  {
131  $parts = preg_split('!(\r?\n){2}!m', $str, 2);
132  $headerLines = explode("\n", $parts[0]);
133  $response = new HTTP_Request2_Response(array_shift($headerLines));
134  foreach ($headerLines as $headerLine) {
135  $response->parseHeaderLine($headerLine);
136  }
137  $response->parseHeaderLine('');
138  if (isset($parts[1])) {
139  $response->appendBody($parts[1]);
140  }
141  return $response;
142  }
143 
152  public static function createResponseFromFile($fp)
153  {
154  $response = new HTTP_Request2_Response(fgets($fp));
155  do {
156  $headerLine = fgets($fp);
157  $response->parseHeaderLine($headerLine);
158  } while ('' != trim($headerLine));
159 
160  while (!feof($fp)) {
161  $response->appendBody(fread($fp, 8192));
162  }
163  return $response;
164  }
165 }
166 ?>
sendRequest(HTTP_Request2 $request)
Definition: Mock.php:71
static createResponseFromString($str)
Definition: Mock.php:129
static createResponseFromFile($fp)
Definition: Mock.php:152
addResponse($response, $url=null)
Definition: Mock.php:107