blob: 03837a8a7a8c06a594e6c36e4d7c996aa2d5e523 [file] [log] [blame]
Mark Slee99e2b262006-10-10 01:42:29 +00001<?php
2
3/**
Mark Slee4902c052007-03-01 00:31:30 +00004 * 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/**
Mark Slee99e2b262006-10-10 01:42:29 +000015 * 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_)) {
Mark Slee76791962007-03-14 02:47:35 +000043 throw new TException('TPhpStream: Could not open php://input');
Mark Slee99e2b262006-10-10 01:42:29 +000044 }
45 }
46 if ($this->write_) {
47 $this->outStream_ = @fopen('php://output', 'w');
48 if (!is_resource($this->outStream_)) {
Mark Slee76791962007-03-14 02:47:35 +000049 throw new TException('TPhpStream: Could not open php://output');
Mark Slee99e2b262006-10-10 01:42:29 +000050 }
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) {
Mark Slee76791962007-03-14 02:47:35 +000074 throw new TException('TPhpStream: Could not read '.$len.' bytes');
Mark Slee99e2b262006-10-10 01:42:29 +000075 }
76 return $data;
77 }
78
79 public function write($buf) {
Mark Sleed395d572007-02-27 01:16:55 +000080 while (strlen($buf) > 0) {
Mark Slee99e2b262006-10-10 01:42:29 +000081 $got = @fwrite($this->outStream_, $buf);
82 if ($got === 0 || $got === FALSE) {
Mark Slee76791962007-03-14 02:47:35 +000083 throw new TException('TPhpStream: Could not write '.strlen($buf).' bytes');
Mark Slee99e2b262006-10-10 01:42:29 +000084 }
85 $buf = substr($buf, $got);
86 }
87 }
88
89 public function flush() {
90 @fflush($this->outStream_);
91 }
92
93}
94
95?>