|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Akatsuki\Component\Bencode; |
|
4
|
|
|
|
|
5
|
|
|
use JsonSerializable; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class Encoder |
|
9
|
|
|
* |
|
10
|
|
|
* @package Akatsuki\Component\Bencode |
|
11
|
|
|
* @author Aurimas Niekis <[email protected]> |
|
12
|
|
|
*/ |
|
13
|
|
|
class Encoder |
|
14
|
|
|
{ |
|
15
|
|
|
private $data; |
|
16
|
|
|
|
|
17
|
7 |
|
public function encode($data): string |
|
18
|
|
|
{ |
|
19
|
7 |
|
if (is_object($data)) { |
|
20
|
2 |
|
if ($data instanceof BencodeSerializable) { |
|
21
|
1 |
|
$data = $data->bencodeSerialize(); |
|
22
|
|
|
} else { |
|
23
|
1 |
|
$data = (array)$data; |
|
24
|
|
|
} |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
7 |
|
$this->data = $data; |
|
28
|
|
|
|
|
29
|
7 |
|
return $this->doEncode(); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
7 |
|
private function doEncode($data = null): string |
|
33
|
|
|
{ |
|
34
|
7 |
|
$data = $data ?? $this->data; |
|
35
|
|
|
|
|
36
|
7 |
|
if (is_array($data) && (isset ($data[0]) || empty ($data))) { |
|
37
|
1 |
|
return $this->encodeList($data); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
7 |
|
if (is_array($data)) { |
|
41
|
4 |
|
return $this->encodeDict($data); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
7 |
|
if (is_int($data) || is_float($data)) { |
|
45
|
3 |
|
$data = sprintf('%.0f', round($data, 0)); |
|
46
|
|
|
|
|
47
|
3 |
|
return $this->encodeInteger($data); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
6 |
|
return $this->encodeString($data); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
3 |
|
private function encodeInteger($data = null): string |
|
54
|
|
|
{ |
|
55
|
3 |
|
$data = $data ?? $this->data; |
|
56
|
|
|
|
|
57
|
3 |
|
return sprintf("i%.0fe", $data); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
6 |
|
private function encodeString($data = null): string |
|
61
|
|
|
{ |
|
62
|
6 |
|
$data = $data ?? $this->data; |
|
63
|
|
|
|
|
64
|
6 |
|
return sprintf("%d:%s", strlen($data), $data); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
1 |
|
private function encodeList(array $data = null): string |
|
68
|
|
|
{ |
|
69
|
1 |
|
$data = $data ?? $this->data; |
|
70
|
|
|
|
|
71
|
1 |
|
$list = ''; |
|
72
|
1 |
|
foreach ($data as $value) { |
|
73
|
1 |
|
$list .= $this->doEncode($value); |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
1 |
|
return 'l' . $list . 'e'; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
4 |
|
private function encodeDict(array $data = null): string |
|
80
|
|
|
{ |
|
81
|
4 |
|
$data = $data ?? $this->data; |
|
82
|
4 |
|
ksort($data); |
|
83
|
|
|
|
|
84
|
4 |
|
$dict = ''; |
|
85
|
4 |
|
foreach ($data as $key => $value) { |
|
86
|
4 |
|
$dict .= $this->encodeString($key) . $this->doEncode($value); |
|
87
|
|
|
} |
|
88
|
|
|
|
|
89
|
4 |
|
return 'd' . $dict . 'e'; |
|
90
|
|
|
} |
|
91
|
|
|
} |