Passed
Push — master ( 514bca...891b04 )
by smiley
02:57
created

Number   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 20
dl 0
loc 49
rs 10
c 2
b 0
f 0
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A parseInt() 0 16 3
A write() 0 15 5
1
<?php
2
/**
3
 * Class Number
4
 *
5
 * @filesource   Number.php
6
 * @created      26.11.2015
7
 * @package      QRCode
8
 * @author       Smiley <[email protected]>
9
 * @copyright    2015 Smiley
10
 * @license      MIT
11
 */
12
13
namespace chillerlan\QRCode\Data;
14
15
use chillerlan\QRCode\QRCode;
16
17
use function ord, sprintf, substr;
18
19
/**
20
 * Numeric mode: decimal digits 0 through 9
21
 */
22
class Number extends QRDataAbstract{
23
24
	protected int $datamode = QRCode::DATA_NUMBER;
25
26
	protected array $lengthBits = [10, 12, 14];
27
28
	/**
29
	 * @inheritdoc
30
	 */
31
	protected function write(string $data):void{
32
		$i = 0;
33
34
		while($i + 2 < $this->strlen){
35
			$this->bitBuffer->put($this->parseInt(substr($data, $i, 3)), 10);
36
			$i += 3;
37
		}
38
39
		if($i < $this->strlen){
40
41
			if($this->strlen - $i === 1){
42
				$this->bitBuffer->put($this->parseInt(substr($data, $i, $i + 1)), 4);
43
			}
44
			elseif($this->strlen - $i === 2){
45
				$this->bitBuffer->put($this->parseInt(substr($data, $i, $i + 2)), 7);
46
			}
47
48
		}
49
50
	}
51
52
	/**
53
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
54
	 */
55
	protected function parseInt(string $string):int{
56
		$num = 0;
57
58
		$len = strlen($string);
59
		for($i = 0; $i < $len; $i++){
60
			$c = ord($string[$i]);
61
62
			if(!in_array($string[$i], $this::NUMBER_CHAR_MAP, true)){
63
				throw new QRCodeDataException(sprintf('illegal char: "%s" [%d]', $string[$i], $c));
64
			}
65
66
			$c   = $c - 48; // ord('0')
67
			$num = $num * 10 + $c;
68
		}
69
70
		return $num;
71
	}
72
73
}
74