RemoveWhitespace::optimizeStream()   B
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 8.8571
cc 5
eloc 8
nc 3
nop 0
crap 5
1
<?php
2
3
/**
4
* @package   s9e\SourceOptimizer
5
* @copyright Copyright (c) 2014-2018 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\SourceOptimizer\Passes;
9
10
class RemoveWhitespace extends AbstractPass
11
{
12
	/**
13
	* @var bool Whether to remove blank lines from the source
14
	*/
15
	public $removeBlankLines = true;
16
17
	/**
18
	* @var bool Whether to remove the indentation at the start of a line
19
	*/
20
	public $removeIndentation = false;
21
22
	/**
23
	* @var bool Whether to remove superfluous whitespace inside of a line
24
	*/
25
	public $removeSameLineWhitespace = true;
26
27
	/**
28
	* {@inheritdoc}
29
	*/
30 13
	protected function optimizeStream()
31
	{
32 13
		$regexp = $this->getRegexp();
33 13
		while ($this->stream->skipTo(T_WHITESPACE))
34
		{
35 13
			$ws = $this->stream->currentText();
36 13
			if ($this->removeSameLineWhitespace && strpos($ws, "\n") === false && $this->stream->canRemoveCurrentToken())
37
			{
38 11
				$this->stream->remove();
39 11
				continue;
40
			}
41
42 13
			$this->stream->replace([T_WHITESPACE, preg_replace($regexp, "\n", $ws)]);
43
		}
44 13
	}
45
46
	/**
47
	* Generate the regexp that corresponds to the removal options
48
	*
49
	* @return string
50
	*/
51 13
	protected function getRegexp()
52
	{
53 13
		if ($this->removeBlankLines)
54
		{
55 11
			return ($this->removeIndentation) ? '(\\n\\s+)' : '(\\n\\s*\\n)';
56
		}
57
58 2
		if ($this->removeIndentation)
59
		{
60 1
			return '(\\n[ \\t]+)';
61
		}
62
63 1
		return '((?!))';
64
	}
65
}