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
|
9 |
|
protected function decodeDictionary(): ArrayObject |
28
|
|
|
{ |
29
|
9 |
|
$previousState = $this->sortDictionary; |
30
|
9 |
|
$this->sortDictionary = false; |
31
|
9 |
|
$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
|
12 |
|
protected function decodeString(): string |
42
|
|
|
{ |
43
|
12 |
|
if ($this->bencoded[$this->offset] === 'i') |
44
|
|
|
{ |
45
|
2 |
|
return (string) $this->decodeInteger(); |
46
|
|
|
} |
47
|
|
|
|
48
|
11 |
|
return parent::decodeString(); |
49
|
|
|
} |
50
|
|
|
|
51
|
4 |
|
protected function dictionaryComplianceError(string $key, string $lastKey): void |
52
|
|
|
{ |
53
|
4 |
|
$this->sortDictionary = true; |
54
|
|
|
} |
55
|
|
|
|
56
|
18 |
|
protected function readDigits(string $terminator): string |
57
|
|
|
{ |
58
|
18 |
|
if ($this->bencoded[$this->offset] === '0') |
59
|
|
|
{ |
60
|
|
|
// Skip past the trailing zeroes and stop at the next digit or the last zero |
61
|
10 |
|
preg_match('(0++[1-9]?)A', $this->bencoded, $m, 0, $this->offset); |
62
|
10 |
|
$this->offset += strlen($m[0]) - 1; |
63
|
|
|
} |
64
|
|
|
|
65
|
18 |
|
return parent::readDigits($terminator); |
66
|
|
|
} |
67
|
|
|
} |