Completed
Push — master ( b6e3ce...d0c1a3 )
by Josh
15:23
created

HostedMinifier::getContext()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 9.4286
cc 1
eloc 8
nc 1
nop 2
crap 1
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\JavaScript\Minifiers;
9
10
use RuntimeException;
11
use s9e\TextFormatter\Configurator\JavaScript\Minifier;
12
13
class HostedMinifier extends Minifier
14
{
15
	/**
16
	* @var integer Compression level used to compress the request's payload
17
	*/
18
	public $gzLevel = 5;
19
20
	/**
21
	* @var integer
22
	*/
23
	public $timeout = 20;
24
25
	/**
26
	* @var string
27
	*/
28
	public $url = 'http://s9e-textformatter.rhcloud.com/minifier/minify.php';
29
30
	/**
31
	* {@inheritdoc}
32
	*/
33 2
	public function minify($src)
34
	{
35 2
		$url     = $this->url;
36 2
		$headers = ['Connection: close', 'Content-Type: application/octet-stream'];
37 2
		$content = $src;
38 2
		if (extension_loaded('zlib'))
39 2
		{
40 2
			$url       = 'compress.zlib://' . $url;
41 2
			$headers[] = 'Content-Encoding: gzip';
42 2
			$headers[] = 'Accept-Encoding: gzip';
43 2
			$content   = gzencode($content, $this->gzLevel);
44 2
		}
45 2
		$headers[] = 'Content-Length: ' . strlen($content);
46
47 2
		$content = file_get_contents($url, false, $this->getContext($headers, $content));
48 2
		if (empty($http_response_header[0]) || strpos($http_response_header[0], '200') === false)
49 2
		{
50 1
			throw new RuntimeException($content);
51
		}
52
53 1
		return $content;
54
	}
55
56
	/**
57
	* Create the HTTP stream context for given request
58
	*
59
	* @param  string[] $headers Request headers
60
	* @param  string   $content Request body
61
	* @return resource
62
	*/
63 2
	protected function getContext(array $headers, $content)
64
	{
65 2
		return stream_context_create([
66
			'http' => [
67 2
				'method'        => 'POST',
68 2
				'header'        => implode("\r\n", $headers),
69 2
				'content'       => $content,
70 2
				'timeout'       => $this->timeout,
71
				'ignore_errors' => true
72 2
			]
73 2
		]);
74
	}
75
}