ReadableStream.php 8.03 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright 2016-2017 MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
17 18 19

namespace MongoDB\GridFS;

20
use MongoDB\Exception\InvalidArgumentException;
21
use MongoDB\GridFS\Exception\CorruptFileException;
22
use IteratorIterator;
23 24 25
use stdClass;

/**
26
 * ReadableStream abstracts the process of reading a GridFS file.
27 28 29
 *
 * @internal
 */
30
class ReadableStream
31 32
{
    private $buffer;
33
    private $bufferOffset = 0;
34
    private $chunkSize;
35 36
    private $chunkOffset = 0;
    private $chunksIterator;
37
    private $collectionWrapper;
38
    private $expectedLastChunkSize = 0;
39
    private $file;
40
    private $length;
41
    private $numChunks = 0;
42 43

    /**
44
     * Constructs a readable GridFS stream.
45
     *
46
     * @param CollectionWrapper $collectionWrapper GridFS collection wrapper
47
     * @param stdClass          $file              GridFS file document
48
     * @throws CorruptFileException
49
     */
50
    public function __construct(CollectionWrapper $collectionWrapper, stdClass $file)
51
    {
52 53 54 55 56 57 58 59
        if ( ! isset($file->chunkSize) || ! is_integer($file->chunkSize) || $file->chunkSize < 1) {
            throw new CorruptFileException('file.chunkSize is not an integer >= 1');
        }

        if ( ! isset($file->length) || ! is_integer($file->length) || $file->length < 0) {
            throw new CorruptFileException('file.length is not an integer > 0');
        }

60
        if ( ! isset($file->_id) && ! property_exists($file, '_id')) {
61 62 63
            throw new CorruptFileException('file._id does not exist');
        }

64
        $this->file = $file;
65 66
        $this->chunkSize = (integer) $file->chunkSize;
        $this->length = (integer) $file->length;
67

68
        $this->collectionWrapper = $collectionWrapper;
69 70 71 72 73

        if ($this->length > 0) {
            $this->numChunks = (integer) ceil($this->length / $this->chunkSize);
            $this->expectedLastChunkSize = ($this->length - (($this->numChunks - 1) * $this->chunkSize));
        }
74 75
    }

76 77 78 79 80 81 82 83 84 85 86
    /**
     * Return internal properties for debugging purposes.
     *
     * @see http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.debuginfo
     * @return array
     */
    public function __debugInfo()
    {
        return [
            'bucketName' => $this->collectionWrapper->getBucketName(),
            'databaseName' => $this->collectionWrapper->getDatabaseName(),
87
            'file' => $this->file,
88 89 90
        ];
    }

91 92
    public function close()
    {
93
        // Nothing to do
94 95
    }

96
    /**
97
     * Return the stream's file document.
98
     *
99
     * @return stdClass
100
     */
101
    public function getFile()
102
    {
103
        return $this->file;
104 105
    }

106
    /**
107
     * Return the stream's size in bytes.
108 109 110
     *
     * @return integer
     */
111 112
    public function getSize()
    {
113
        return $this->length;
114 115
    }

116
    /**
Jeremy Mikola's avatar
Jeremy Mikola committed
117 118 119 120
     * Return whether the current read position is at the end of the stream.
     *
     * @return boolean
     */
121 122
    public function isEOF()
    {
123 124 125 126 127
        if ($this->chunkOffset === $this->numChunks - 1) {
            return $this->bufferOffset >= $this->expectedLastChunkSize;
        }

        return $this->chunkOffset >= $this->numChunks;
128 129
    }

130 131 132 133 134
    /**
     * 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.
135
     *
136 137 138 139 140
     * @param integer $length Number of bytes to read
     * @return string
     * @throws InvalidArgumentException if $length is negative
     */
    public function readBytes($length)
141
    {
142 143 144
        if ($length < 0) {
            throw new InvalidArgumentException(sprintf('$length must be >= 0; given: %d', $length));
        }
145

146 147 148 149 150 151
        if ($this->chunksIterator === null) {
            $this->initChunksIterator();
        }

        if ($this->buffer === null && ! $this->initBufferFromCurrentChunk()) {
            return '';
152 153
        }

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
        $data = '';

        while (strlen($data) < $length) {
            if ($this->bufferOffset >= strlen($this->buffer) && ! $this->initBufferFromNextChunk()) {
                break;
            }

            $initialDataLength = strlen($data);
            $data .= substr($this->buffer, $this->bufferOffset, $length - $initialDataLength);
            $this->bufferOffset += strlen($data) - $initialDataLength;
        }

        return $data;
    }

169 170 171 172 173 174 175 176 177
    /**
     * Seeks the chunk and buffer offsets for the next read operation.
     *
     * @param integer $offset
     * @throws InvalidArgumentException if $offset is out of range
     */
    public function seek($offset)
    {
        if ($offset < 0 || $offset > $this->file->length) {
178
            throw new InvalidArgumentException(sprintf('$offset must be >= 0 and <= %d; given: %d', $this->file->length, $offset));
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
        }

        /* Compute the offsets for the chunk and buffer (i.e. chunk data) from
         * which we will expect to read after seeking. If the chunk offset
         * changed, we'll also need to reset the buffer.
         */
        $lastChunkOffset = $this->chunkOffset;
        $this->chunkOffset = (integer) floor($offset / $this->chunkSize);
        $this->bufferOffset = $offset % $this->chunkSize;

        if ($lastChunkOffset !== $this->chunkOffset) {
            $this->buffer = null;
            $this->chunksIterator = null;
        }
    }

    /**
     * Return the current position of the stream.
     *
     * This is the offset within the stream where the next byte would be read.
     *
     * @return integer
     */
    public function tell()
    {
        return ($this->chunkOffset * $this->chunkSize) + $this->bufferOffset;
    }

207 208 209 210 211 212 213 214 215 216
    /**
     * Initialize the buffer to the current chunk's data.
     *
     * @return boolean Whether there was a current chunk to read
     * @throws CorruptFileException if an expected chunk could not be read successfully
     */
    private function initBufferFromCurrentChunk()
    {
        if ($this->chunkOffset === 0 && $this->numChunks === 0) {
            return false;
217 218 219
        }

        if ( ! $this->chunksIterator->valid()) {
220
            throw CorruptFileException::missingChunk($this->chunkOffset);
221 222
        }

223 224 225 226
        $currentChunk = $this->chunksIterator->current();

        if ($currentChunk->n !== $this->chunkOffset) {
            throw CorruptFileException::unexpectedIndex($currentChunk->n, $this->chunkOffset);
227 228
        }

229
        $this->buffer = $currentChunk->data->getData();
230

231 232 233 234
        $actualChunkSize = strlen($this->buffer);

        $expectedChunkSize = ($this->chunkOffset === $this->numChunks - 1)
            ? $this->expectedLastChunkSize
235
            : $this->chunkSize;
236

237
        if ($actualChunkSize !== $expectedChunkSize) {
238
            throw CorruptFileException::unexpectedSize($actualChunkSize, $expectedChunkSize);
239 240 241 242
        }

        return true;
    }
243

244 245 246 247 248 249 250
    /**
     * Advance to the next chunk and initialize the buffer to its data.
     *
     * @return boolean Whether there was a next chunk to read
     * @throws CorruptFileException if an expected chunk could not be read successfully
     */
    private function initBufferFromNextChunk()
251
    {
252 253
        if ($this->chunkOffset === $this->numChunks - 1) {
            return false;
254 255
        }

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
        $this->bufferOffset = 0;
        $this->chunkOffset++;
        $this->chunksIterator->next();

        return $this->initBufferFromCurrentChunk();
    }

    /**
     * Initializes the chunk iterator starting from the current offset.
     */
    private function initChunksIterator()
    {
        $cursor = $this->collectionWrapper->findChunksByFileId($this->file->_id, $this->chunkOffset);

        $this->chunksIterator = new IteratorIterator($cursor);
        $this->chunksIterator->rewind();
272
    }
273
}