GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Stream::request()   F
last analyzed

Complexity

Conditions 29
Paths > 20000

Size

Total Lines 183

Duplication

Lines 18
Ratio 9.84 %

Importance

Changes 0
Metric Value
cc 29
nc 512000
nop 6
dl 18
loc 183
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Part of the Joomla Framework Http Package
4
 *
5
 * @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
6
 * @license    GNU General Public License version 2 or later; see LICENSE
7
 */
8
9
namespace Joomla\Http\Transport;
10
11
use Composer\CaBundle\CaBundle;
12
use Joomla\Http\Exception\InvalidResponseCodeException;
13
use Joomla\Http\TransportInterface;
14
use Joomla\Http\Response;
15
use Joomla\Uri\Uri;
16
use Joomla\Uri\UriInterface;
17
18
/**
19
 * HTTP transport class for using PHP streams.
20
 *
21
 * @since  1.0
22
 */
23
class Stream implements TransportInterface
24
{
25
	/**
26
	 * The client options.
27
	 *
28
	 * @var    array|\ArrayAccess
29
	 * @since  1.0
30
	 */
31
	protected $options;
32
33
	/**
34
	 * Constructor.
35
	 *
36
	 * @param   array|\ArrayAccess  $options  Client options array.
37
	 *
38
	 * @since   1.0
39
	 * @throws  \RuntimeException
40
	 */
41 View Code Duplication
	public function __construct($options = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
42
	{
43
		// Verify that fopen() is available.
44
		if (!self::isSupported())
45
		{
46
			throw new \RuntimeException('Cannot use a stream transport when fopen() is not available.');
47
		}
48
49
		// Verify that URLs can be used with fopen();
50
		if (!ini_get('allow_url_fopen'))
51
		{
52
			throw new \RuntimeException('Cannot use a stream transport when "allow_url_fopen" is disabled.');
53
		}
54
55
		if (!is_array($options) && !($options instanceof \ArrayAccess))
56
		{
57
			throw new \InvalidArgumentException(
58
				'The options param must be an array or implement the ArrayAccess interface.'
59
			);
60
		}
61
62
		$this->options = $options;
63
	}
64
65
	/**
66
	 * Send a request to the server and return a Response object with the response.
67
	 *
68
	 * @param   string        $method     The HTTP method for sending the request.
69
	 * @param   UriInterface  $uri        The URI to the resource to request.
70
	 * @param   mixed         $data       Either an associative array or a string to be sent with the request.
71
	 * @param   array         $headers    An array of request headers to send with the request.
72
	 * @param   integer       $timeout    Read timeout in seconds.
73
	 * @param   string        $userAgent  The optional user agent string to send with the request.
74
	 *
75
	 * @return  Response
76
	 *
77
	 * @since   1.0
78
	 * @throws  \RuntimeException
79
	 */
80
	public function request($method, UriInterface $uri, $data = null, array $headers = null, $timeout = null, $userAgent = null)
81
	{
82
		// Create the stream context options array with the required method offset.
83
		$options = array('method' => strtoupper($method));
84
85
		// If data exists let's encode it and make sure our Content-Type header is set.
86
		if (isset($data))
87
		{
88
			// If the data is a scalar value simply add it to the stream context options.
89
			if (is_scalar($data))
90
			{
91
				$options['content'] = $data;
92
			}
93
			else
94
			// Otherwise we need to encode the value first.
95
			{
96
				$options['content'] = http_build_query($data);
97
			}
98
99
			if (!isset($headers['Content-Type']))
100
			{
101
				$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
102
			}
103
104
			// Add the relevant headers.
105
			$headers['Content-Length'] = strlen($options['content']);
106
		}
107
108
		// If an explicit timeout is given user it.
109
		if (isset($timeout))
110
		{
111
			$options['timeout'] = (int) $timeout;
112
		}
113
114
		// If an explicit user agent is given use it.
115
		if (isset($userAgent))
116
		{
117
			$options['user_agent'] = $userAgent;
118
		}
119
120
		// Ignore HTTP errors so that we can capture them.
121
		$options['ignore_errors'] = 1;
122
123
		// Follow redirects.
124
		$options['follow_location'] = isset($this->options['follow_location']) ? (int) $this->options['follow_location'] : 1;
125
126
		// Configure protocol version, use transport's default if not set otherwise.
127
		$options['follow_location'] = isset($this->options['protocolVersion']) ? $this->options['protocolVersion'] : '1.0';
128
129
		// Add the proxy configuration if enabled
130
		$proxyEnabled = isset($this->options['proxy.enabled']) ? (bool) $this->options['proxy.enabled'] : false;
131
132
		if ($proxyEnabled)
133
		{
134
			$options['request_fulluri'] = true;
135
136
			if (isset($this->options['proxy.host']) && isset($this->options['proxy.port']))
137
			{
138
				$options['proxy'] = $this->options['proxy.host'] . ':' . (int) $this->options['proxy.port'];
139
			}
140
141
			// If authentication details are provided, add those as well
142 View Code Duplication
			if (isset($this->options['proxy.user']) && isset($this->options['proxy.password']))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
143
			{
144
				$headers['Proxy-Authorization'] = 'Basic ' . base64_encode($this->options['proxy.user'] . ':' . $this->options['proxy.password']);
145
			}
146
		}
147
148
		// Build the headers string for the request.
149
		$headerString = null;
150
151
		if (isset($headers))
152
		{
153
			foreach ($headers as $key => $value)
154
			{
155
				$headerString .= $key . ': ' . $value . "\r\n";
156
			}
157
158
			// Add the headers string into the stream context options array.
159
			$options['header'] = trim($headerString, "\r\n");
160
		}
161
162
		// Authentication, if needed
163
		if ($uri instanceof Uri && isset($this->options['userauth']) && isset($this->options['passwordauth']))
0 ignored issues
show
Bug introduced by
The class Joomla\Uri\Uri does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
164
		{
165
			$uri->setUser($this->options['userauth']);
166
			$uri->setPass($this->options['passwordauth']);
167
		}
168
169
		// Set any custom transport options
170
		if (isset($this->options['transport.stream']))
171
		{
172
			foreach ($this->options['transport.stream'] as $key => $value)
173
			{
174
				$options[$key] = $value;
175
			}
176
		}
177
178
		// Get the current context options.
179
		$contextOptions = stream_context_get_options(stream_context_get_default());
180
181
		// Add our options to the currently defined options, if any.
182
		$contextOptions['http'] = isset($contextOptions['http']) ? array_merge($contextOptions['http'], $options) : $options;
183
184
		// Create the stream context for the request.
185
		$streamOptions = array(
186
			'http' => $options,
187
			'ssl' => array(
188
				'verify_peer'  => true,
189
				'verify_depth' => 5,
190
			)
191
		);
192
193
		// Ensure the ssl peer name is verified where possible
194
		if (version_compare(PHP_VERSION, '5.6.0') >= 0)
195
		{
196
			$streamOptions['ssl']['verify_peer_name'] = true;
197
		}
198
199
		// The cacert may be a file or path
200
		$certpath = isset($this->options['stream.certpath']) ? $this->options['stream.certpath'] : CaBundle::getSystemCaRootBundlePath();
201
202
		if (is_dir($certpath))
203
		{
204
			$streamOptions['ssl']['capath'] = $certpath;
205
		}
206
		else
207
		{
208
			$streamOptions['ssl']['cafile'] = $certpath;
209
		}
210
211
		$context = stream_context_create($streamOptions);
212
213
		// Capture PHP errors
214
		$php_errormsg = '';
215
		$trackErrors = ini_get('track_errors');
216
		ini_set('track_errors', true);
217
218
		// Open the stream for reading.
219
		$stream = @fopen((string) $uri, 'r', false, $context);
220
221 View Code Duplication
		if (!$stream)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
222
		{
223
			if (!$php_errormsg)
224
			{
225
				// Error but nothing from php? Create our own
226
				// @todo $err and $errno are undefined variables.
227
				$php_errormsg = sprintf('Could not connect to resource: %s', $uri, $err, $errno);
0 ignored issues
show
Bug introduced by
The variable $err does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $errno does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
228
			}
229
230
			// Restore error tracking to give control to the exception handler
231
			ini_set('track_errors', $trackErrors);
232
233
			throw new \RuntimeException($php_errormsg);
234
		}
235
236
		// Restore error tracking to what it was before.
237
		ini_set('track_errors', $trackErrors);
238
239
		// Get the metadata for the stream, including response headers.
240
		$metadata = stream_get_meta_data($stream);
241
242
		// Get the contents from the stream.
243
		$content = stream_get_contents($stream);
244
245
		// Close the stream.
246
		fclose($stream);
247
248
		if (isset($metadata['wrapper_data']['headers']))
249
		{
250
			$headers = $metadata['wrapper_data']['headers'];
251
		}
252
		elseif (isset($metadata['wrapper_data']))
253
		{
254
			$headers = $metadata['wrapper_data'];
255
		}
256
		else
257
		{
258
			$headers = array();
259
		}
260
261
		return $this->getResponse($headers, $content);
262
	}
263
264
	/**
265
	 * Method to get a response object from a server response.
266
	 *
267
	 * @param   array   $headers  The response headers as an array.
268
	 * @param   string  $body     The response body as a string.
269
	 *
270
	 * @return  Response
271
	 *
272
	 * @since   1.0
273
	 * @throws  InvalidResponseCodeException
274
	 */
275
	protected function getResponse(array $headers, $body)
276
	{
277
		// Create the response object.
278
		$return = new Response;
279
280
		// Set the body for the response.
281
		$return->body = $body;
282
283
		// Get the response code from the first offset of the response headers.
284
		preg_match('/[0-9]{3}/', array_shift($headers), $matches);
285
		$code = $matches[0];
286
287
		if (is_numeric($code))
288
		{
289
			$return->code = (int) $code;
290
		}
291
		// No valid response code was detected.
292
		else
293
		{
294
			throw new InvalidResponseCodeException('No HTTP response code found.');
295
		}
296
297
		// Add the response headers to the response object.
298 View Code Duplication
		foreach ($headers as $header)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
299
		{
300
			$pos = strpos($header, ':');
301
			$return->headers[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
302
		}
303
304
		return $return;
305
	}
306
307
	/**
308
	 * Method to check if http transport stream available for use
309
	 *
310
	 * @return  boolean  True if available else false
311
	 *
312
	 * @since   1.0
313
	 */
314
	public static function isSupported()
315
	{
316
		return function_exists('fopen') && is_callable('fopen') && ini_get('allow_url_fopen');
317
	}
318
}
319