Completed
Push — master ( 78d4e7...979ecb )
by smiley
02:57
created

factory_helpers.php ➔ create_stream_from_input()   B

Complexity

Conditions 9
Paths 7

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
nc 7
nop 1
dl 0
loc 29
rs 8.0555
c 0
b 0
f 0
1
<?php
2
/**
3
 * @filesource   factory_helpers.php
4
 * @created      28.08.2018
5
 * @author       smiley <[email protected]>
6
 * @copyright    2018 smiley
7
 * @license      MIT
8
 */
9
10
namespace chillerlan\HTTP\Psr17;
11
12
use chillerlan\HTTP\Psr7;
13
use chillerlan\HTTP\Psr7\{ServerRequest, Stream, Uri};
14
use InvalidArgumentException;
15
use Psr\Http\Message\StreamInterface;
16
17
const PSR17_INCLUDES = true;
18
19
/**
20
 * Return a ServerRequest populated with superglobals:
21
 * $_GET
22
 * $_POST
23
 * $_COOKIE
24
 * $_FILES
25
 * $_SERVER
26
 *
27
 * @return \chillerlan\HTTP\Psr7\ServerRequest|\Psr\Http\Message\ServerRequestInterface
28
 */
29
function create_server_request_from_globals():ServerRequest{
30
31
	$serverRequest = new ServerRequest(
32
		isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : ServerRequest::METHOD_GET,
33
		create_uri_from_globals(),
34
		function_exists('getallheaders') ? getallheaders() : [],
35
		(new StreamFactory)->createStream(),
36
		isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1',
37
		$_SERVER
38
	);
39
40
	return $serverRequest
41
		->withCookieParams($_COOKIE)
42
		->withQueryParams($_GET)
43
		->withParsedBody($_POST)
44
		->withUploadedFiles(Psr7\normalize_files($_FILES))
45
	;
46
}
47
48
/**
49
 * Get a Uri populated with values from $_SERVER.
50
 *
51
 * @return \chillerlan\HTTP\Psr7\Uri|\Psr\Http\Message\UriInterface
52
 */
53
function create_uri_from_globals():Uri{
54
	$parts    = [];
55
	$hasPort  = false;
56
	$hasQuery = false;
57
58
	$parts['scheme'] = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http';
59
60
	if(isset($_SERVER['HTTP_HOST'])){
61
		$hostHeaderParts = explode(':', $_SERVER['HTTP_HOST']);
62
		$parts['host'] = $hostHeaderParts[0];
63
64
		if(isset($hostHeaderParts[1])){
65
			$hasPort       = true;
66
			$parts['port'] = $hostHeaderParts[1];
67
		}
68
	}
69
	elseif(isset($_SERVER['SERVER_NAME'])){
70
		$parts['host'] = $_SERVER['SERVER_NAME'];
71
	}
72
	elseif(isset($_SERVER['SERVER_ADDR'])){
73
		$parts['host'] = $_SERVER['SERVER_ADDR'];
74
	}
75
76
	if(!$hasPort && isset($_SERVER['SERVER_PORT'])){
77
		$parts['port'] = $_SERVER['SERVER_PORT'];
78
	}
79
80
	if(isset($_SERVER['REQUEST_URI'])){
81
		$requestUriParts = explode('?', $_SERVER['REQUEST_URI']);
82
		$parts['path']   = $requestUriParts[0];
83
84
		if(isset($requestUriParts[1])){
85
			$hasQuery       = true;
86
			$parts['query'] = $requestUriParts[1];
87
		}
88
	}
89
90
	if(!$hasQuery && isset($_SERVER['QUERY_STRING'])){
91
		$parts['query'] = $_SERVER['QUERY_STRING'];
92
	}
93
94
	return Uri::fromParts($parts);
95
}
96
97
98
/**
99
 * Create a new stream from a string.
100
 *
101
 * The stream SHOULD be created with a temporary resource.
102
 *
103
 * @param string $content String content with which to populate the stream.
104
 *
105
 * @return \chillerlan\HTTP\Psr7\Stream|\Psr\Http\Message\StreamInterface
106
 */
107
function create_stream(string $content = ''):Stream{
108
	$stream = fopen('php://temp', 'r+');
109
110
	if($content !== ''){
111
		fwrite($stream, $content);
112
		fseek($stream, 0);
113
	}
114
115
	return new Stream($stream);
116
}
117
118
/**
119
 * @param mixed $in
120
 *
121
 * @return \chillerlan\HTTP\Psr7\Stream|\Psr\Http\Message\StreamInterface
122
 */
123
function create_stream_from_input($in = null):StreamInterface{
124
	$in = $in ?? '';
125
126
	if(is_string($in) && is_file($in) && is_readable($in)){
127
		return new Stream(fopen($in, 'r'));
128
	}
129
130
	if(is_scalar($in)){
131
		return create_stream((string)$in);
132
	}
133
134
	$type = gettype($in);
135
136
	if($type === 'resource'){
137
		return new Stream($in);
0 ignored issues
show
Documentation introduced by
$in is of type object|null|array, but the function expects a resource.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
138
	}
139
	elseif($type === 'object'){
140
141
		if($in instanceof StreamInterface){
142
			return $in;
143
		}
144
		elseif(method_exists($in, '__toString')){
145
			return create_stream((string)$in);
146
		}
147
148
	}
149
150
	throw new InvalidArgumentException('Invalid resource type: '.$type);
151
}
152