/**
  * Reads a Bencoded file and puts it into and array.
  */
 public function testReadingFile()
 {
     // you should always trim an opened file, in case of a newline character
     // at the end, f*****g some shit up
     $stream = trim(file_get_contents(__DIR__ . '/assets/dictionary.be'));
     $dictionary = new Dictionary();
     $dictionary->decode($stream);
     $this->assertEquals($stream, $dictionary->encode());
 }
Beispiel #2
0
 /**
  * Decoding a Dictionary is a lot like decoding a List, however we are
  * looking for the firs two Elements and setting them as the key and value
  * of the array.
  * 
  * A key must be an encoded byte, however the value can be any of the other
  * elements, such as an Integer, List or another Dictionary.
  * 
  * @param string $stream Encoded Dictionary
  * 
  * @return string the remainder of the stream, if anything
  */
 public function decode($stream)
 {
     $stream = $this->dropEncoding($stream, self::PATTERN);
     if (is_numeric($stream[0])) {
         $key = new Byte();
     } elseif ($stream[0] === 'i') {
         $key = new Integer();
     } else {
         return $stream;
     }
     // always read the key first, then onto the value
     $stream = $key->decode($stream);
     if (is_numeric($stream[0])) {
         $value = new Byte();
     } elseif ($stream[0] === 'i') {
         $value = new Integer();
     } elseif ($stream[0] === 'l') {
         $value = new BList();
     } elseif ($stream[0] === 'd') {
         $value = new Dictionary();
     } else {
         throw new DictionaryException('Improper dictionary value encoding: ' . $stream);
     }
     $stream = $value->decode($stream);
     // assign the key and value.
     $this->_buffer[$key->write()] = $value->write();
     if (strlen($stream) > 0) {
         return $this->decode($stream);
     }
     return $stream;
 }
<?php

/**
 * This file will demonstrate opening a .torrent file and getting its
 * contents. Run it from the command line and see the comment from the
 * 'test.torrent' file in the tests/assets/ directory.
 */
require '../vendor/autoload.php';
use Bencode\Collection\Dictionary;
$dictionary = new Dictionary();
$torrent = file_get_contents('../tests/assets/test.torrent');
$dictionary->decode($torrent);
$buffer = $dictionary->write();
var_dump($buffer);
echo $buffer['comment'] . "\n";