1: <?php
2: 3: 4: 5: 6: 7:
8:
9: namespace PipelinerSales\ApiClient\Http;
10:
11: 12: 13:
14: class CurlHttpClient implements HttpInterface
15: {
16:
17: private = null;
18: private $username;
19: private $password;
20: private $userAgent;
21:
22: public function __construct($userAgent = 'Pipeliner_PHP_API_Client/1.0')
23: {
24: $this->userAgent = $userAgent;
25: }
26:
27: public function request($method, $url, $rawPayload = null, $contentType = 'application/json')
28: {
29: $ch = curl_init($url);
30:
31: curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
32: curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
33: curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
34: curl_setopt($ch, CURLOPT_HEADER, 1);
35: if (!empty($rawPayload)) {
36: curl_setopt($ch, CURLOPT_POSTFIELDS, $rawPayload);
37: curl_setopt(
38: $ch,
39: CURLOPT_HTTPHEADER,
40: array(
41: 'Content-Length: ' . strlen($rawPayload),
42: 'Content-Type: ' . $contentType
43: )
44: );
45: }
46:
47: if (!empty($this->extraCurlOptions)) {
48: curl_setopt_array($ch, $this->extraCurlOptions);
49: }
50:
51: if (!empty($this->username)) {
52: curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password);
53: }
54:
55: $result = curl_exec($ch);
56:
57: if ($result !== false) {
58: list($headers, $body) = explode("\r\n\r\n", $result, 2);
59: } else {
60: list($headers, $body) = array('', '');
61: }
62: $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
63:
64: if ($result === false or $status < 200 or $status > 399) {
65: throw new PipelinerHttpException(
66: new Response($body, $headers, $status, $url, $method),
67: '',
68: curl_error($ch)
69: );
70: }
71:
72: return new Response($body, $headers, $status, $url, $method);
73: }
74:
75: public function setUserCredentials($username, $password)
76: {
77: $this->username = $username;
78: $this->password = $password;
79: }
80:
81: 82: 83: 84:
85: public function setUserAgent($userAgent)
86: {
87: $this->userAgent = $userAgent;
88: }
89:
90: 91: 92: 93:
94: public function (array $extraOptions)
95: {
96: $this->extraCurlOptions = $extraOptions;
97: }
98: }
99: