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

NonCompliantDecoder   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 58
ccs 23
cts 23
cp 1
rs 10
c 2
b 0
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A decodeDictionary() 0 12 2
A complianceError() 0 2 1
A decodeString() 0 14 3
A dictionaryComplianceError() 0 3 1
A readDigits() 0 10 2
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
}