-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBencode.php
47 lines (38 loc) · 859 Bytes
/
Bencode.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
namespace PureBencode;
class Bencode {
private static function isAssoc(array $array) {
$i = 0;
foreach ($array as $k => $v)
if ($k !== $i++)
return true;
return false;
}
/**
* @param int|string|array $value
* @return string
*/
static function encode($value) {
if (is_array($value)) {
if (self::isAssoc($value)) {
ksort($value, SORT_STRING);
$result = '';
foreach ($value as $k => $v)
$result .= self::encode("$k") . self::encode($v);
return "d{$result}e";
} else {
$result = '';
foreach ($value as $v)
$result .= self::encode($v);
return "l{$result}e";
}
} else if (is_int($value)) {
return "i{$value}e";
} else if (is_string($value)) {
return strlen($value) . ":$value";
} else {
return "d14:failure reason30:服务器内部错误. (EC: 1)e";
}
}
}
?>