1 | <?php |
||
19 | * |
||
20 | * @since 2.0.0 |
||
21 | */ |
||
22 | class CurlDriver implements DriverInterface |
||
23 | { |
||
24 | /** |
||
25 | * @var resource |
||
26 | */ |
||
27 | protected $ch; |
||
28 | |||
29 | /** |
||
30 | * @var array |
||
31 | */ |
||
32 | protected $curlOptions = array(); |
||
33 | |||
34 | /** |
||
35 | * @since 2.0.0 |
||
36 | */ |
||
37 | public function __destruct() |
||
38 | { |
||
39 | if (null !== $this->ch) { |
||
40 | curl_close($this->ch); |
||
41 | $this->ch=null; |
||
42 | } |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * @since 2.0.0 |
||
47 | * {@inheritDoc} |
||
48 | */ |
||
49 | public function execute(RequestInterface $request) |
||
50 | { |
||
51 | $uri = $request->getUri(); |
||
52 | |||
53 | if (null === $this->ch) { |
||
54 | $this->ch = curl_init(); |
||
55 | } |
||
56 | |||
57 | curl_setopt_array($this->ch, $this->getDefaultCurlOptions()); |
||
58 | |||
59 | curl_setopt($this->ch, CURLOPT_URL, sprintf('%s://%s@%s', $uri->getScheme(), $uri->getUserInfo(), $uri->getHost())); |
||
60 | curl_setopt($this->ch, CURLOPT_PORT, $uri->getPort()); |
||
61 | |||
62 | $headers = array(); |
||
63 | foreach ($request->getHeaders() as $header => $values) { |
||
64 | $headers[] = $header.': '.implode(', ', $values); |
||
65 | } |
||
66 | curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers); |
||
67 | curl_setopt($this->ch, CURLOPT_POSTFIELDS, $request->getBody()->getContents()); |
||
68 | |||
69 | // Allows user to override any option, may cause errors |
||
70 | curl_setopt_array($this->ch, $this->curlOptions); |
||
71 | |||
72 | /** @var string|false */ |
||
73 | $result = curl_exec($this->ch); |
||
74 | /** @var array|false */ |
||
75 | $info = curl_getinfo($this->ch); |
||
76 | /** @var string */ |
||
77 | $error = curl_error($this->ch); |
||
78 | |||
79 | if (!empty($error)) { |
||
80 | throw new \Exception($error); |
||
81 | } |
||
82 | |||
83 | $response = new Response(); |
||
84 | $response->withStatus($info['http_code']); |
||
85 | $response->getBody()->write($result); |
||
86 | |||
87 | return $response; |
||
88 | } |
||
89 | |||
90 | /** |
||
91 | * Add options to use for cURL requests |
||
92 | * |
||
93 | * @since 2.0.0 |
||
94 | * @param integer $option |
||
95 | * @param mixed $value |
||
96 | */ |
||
97 | public function addCurlOption($option, $value) |
||
98 | { |
||
99 | $this->curlOptions[$option] = $value; |
||
100 | |||
101 | return $this; |
||
102 | } |
||
103 | |||
104 | /** |
||
105 | * Returns an array of cURL options |
||
106 | * |
||
107 | * @since 2.0.0 |
||
108 | * @return array |
||
109 | */ |
||
110 | protected function getDefaultCurlOptions() |
||
111 | { |
||
112 | return array( |
||
113 | CURLOPT_POST => true, |
||
114 | CURLOPT_RETURNTRANSFER => true, |
||
115 | CURLOPT_CONNECTTIMEOUT => 5, |
||
116 | CURLOPT_TIMEOUT => 10, |
||
117 | ); |
||
120 |