StreamWrapper.php 5.71 KB
Newer Older
1 2
<?php

3
namespace MongoDB\GridFS;
4

5 6
use Exception;

7 8 9 10
/**
 * Stream wrapper for reading and writing a GridFS file.
 *
 * @internal
11 12
 * @see Bucket::openUploadStream()
 * @see Bucket::openDownloadStream()
13 14 15
 */
class StreamWrapper
{
16 17 18
    /**
     * @var resource|null Stream context (set by PHP)
     */
19 20
    public $context;

21
    private $mode;
22 23
    private $protocol;
    private $stream;
24

25 26 27 28 29 30
    /**
     * Return the stream's file document.
     *
     * @return stdClass
     */
    public function getFile()
31
    {
32
        return $this->stream->getFile();
33 34
    }

35 36
    /**
     * Register the GridFS stream wrapper.
37 38
     *
     * @param string $protocol Protocol to use for stream_wrapper_register()
39
     */
40
    public static function register($protocol = 'gridfs')
41
    {
42 43
        if (in_array($protocol, stream_get_wrappers())) {
            stream_wrapper_unregister($protocol);
44
        }
45

46
        stream_wrapper_register($protocol, get_called_class(), \STREAM_IS_URL);
47
    }
48

49 50 51 52 53
    /**
     * Closes the stream.
     *
     * @see http://php.net/manual/en/streamwrapper.stream-close.php
     */
54 55
    public function stream_close()
    {
56
        $this->stream->close();
57
    }
58

59 60 61 62 63 64
    /**
     * Returns whether the file pointer is at the end of the stream.
     *
     * @see http://php.net/manual/en/streamwrapper.stream-eof.php
     * @return boolean
     */
65
    public function stream_eof()
66
    {
67 68 69 70
        if ( ! $this->stream instanceof ReadableStream) {
            return false;
        }

71
        return $this->stream->isEOF();
72
    }
73

74 75 76 77 78 79 80 81 82
    /**
     * Opens the stream.
     *
     * @see http://php.net/manual/en/streamwrapper.stream-open.php
     * @param string  $path       Path to the file resource
     * @param string  $mode       Mode used to open the file (only "r" and "w" are supported)
     * @param integer $options    Additional flags set by the streams API
     * @param string  $openedPath Not used
     */
83 84 85 86
    public function stream_open($path, $mode, $options, &$openedPath)
    {
        $this->initProtocol($path);
        $this->mode = $mode;
87

88 89 90 91 92 93
        if ($mode === 'r') {
            return $this->initReadableStream();
        }

        if ($mode === 'w') {
            return $this->initWritableStream();
94
        }
95 96

        return false;
97
    }
98

99 100 101 102 103 104 105 106
    /**
     * Read bytes from the stream.
     *
     * Note: this method may return a string smaller than the requested length
     * if data is not available to be read.
     * 
     * @see http://php.net/manual/en/streamwrapper.stream-read.php
     * @param integer $count Number of bytes to read
107
     * @return string
108
     */
109 110
    public function stream_read($count)
    {
111 112 113 114
        if ( ! $this->stream instanceof ReadableStream) {
            return '';
        }

115 116 117 118 119 120
        try {
            return $this->stream->downloadNumBytes($count);
        } catch (Exception $e) {
            trigger_error(sprintf('%s: %s', get_class($e), $e->getMessage()), \E_USER_WARNING);
            return false;
        }
121
    }
122

123 124 125 126 127 128
    /**
     * Return information about the stream.
     *
     * @see http://php.net/manual/en/streamwrapper.stream-stat.php
     * @return array
     */
129 130 131
    public function stream_stat()
    {
        $stat = $this->getStatTemplate();
132 133 134

        $stat[2] = $stat['mode'] = $this->mode;
        $stat[7] = $stat['size'] = $this->stream->getSize();
135 136 137 138

        return $stat;
    }

139 140 141 142 143
    /**
     * Write bytes to the stream.
     *
     * @see http://php.net/manual/en/streamwrapper.stream-write.php
     * @param string $data Data to write
144
     * @return integer The number of bytes written
145
     */
146 147
    public function stream_write($data)
    {
148 149 150
        if ( ! $this->stream instanceof WritableStream) {
            return 0;
        }
151

152 153 154 155 156 157
        try {
            return $this->stream->insertChunks($data);
        } catch (Exception $e) {
            trigger_error(sprintf('%s: %s', get_class($e), $e->getMessage()), \E_USER_WARNING);
            return false;
        }
158
    }
159 160

    /**
161 162
     * Returns a stat template with default values.
     *
163 164
     * @return array
     */
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    private function getStatTemplate()
    {
        return [
            0  => 0,  'dev'     => 0,
            1  => 0,  'ino'     => 0,
            2  => 0,  'mode'    => 0,
            3  => 0,  'nlink'   => 0,
            4  => 0,  'uid'     => 0,
            5  => 0,  'gid'     => 0,
            6  => -1, 'rdev'    => -1,
            7  => 0,  'size'    => 0,
            8  => 0,  'atime'   => 0,
            9  => 0,  'mtime'   => 0,
            10 => 0,  'ctime'   => 0,
            11 => -1, 'blksize' => -1,
            12 => -1, 'blocks'  => -1,
        ];
    }
183

184 185 186 187 188 189
    /**
     * Initialize the protocol from the given path.
     *
     * @see StreamWrapper::stream_open()
     * @param string $path
     */
190 191
    private function initProtocol($path)
    {
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        $parts = explode('://', $path, 2);
        $this->protocol = $parts[0] ?: 'gridfs';
    }

    /**
     * Initialize the internal stream for reading.
     *
     * @see StreamWrapper::stream_open()
     * @return boolean
     */
    private function initReadableStream()
    {
        $context = stream_context_get_options($this->context);

        $this->stream = new ReadableStream(
            $context[$this->protocol]['collectionWrapper'],
            $context[$this->protocol]['file']
        );

        return true;
    }

    /**
     * Initialize the internal stream for writing.
     *
     * @see StreamWrapper::stream_open()
     * @return boolean
     */
    private function initWritableStream()
    {
        $context = stream_context_get_options($this->context);

        $this->stream = new WritableStream(
            $context[$this->protocol]['collectionWrapper'],
            $context[$this->protocol]['filename'],
            $context[$this->protocol]['options']
        );

        return true;
231
    }
232
}