summaryrefslogtreecommitdiff
path: root/vendor/guzzle/guzzle/src/Guzzle/Stream/PhpStreamRequestFactory.php
blob: d115fd890c94c7c70262539198918ae74c07caf8 (plain)
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
<?php

namespace Guzzle\Stream;

use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Url;

/**
 * Factory used to create fopen streams using PHP's http and https stream wrappers
 *
 * Note: PHP's http stream wrapper only supports streaming downloads. It does not support streaming uploads.
 */
class PhpStreamRequestFactory implements StreamRequestFactoryInterface
{
    /** @var resource Stream context options */
    protected $context;

    /** @var array Stream context */
    protected $contextOptions;

    /** @var Url Stream URL */
    protected $url;

    /** @var array Last response headers received by the HTTP request */
    protected $lastResponseHeaders;

    /**
     * {@inheritdoc}
     *
     * The $params array can contain the following custom keys specific to the PhpStreamRequestFactory:
     * - stream_class: The name of a class to create instead of a Guzzle\Stream\Stream object
     */
    public function fromRequest(RequestInterface $request, $context = array(), array $params = array())
    {
        if (is_resource($context)) {
            $this->contextOptions = stream_context_get_options($context);
            $this->context = $context;
        } elseif (is_array($context) || !$context) {
            $this->contextOptions = $context;
            $this->createContext($params);
        } elseif ($context) {
            throw new InvalidArgumentException('$context must be an array or resource');
        }

        // Dispatch the before send event
        $request->dispatch('request.before_send', array(
            'request'         => $request,
            'context'         => $this->context,
            'context_options' => $this->contextOptions
        ));

        $this->setUrl($request);
        $this->addDefaultContextOptions($request);
        $this->addSslOptions($request);
        $this->addBodyOptions($request);
        $this->addProxyOptions($request);

        // Create the file handle but silence errors
        return $this->createStream($params)
            ->setCustomData('request', $request)
            ->setCustomData('response_headers', $this->getLastResponseHeaders());
    }

    /**
     * Set an option on the context and the internal options array
     *
     * @param string $wrapper   Stream wrapper name of http
     * @param string $name      Context name
     * @param mixed  $value     Context value
     * @param bool   $overwrite Set to true to overwrite an existing value
     */
    protected function setContextValue($wrapper, $name, $value, $overwrite = false)
    {
        if (!isset($this->contextOptions[$wrapper])) {
            $this->contextOptions[$wrapper] = array($name => $value);
        } elseif (!$overwrite && isset($this->contextOptions[$wrapper][$name])) {
            return;
        }
        $this->contextOptions[$wrapper][$name] = $value;
        stream_context_set_option($this->context, $wrapper, $name, $value);
    }

    /**
     * Create a stream context
     *
     * @param array $params Parameter array
     */
    protected function createContext(array $params)
    {
        $options = $this->contextOptions;
        $this->context = $this->createResource(function () use ($params, $options) {
            return stream_context_create($options, $params);
        });
    }

    /**
     * Get the last response headers received by the HTTP request
     *
     * @return array
     */
    public function getLastResponseHeaders()
    {
        return $this->lastResponseHeaders;
    }

    /**
     * Adds the default context options to the stream context options
     *
     * @param RequestInterface $request Request
     */
    protected function addDefaultContextOptions(RequestInterface $request)
    {
        $this->setContextValue('http', 'method', $request->getMethod());
        $headers = $request->getHeaderLines();

        // "Connection: close" is required to get streams to work in HTTP 1.1
        if (!$request->hasHeader('Connection')) {
            $headers[] = 'Connection: close';
        }

        $this->setContextValue('http', 'header', $headers);
        $this->setContextValue('http', 'protocol_version', $request->getProtocolVersion());
        $this->setContextValue('http', 'ignore_errors', true);
    }

