Passed
Push — master ( cab9a5...488e58 )
by Josh
03:04
created

PrintableAscii   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 11
c 1
b 0
f 0
dl 0
loc 63
ccs 14
cts 14
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 3
A outputValidValue() 0 13 4
A escapeControlCode() 0 5 2
A escapeAscii() 0 3 1
1
<?php declare(strict_types=1);
2
3
/**
4
* @package   s9e\RegexpBuilder
5
* @copyright Copyright (c) 2016-2020 The s9e authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\RegexpBuilder\Output;
9
10
abstract class PrintableAscii extends BaseImplementation
11
{
12
	/**
13
	* @var string 'x' for lowercase hexadecimal symbols, 'X' for uppercase
14
	*/
15
	protected $hexCase;
16
17
	/**
18
	* {@inheritdoc}
19
	*/
20 34
	public function __construct(array $options = [])
21
	{
22 34
		$this->hexCase = (isset($options['case']) && $options['case'] === 'lower') ? 'x' : 'X';
23 34
	}
24
25
	/**
26
	* Escape given ASCII codepoint
27
	*
28
	* @param  integer $cp
29
	* @return string
30
	*/
31 6
	protected function escapeAscii(int $cp): string
32
	{
33 6
		return '\\x' . sprintf('%02' . $this->hexCase, $cp);
34
	}
35
36
	/**
37
	* Escape given control code
38
	*
39
	* @param  integer $cp
40
	* @return string
41
	*/
42 6
	protected function escapeControlCode(int $cp): string
43
	{
44 6
		$table = [9 => '\\t', 10 => '\\n', 13 => '\\r'];
45
46 6
		return (isset($table[$cp])) ? $table[$cp] : $this->escapeAscii($cp);
47
	}
48
49
	/**
50
	* Output the representation of a unicode character
51
	*
52
	* @param  integer $cp Unicode codepoint
53
	* @return string
54
	*/
55
	abstract protected function escapeUnicode(int $cp): string;
56
57
	/**
58
	* {@inheritdoc}
59
	*/
60 32
	protected function outputValidValue(int $value): string
61
	{
62 32
		if ($value < 32)
63
		{
64 6
			return $this->escapeControlCode($value);
65
		}
66
67 26
		if ($value < 127)
68
		{
69 6
			return chr($value);
70
		}
71
72 20
		return ($value > 255) ? $this->escapeUnicode($value) : $this->escapeAscii($value);
73
	}
74
}