I rather create new from scratch such as a PHP 7 version of BDecode
<?php
namespace System\Protocol;
class Bdecode
{
/**
* Bencode.
*
* @var string
*/
protected $bencode;
/**
* Length.
*
* @var integer
*/
protected $length = 0;
/**
* Offset.
*
* @var integer
*/
protected $offset = 0;
/**
* Decode.
*
* @param string $bencode
* @return mixed
*/
public function decode(string $bencode = null)
{
if ($this->bencode === null) {
if ($bencode !== null) {
$this->bencode = $bencode;
$this->length = strlen($bencode);
} else {
return null;
}
}
if ($this->offset >= $this->length) {
return null;
}
$char = $this->bencode[$this->offset];
if ($char === 'd') {
return $this->decodeDict();
} elseif ($char === 'l') {
return $this->decodeList();
} elseif ($char === 'i') {
return $this->decodeInt();
} elseif (is_numeric($char)) {
return $this->decodeStr();
} else {
return null;
}
}
/**
* Decode dictionary.
*
* @return array|null
*/
private function decodeDict()
{
$start = substr($this->bencode, $this->offset, 1);
if ($start !== 'd') {
return null;
}
$limit = substr($this->bencode, -1);
if ($limit !== 'e') {
return null;
}
$this->offset++;
$dict = [];
while ($this->bencode[$this->offset] !== 'e') {
$index = $this->decodeStr();
if ($index === null) {
return null;
}
$value = $this->decode();
if ($value === null) {
return null;
}
$dict[$index] = $value;
}
$this->offset++;
return $dict;
}
/**
* Decode list.
*
* @return array|null
*/
private function decodeList()
{
$start = substr($this->bencode, $this->offset, 1);
if ($start !== 'l') {
return null;
}
$limit = substr($this->bencode, -1);
if ($limit !== 'e') {
return null;
}
$this->offset++;
$list = [];
while ($this->bencode[$this->offset] !== 'e') {
$value = $this->decode();
if ($value === null) {
return null;
}
$list[] = $value;
}
$this->offset++;
return $list;
}
/**
* Decode integer.
*
* @return string|null
*/
private function decodeInt()
{
$start = substr($this->bencode, $this->offset, 1);
if ($start !== 'i') {
return null;
}
$limit = strpos($this->bencode, 'e', $this->offset);
if ($limit === false) {
return null;
}
$this->offset++;
$buffer = '';
while ($this->offset < $limit) {
$buffer .= $this->bencode[$this->offset];
$this->offset++;
}
$this->offset++;
if (preg_match('@^([0]|[-]?[1-9][0-9]*)$@', $buffer)) {
return 0 + $buffer;
} else {
return null;
}
}
/**
* Decode string.
*
* @return string|null
*/
private function decodeStr()
{
$delimiter = strpos($this->bencode, ':', $this->offset);
if ($delimiter === false) {
return null;
}
$length = substr($this->bencode, $this->offset, $delimiter - $this->offset);
if (! preg_match('@^([0]|[1-9][0-9]*)$@', $length)) {
return null;
}
$this->offset = ++$delimiter;
$buffer = substr($this->bencode, $this->offset, $length);
$strlen = strlen($buffer);
if ($strlen != $length) {
return null;
}
$this->offset += $length;
return $buffer;
}
}