Server.php
2.84 KB
1
2
3
4
5
6
7
8
9
10
11
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
98
99
100
101
102
103
104
105
106
107
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Message\MessageFactory;
use GuzzleHttp\Message\Response;
use GuzzleHttp\Message\ResponseInterface;
use GuzzleHttp\RingBridge;
use GuzzleHttp\Tests\Ring\Client\Server as TestServer;
/**
* Placeholder for the RingPHP-Client server that makes it easier to use.
*/
class Server
{
public static $url = 'http://127.0.0.1:8125/';
public static $port = 8125;
/**
* Queue an array of responses or a single response on the server.
*
* Any currently queued responses will be overwritten. Subsequent requests
* on the server will return queued responses in FIFO order.
*
* @param array $responses Responses to queue.
* @throws \Exception
*/
public static function enqueue(array $responses)
{
static $factory;
if (!$factory) {
$factory = new MessageFactory();
}
$data = [];
foreach ($responses as $response) {
// Create the response object from a string
if (is_string($response)) {
$response = $factory->fromMessage($response);
} elseif (!($response instanceof ResponseInterface)) {
throw new \Exception('Responses must be strings or Responses');
}
$data[] = self::convertResponse($response);
}
TestServer::enqueue($data);
}
/**
* Get all of the received requests
*
* @param bool $hydrate Set to TRUE to turn the messages into
* actual {@see RequestInterface} objects. If $hydrate is FALSE,
* requests will be returned as strings.
*
* @return array
* @throws \RuntimeException
*/
public static function received($hydrate = false)
{
$response = TestServer::received();
if ($hydrate) {
$c = new Client();
$factory = new MessageFactory();
$response = array_map(function($message) use ($factory, $c) {
return RingBridge::fromRingRequest($message);
}, $response);
}
return $response;
}
public static function flush()
{
TestServer::flush();
}
public static function stop()
{
TestServer::stop();
}
public static function wait($maxTries = 5)
{
TestServer::wait($maxTries);
}
public static function start()
{
TestServer::start();
}
private static function convertResponse(Response $response)
{
$headers = array_map(function ($h) {
return implode(', ', $h);
}, $response->getHeaders());
return [
'status' => $response->getStatusCode(),
'reason' => $response->getReasonPhrase(),
'headers' => $headers,
'body' => base64_encode((string) $response->getBody())
];
}
}