|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace VideoPublisher\Connection\Curl; |
|
4
|
|
|
|
|
5
|
|
|
use VideoPublisher\Payload\Payload; |
|
6
|
|
|
use VideoPublisher\Connection\ConnectionInterface; |
|
7
|
|
|
use VideoPublisher\Connection\ConnectionException; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Class CurlPost. |
|
11
|
|
|
* |
|
12
|
|
|
* @author Bart Malestein <[email protected]> |
|
13
|
|
|
*/ |
|
14
|
|
|
class CurlPost implements ConnectionInterface |
|
15
|
|
|
{ |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var int |
|
19
|
|
|
*/ |
|
20
|
|
|
private $curlOptConnectionTimeOut; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @var int |
|
24
|
|
|
*/ |
|
25
|
|
|
private $curlOptTimeOut; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* CurlPost constructor. |
|
29
|
|
|
* |
|
30
|
|
|
* @param int $curlOptConnectionTimeOut |
|
31
|
|
|
* @param int $curlOptTimeOut |
|
32
|
|
|
*/ |
|
33
|
|
|
public function __construct($curlOptConnectionTimeOut = 2, $curlOptTimeOut = 8) |
|
34
|
|
|
{ |
|
35
|
|
|
$this->curlOptConnectionTimeOut = $curlOptConnectionTimeOut; |
|
36
|
|
|
$this->curlOptTimeOut = $curlOptTimeOut; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @param Payload $payload |
|
41
|
|
|
* @return CurlResponse |
|
42
|
|
|
* @throws ConnectionException |
|
43
|
|
|
*/ |
|
44
|
|
|
public function sendPayload(Payload $payload) |
|
45
|
|
|
{ |
|
46
|
|
|
$ch = curl_init($payload->getUrl()); |
|
47
|
|
|
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); |
|
48
|
|
|
curl_setopt($ch, CURLOPT_HEADER, 1); |
|
49
|
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
|
50
|
|
|
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->curlOptConnectionTimeOut); |
|
51
|
|
|
curl_setopt($ch, CURLOPT_TIMEOUT, $this->curlOptTimeOut); |
|
52
|
|
|
|
|
53
|
|
|
if (in_array($payload->getMethod(), [ |
|
54
|
|
|
'post', |
|
55
|
|
|
'put' |
|
56
|
|
|
])) { |
|
57
|
|
|
curl_setopt($ch, CURLOPT_POST, 1); |
|
58
|
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload->getPostData())); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
$headers = $payload->getHeaders(); |
|
62
|
|
|
if (false === empty($headers)) { |
|
63
|
|
|
$curlHeaders = array(); |
|
64
|
|
|
foreach ($headers as $key => $value) { |
|
65
|
|
|
$curlHeaders[] = $key . ': ' . $value; |
|
66
|
|
|
} |
|
67
|
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
$content = curl_exec($ch); |
|
71
|
|
|
if ($content === false) { |
|
72
|
|
|
throw new ConnectionException(); |
|
73
|
|
|
} |
|
74
|
|
|
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); |
|
75
|
|
|
$retHeaders = substr($content, 0, $header_size); |
|
76
|
|
|
$body = substr($content, $header_size); |
|
77
|
|
|
|
|
78
|
|
|
return new CurlResponse(curl_getinfo($ch, CURLINFO_HTTP_CODE), $retHeaders, $body); |
|
79
|
|
|
} |
|
80
|
|
|
} |