示例#1
0
 /**
  * Returns the decoded array from $str
  * @throws an IllegalArgumentException in the case
  * that the string is malformed.
  */
 public static function toArray($str)
 {
     if (substr($str, 0, 1) != "d" || substr($str, -1, 1) != "e") {
         throw new IllegalArgumentException("BEncoded dictionary does not start with d or end with e.");
     }
     // An array is simply two lists encoded in an alternating list
     $arrays = BList::toList("l" . substr($str, 1));
     $i = 0;
     for ($i = 0; $i < sizeof($arrays); $i += 2) {
         $array[$arrays[$i]] = $arrays[$i + 1];
     }
     return $array;
 }
示例#2
0
 /**
  * Returns the decoded array from $str
  * @throws an IllegalArgumentException in the case
  * that the string is malformed.
  */
 public static function toList($str)
 {
     if (substr($str, 0, 1) != "l" || substr($str, -1, 1) != "e") {
         throw new IllegalArgumentException("BEncoded list does not start with l or end with e.");
     }
     $value = substr($str, 1, -1);
     // Scan through encoded list and decode everything
     $list = array();
     $i = 0;
     $lastI = 0;
     while ($i < strlen($value)) {
         $curChar = substr($value, $i, 1);
         if ($curChar == "i") {
             // We just saw an Integer
             $endPos = strpos($value, "e", $i);
             // Search for the end of it
             if ($endPos === false) {
                 throw new IllegalArgumentException("BEncoded list contains non-terminated integer");
             }
             $list[] = BInteger::toInteger(substr($value, $i, $endPos - $i + 1));
             $i = $endPos + 1;
         } elseif (is_numeric($curChar)) {
             // A number means we just saw a string starting
             $seperatorPos = strpos($value, ":", $i);
             // Search for the seperator
             if ($seperatorPos === false) {
                 throw new IllegalArgumentException("BEncoded list contains malformed string with no length specified");
             }
             $totalLength = substr($value, $i, $seperatorPos - $i);
             $list[] = BString::toString(substr($value, $i, $seperatorPos - $i + $totalLength + 1));
             $i = $seperatorPos + $totalLength + 1;
         } elseif ($curChar == "d" || $curChar == "l") {
             // Found a dictionary or list
             // Scan for end of it
             $listLength = BList::getListLength(substr($value, $i));
             if ($curChar == "d") {
                 $list[] = BDictionary::toArray(substr($value, $i, $listLength));
             } else {
                 $list[] = BList::toList(substr($value, $i, $listLength));
             }
             $i += $listLength;
         }
         if ($i == $lastI) {
             throw new IllegalArgumentException("BEncoded list contains malfomed or unrecognized content");
         }
         $lastI = $i;
     }
     return $list;
 }