- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketHttpClient.php
More file actions
110 lines (80 loc) · 2.46 KB
/
SocketHttpClient.php
File metadata and controls
110 lines (80 loc) · 2.46 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
108
109
110
<?php
namespace Mpdf\Http;
use Mpdf\Log\Context as LogContext;
use Mpdf\PsrHttpMessageShim\Response;
use Mpdf\PsrHttpMessageShim\Stream;
use Mpdf\PsrLogAwareTrait\PsrLogAwareTrait;
use Psr\Http\Message\RequestInterface;
use Psr\Log\LoggerInterface;
class SocketHttpClient implements \Mpdf\Http\ClientInterface, \Psr\Log\LoggerAwareInterface
{
use PsrLogAwareTrait;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function sendRequest(RequestInterface $request)
{
if (null === $request->getUri()) {
return (new Response()); // @todo throw exception
}
$url = $request->getUri();
if (is_string($url)) {
$url = new Uri($url);
}
$timeout = 1;
$file = $url->getPath() ?: '/';
$scheme = $url->getScheme();
$port = $url->getPort() ?: 80;
$prefix = '';
if ($scheme === 'https') {
$prefix = 'ssl://';
$port = $url->getPort() ?: 443;
}
$query = $url->getQuery();
if ($query) {
$file .= '?' . $query;
}
$socketPath = $prefix . $url->getHost();
$this->logger->debug(sprintf('Opening socket on %s:%s of URL "%s"', $socketPath, $port, $request->getUri()), ['context' => LogContext::REMOTE_CONTENT]);
$response = new Response();
if (!($fh = @fsockopen($socketPath, $port, $errno, $errstr, $timeout))) {
$this->logger->error(sprintf('Socket error "%s": "%s"', $errno, $errstr), ['context' => LogContext::REMOTE_CONTENT]);
return $response;
}
$getRequest = 'GET ' . $file . ' HTTP/1.1' . "\r\n" .
'Host: ' . $url->getHost() . " \r\n" .
'Connection: close' . "\r\n\r\n";
fwrite($fh, $getRequest);
$httpHeader = fgets($fh, 1024);
if (!$httpHeader) {
return $response; // @todo throw exception
}
preg_match('@HTTP/(?P<protocolVersion>[\d\.]+) (?P<httpStatusCode>[\d]+) .*@', $httpHeader, $parsedHeader);
if (!$parsedHeader) {
return $response; // @todo throw exception
}
$response = $response->withStatus($parsedHeader['httpStatusCode']);
while (!feof($fh)) {
$s = fgets($fh, 1024);
if ($s === "\r\n") {
break;
}
preg_match('/^(?P<headerName>.*?): ?(?P<headerValue>.*)$/', $s, $parsedHeader);
if (!$parsedHeader) {
continue;
}
$response = $response->withHeader($parsedHeader['headerName'], trim($parsedHeader['headerValue']));
}
$body = '';
while (!feof($fh)) {
$line = fgets($fh, 1024);
$body .= $line;
}
fclose($fh);
$stream = Stream::create($body);
$stream->rewind();
return $response
->withBody($stream);
}
}