Mark Slee | 99e2b26 | 2006-10-10 01:42:29 +0000 | [diff] [blame] | 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Php stream transport. Reads to and writes from the php standard streams |
| 5 | * php://input and php://output |
| 6 | * |
| 7 | * @package thrift.transport |
| 8 | * @author Mark Slee <mcslee@facebook.com> |
| 9 | */ |
| 10 | class TPhpStream extends TTransport { |
| 11 | |
| 12 | const MODE_R = 1; |
| 13 | const MODE_W = 2; |
| 14 | |
| 15 | private $inStream_ = null; |
| 16 | |
| 17 | private $outStream_ = null; |
| 18 | |
| 19 | private $read_ = false; |
| 20 | |
| 21 | private $write_ = false; |
| 22 | |
| 23 | public function __construct($mode) { |
| 24 | $this->read_ = $mode & self::MODE_R; |
| 25 | $this->write_ = $mode & self::MODE_W; |
| 26 | } |
| 27 | |
| 28 | public function open() { |
| 29 | if ($this->read_) { |
| 30 | $this->inStream_ = @fopen('php://input', 'r'); |
| 31 | if (!is_resource($this->inStream_)) { |
| 32 | throw new Exception('TPhpStream: Could not open php://input'); |
| 33 | } |
| 34 | } |
| 35 | if ($this->write_) { |
| 36 | $this->outStream_ = @fopen('php://output', 'w'); |
| 37 | if (!is_resource($this->outStream_)) { |
| 38 | throw new Exception('TPhpStream: Could not open php://output'); |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | public function close() { |
| 44 | if ($this->read_) { |
| 45 | @fclose($this->inStream_); |
| 46 | $this->inStream_ = null; |
| 47 | } |
| 48 | if ($this->write_) { |
| 49 | @fclose($this->outStream_); |
| 50 | $this->outStream_ = null; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | public function isOpen() { |
| 55 | return |
| 56 | (!$this->read_ || is_resource($this->inStream_)) && |
| 57 | (!$this->write_ || is_resource($this->outStream_)); |
| 58 | } |
| 59 | |
| 60 | public function read($len) { |
| 61 | $data = @fread($this->inStream_, $len); |
| 62 | if (!$data) { |
| 63 | throw new Exception('TPhpStream: Could not read '.$len.' bytes'); |
| 64 | } |
| 65 | return $data; |
| 66 | } |
| 67 | |
| 68 | public function write($buf) { |
| 69 | while (!empty($buf)) { |
| 70 | $got = @fwrite($this->outStream_, $buf); |
| 71 | if ($got === 0 || $got === FALSE) { |
| 72 | throw new Exception('TPhpStream: Could not write '.strlen($buf).' bytes'); |
| 73 | } |
| 74 | $buf = substr($buf, $got); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | public function flush() { |
| 79 | @fflush($this->outStream_); |
| 80 | } |
| 81 | |
| 82 | } |
| 83 | |
| 84 | ?> |