Passed
Push — master ( ec6c3a...62ef64 )
by Josh
01:58
created

NonCompliantDecoder::readDigits()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
/**
4
* @package   s9e\Bencode
5
* @copyright Copyright (c) The s9e authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\Bencode;
9
10
use ArrayObject;
11
use const SORT_STRING, false, true;
12
use function preg_match, strcmp, strlen;
13
use s9e\Bencode\Exceptions\DecodingException;
14
15
class NonCompliantDecoder extends Decoder
16
{
17
	/**
18
	* @var bool Whether current dictionary needs to be sorted
19
	*/
20
	protected bool $sortDictionary = false;
21
22 5
	protected function complianceError(string $message, int $offset): void
23
	{
24
		// Do nothing
25 5
	}
26
27 8
	protected function decodeDictionary(): ArrayObject
28
	{
29 8
		$previousState        = $this->sortDictionary;
30 8
		$this->sortDictionary = false;
31 8
		$dictionary           = parent::decodeDictionary();
32 6
		if ($this->sortDictionary)
33
		{
34 4
			$dictionary->ksort(SORT_STRING);
35
		}
36 6
		$this->sortDictionary = $previousState;
37
38 6
		return $dictionary;
39
	}
40
41 11
	protected function decodeString(): string
42
	{
43
		try
44
		{
45 11
			return parent::decodeString();
46
		}
47 3
		catch (DecodingException $e)
48
		{
49 3
			if ($this->bencoded[$this->offset] === 'i')
50
			{
51 2
				return (string) $this->decodeInteger();
52
			}
53
54 1
			throw $e;
55
		}
56
	}
57
58 4
	protected function dictionaryComplianceError(string $key, string $lastKey): void
59
	{
60 4
		$this->sortDictionary = true;
61
	}
62
63 17
	protected function readDigits(string $terminator): string
64
	{
65 17
		if ($this->bencoded[$this->offset] === '0')
66
		{
67
			// Skip past the trailing zeroes and stop at the next digit or the last zero
68 10
			preg_match('(0++[1-9]?)A', $this->bencoded, $m, 0, $this->offset);
69 10
			$this->offset += strlen($m[0]) - 1;
70
		}
71
72 17
		return parent::readDigits($terminator);
73
	}
74
}