    /**
     * Set the URL to use with the factory
     *
     * @param RequestInterface $request Request that owns the URL
     */
    protected function setUrl(RequestInterface $request)
    {
        $this->url = $request->getUrl(true);

        // Check for basic Auth username
        if ($request->getUsername()) {
            $this->url->setUsername($request->getUsername());
        }

        // Check for basic Auth password
        if ($request->getPassword()) {
            $this->url->setPassword($request->getPassword());
        }
    }

    /**
     * Add SSL options to the stream context
     *
     * @param RequestInterface $request Request
     */
    protected function addSslOptions(RequestInterface $request)
    {
        if ($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER)) {
            $this->setContextValue('ssl', 'verify_peer', true, true);
            if ($cafile = $request->getCurlOptions()->get(CURLOPT_CAINFO)) {
                $this->setContextValue('ssl', 'cafile', $cafile, true);
            }
        } else {
            $this->setContextValue('ssl', 'verify_peer', false, true);
        }
    }

    /**
     * Add body (content) specific options to the context options
     *
     * @param RequestInterface $request
     */
    protected function addBodyOptions(RequestInterface $request)
    {
        // Add the content for the request if needed
        if (!($request instanceof EntityEnclosingRequestInterface)) {
            return;
        }

        if (count($request->getPostFields())) {
            $this->setContextValue('http', 'content', (string) $request->getPostFields(), true);
        } elseif ($request->getBody()) {
            $this->setContextValue('http', 'content', (string) $request->getBody(), true);
        }

        // Always ensure a content-length header is sent
        if (isset($this->contextOptions['http']['content'])) {
            $headers = isset($this->contextOptions['http']['header']) ? $this->contextOptions['http']['header'] : array();
            $headers[] = 'Content-Length: ' . strlen($this->contextOptions['http']['content']);
            $this->setContextValue('http', 'header', $headers, true);
        }
    }

    /**
     * Add proxy parameters to the context if needed
     *
     * @param RequestInterface $request Request
     */
    protected function addProxyOptions(RequestInterface $request)
    {
        if ($proxy = $request->getCurlOptions()->get(CURLOPT_PROXY)) {
            $this->setContextValue('http', 'proxy', $proxy);
        }
    }

    /**
     * Create the stream for the request with the context options
     *
     * @param array $params Parameters of the stream
     *
     * @return StreamInterface
     */
    protected function createStream(array $params)
    {
        $http_response_header = null;
        $url = $this->url;
        $context = $this->context;
        $fp = $this->createResource(function () use ($context, $url, &$http_response_header) {
            return fopen((string) $url, 'r', false, $context);
        });

        // Determine the class to instantiate
        $className = isset($params['stream_class']) ? $params['stream_class'] : __NAMESPACE__ . '\\Stream';

        /** @var $stream StreamInterface */
        $stream = new $className($fp);

        // Track the response headers of the request
        if (isset($http_response_header)) {
            $this->lastResponseHeaders = $http_response_header;
            $this->processResponseHeaders($stream);
        }

        return $stream;
    }

    /**
     * Process response headers
     *
     * @param StreamInterface $stream
     */
    protected function processResponseHeaders(StreamInterface $stream)
    {
        // Set the size on the stream if it was returned in the response
        foreach ($this->lastResponseHeaders as $header) {
            if ((stripos($header, 'Content-Length:')) === 0) {
                $stream->setSize(trim(substr($header, 15)));
            }
        }
    }

    /**
     * Create a resource and check to ensure it was created successfully
     *
     * @param callable $callback Closure to invoke that must return a valid resource
     *
     * @return resource
     * @throws RuntimeException on error
     */
    protected function createResource($callback)
    {
        $errors = null;
        set_error_handler(function ($_, $msg, $file, $line) use (&$errors) {
            $errors[] = array(
                'message' => $msg,
                'file'    => $file,
                'line'    => $line
            );
            return true;
        });
        $resource = call_user_func($callback);
        restore_error_handler();

        if (!$resource) {
            $message = 'Error creating resource. ';
            foreach ($errors as $err) {
                foreach ($err as $key => $value) {
                    $message .= "[$key] $value" . PHP_EOL;
                }
            }
            throw new RuntimeException(trim($message));
        }

        return $resource;
    }
}