|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Zwartpet\PHPCertificateToolbox; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
6
|
|
|
|
|
7
|
|
|
class TestResponseGenerator |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* Given an HTTP response, this can dump a function which will generate a Response object which can |
|
11
|
|
|
* be used during testing to simulate that response |
|
12
|
|
|
* |
|
13
|
|
|
* @param $method |
|
14
|
|
|
* @param $url |
|
15
|
|
|
* @param ResponseInterface $response |
|
16
|
|
|
* @codeCoverageIgnore |
|
17
|
|
|
*/ |
|
18
|
|
|
public static function dumpTestSimulation($method, $url, ResponseInterface $response) |
|
19
|
|
|
{ |
|
20
|
|
|
static $count = 0; |
|
21
|
|
|
$count++; |
|
22
|
|
|
|
|
23
|
|
|
echo "/**\n"; |
|
24
|
|
|
echo " * Simulate response for $method $url\n"; |
|
25
|
|
|
echo " */\n"; |
|
26
|
|
|
echo "protected function getAcmeResponse{$count}()\n"; |
|
27
|
|
|
echo "{\n"; |
|
28
|
|
|
|
|
29
|
|
|
echo " \$date = new \DateTime;\n"; |
|
30
|
|
|
echo " \$now = \$date->format('D, j M Y H:i:s e');\n"; |
|
31
|
|
|
|
|
32
|
|
|
//store body as heredoc |
|
33
|
|
|
$body = $response->getBody(); |
|
34
|
|
|
if (strlen($body)) { |
|
35
|
|
|
$body = preg_replace('/^/m', ' ', $response->getBody()); |
|
36
|
|
|
echo " \$body = <<<JSON\n"; |
|
37
|
|
|
echo $body; |
|
38
|
|
|
echo "\nJSON;\n"; |
|
39
|
|
|
} |
|
40
|
|
|
echo " \$body=trim(\$body);\n\n"; |
|
41
|
|
|
|
|
42
|
|
|
//dump the header array, replacing dates with a current date |
|
43
|
|
|
echo " \$headers=[\n"; |
|
44
|
|
|
$headers = $response->getHeaders(); |
|
45
|
|
|
foreach ($headers as $name => $values) { |
|
46
|
|
|
//most headers are single valued |
|
47
|
|
|
if (count($values) == 1) { |
|
48
|
|
|
$value = var_export($values[0], true); |
|
49
|
|
|
} else { |
|
50
|
|
|
$value = var_export($values, true); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
//give date-related headers something current when testing |
|
54
|
|
|
if (in_array($name, ['Expires', 'Date'])) { |
|
55
|
|
|
$value = '$now'; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
//ensure content length is correct for our simulated body |
|
59
|
|
|
if ($name == 'Content-Length') { |
|
60
|
|
|
$value = 'strlen($body)'; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
echo " '$name' => " . $value . ",\n"; |
|
64
|
|
|
} |
|
65
|
|
|
echo " ];\n"; |
|
66
|
|
|
|
|
67
|
|
|
$status=$response->getStatusCode(); |
|
68
|
|
|
|
|
69
|
|
|
echo " return new Response($status, \$headers, \$body);\n"; |
|
70
|
|
|
echo "}\n\n"; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|