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