Completed
Push — master ( b042a4...d2fe3d )
by Josh
17:24
created

Native::request()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 19
ccs 16
cts 16
cp 1
rs 9.2
cc 4
eloc 10
nc 8
nop 4
crap 4
1
<?php
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2016 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\TextFormatter\Configurator\Helpers\Http\Clients;
9
10
use s9e\TextFormatter\Configurator\Helpers\Http\Client;
11
12
class Native extends Client
13
{
14
	/**
15
	* @var bool Whether to use gzip encoding
16
	*/
17
	public $gzipEnabled;
18
19
	/**
20
	* Constructor
21
	*
22
	* @return void
23
	*/
24 4
	public function __construct()
25
	{
26 4
		$this->gzipEnabled = extension_loaded('zlib');
27 4
	}
28
29
	/**
30
	* {@inheritdoc}
31
	*/
32 2
	public function get($url, $headers = [])
33
	{
34 2
		return $this->request('GET', $url, $headers);
35
	}
36
37
	/**
38
	* {@inheritdoc}
39
	*/
40 2
	public function post($url, $headers = [], $body = null)
41
	{
42 2
		return $this->request('POST', $url, $headers, $body);
43
	}
44
45
	/**
46
	* Decompress given page if applicable
47
	*
48
	* @param  string|bool $content Request's response body or FALSE
49
	* @return string|bool
50
	*/
51 4
	protected function decompress($content)
52
	{
53 4
		if ($this->gzipEnabled && substr($content, 0, 2) === "\x1f\x8b")
54 4
		{
55 4
			return gzdecode($content);
56
		}
57
58
		return $content;
59
	}
60
61
	/**
62
	* Execute an HTTP request
63
	*
64
	* @param  string      $method  Request method
65
	* @param  string      $url     Request URL
66
	* @param  string[]    $headers Request headers
67
	* @return string|bool          Response body or FALSE
68
	*/
69 4
	protected function request($method, $url, $headers, $body = null)
70
	{
71 4
		$contextOptions = ['http' => ['method' => $method]];
72 4
		if ($this->gzipEnabled)
73 4
		{
74 4
			$headers[] = 'Accept-Encoding: gzip';
75 4
		}
76 4
		if (isset($body))
77 4
		{
78 2
			$headers[] = 'Content-Length: ' . strlen($body);
79 2
			$contextOptions['http']['content'] = $body;
80 2
		}
81 4
		if (!empty($headers))
82 4
		{
83 4
			$contextOptions['http']['header'] = $headers;
84 4
		}
85
86 4
		return $this->decompress(file_get_contents($url, false, stream_context_create($contextOptions)));
87
	}
88
}