_data = $data; $this -> _position = 0; $this -> _length = strlen($data); return $this -> detect(); } /** * @param string $file * @return array */ public function decodeFile($file) { if (!file_exists($file)) { throw new Bencode_Exception('File not found'); } return $this -> decodeString(file_get_contents($file)); } /** * @return array */ protected function detect() { $char = $this -> getChar(); if ($char == "d") { return $this -> getDictionary(); } else if ($char == 'i'){ return $this -> getInt(); } else if ( is_numeric($char)) { return $this -> getString(); } else if ($char == "l") { return $this -> getList(); } throw new Bencode_Exception('File parsing error'); } /** * @return array */ protected function getDictionary() { $dict = array(); $this -> next(); while( ($char = $this -> getChar()) !== "e" ) { $key = $this -> getString(); $value = $this -> detect(); $dict[$key] = $value; } $this -> next(); return $dict; } /** * @return array */ protected function getList() { $dict = array(); $this -> next(); while( ($char = $this -> getChar()) !== "e" ) { $dict[] = $this -> detect(); } $this -> next(); return $dict; } /** * @return string */ protected function getString() { $separator = strpos($this -> _data, ":", $this -> _position); if ($separator === false) { throw new Bencode_Exception('Bad format'); } $length = substr($this -> _data, $this -> _position, $separator - $this -> _position); if (! is_numeric($length)) { throw new Bencode_Exception('Bad format'); } $this -> _position = $separator + $length + 1; return substr($this -> _data, $separator + 1, $length); } /** * @return string */ protected function getInt() { $this -> next(); $end = strpos($this -> _data, "e", $this -> _position); if ($end === false) { throw new Bencode_Exception('Bad format'); } $int = substr($this -> _data, $this -> _position, $end - $this -> _position); if (! is_numeric($int)) { throw new Bencode_Exception('Bad format'); } $this -> _position = $end + 1; return $int; } /** * @return string */ protected function getChar() { if ($this -> _position >= $this -> _length) { throw new Bencode_Exception('EOF'); } return substr($this -> _data, $this -> _position, 1); } /** * @param int $count * @return Bencode_Decode */ protected function next($count = 1) { $this -> _position += $count; return $this; } }