/** * Returns an encoded stream of a Dictionary element. * * @return string Encoded Dictionary */ public function encode() { $buffer = 'd'; foreach ($this->_buffer as $k => $v) { $key = new Byte(); $key->read($k); if (is_array($v)) { $dictionary = false; foreach (array_keys($v) as $ak) { if (!is_numeric($ak)) { $dictionary = true; } } if ($dictionary) { $value = new Dictionary(); } else { $value = new BList(); } } elseif (is_numeric($v)) { $value = new Integer(); } else { $value = new Byte(); } $value->read($v); $buffer .= $key->encode() . $value->encode(); } $buffer .= 'e'; return $buffer; }
/** * Reads a raw stream and decodes the List encoded portion of it. This will * append data to the internal buffer. * * @param string A raw encoded stream of a Bencode List. * * @throws BListException; */ public function decode($stream) { $stream = $this->dropEncoding($stream, self::PATTERN); // This block determines which type of primitive element is in the list if ($stream[0] === 'i') { $element = new Integer(); } elseif (is_numeric($stream[0])) { $element = new Byte(); } else { throw new BListException('Decoded improper encoding: ' . $stream); } $stream = $element->decode($stream); $this->_buffer[] = $element->write(); if (strlen($stream) > 0) { return $this->decode($stream); } }
public function testZeroIntStreamEncoding() { $byte = new Byte('0'); $this->assertEquals('1:0', $byte->encode()); }