CollectionWrapper.php 9 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 20
namespace MongoDB\GridFS;

use MongoDB\Collection;
21 22
use MongoDB\UpdateResult;
use MongoDB\Driver\Cursor;
23
use MongoDB\Driver\Manager;
24
use MongoDB\Driver\ReadPreference;
25
use stdClass;
26

27
/**
28
 * CollectionWrapper abstracts the GridFS files and chunks collections.
29
 *
30
 * @internal
31
 */
32
class CollectionWrapper
33
{
34
    private $bucketName;
35
    private $chunksCollection;
36
    private $databaseName;
37
    private $checkedIndexes = false;
38 39
    private $filesCollection;

40
    /**
41
     * Constructs a GridFS collection wrapper.
42
     *
43 44 45 46 47
     * @see Collection::__construct() for supported options
     * @param Manager $manager           Manager instance from the driver
     * @param string  $databaseName      Database name
     * @param string  $bucketName        Bucket name
     * @param array   $collectionOptions Collection options
48 49
     * @throws InvalidArgumentException
     */
50
    public function __construct(Manager $manager, $databaseName, $bucketName, array $collectionOptions = [])
51
    {
52 53 54
        $this->databaseName = (string) $databaseName;
        $this->bucketName = (string) $bucketName;

55 56
        $this->filesCollection = new Collection($manager, $databaseName, sprintf('%s.files', $bucketName), $collectionOptions);
        $this->chunksCollection = new Collection($manager, $databaseName, sprintf('%s.chunks', $bucketName), $collectionOptions);
57 58
    }

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    /**
     * Deletes all GridFS chunks for a given file ID.
     *
     * @param mixed $id
     */
    public function deleteChunksByFilesId($id)
    {
        $this->chunksCollection->deleteMany(['files_id' => $id]);
    }

    /**
     * Deletes a GridFS file and related chunks by ID.
     *
     * @param mixed $id
     */
    public function deleteFileAndChunksById($id)
    {
        $this->filesCollection->deleteOne(['_id' => $id]);
        $this->chunksCollection->deleteMany(['files_id' => $id]);
    }

    /**
     * Drops the GridFS files and chunks collections.
     */
83 84
    public function dropCollections()
    {
85 86
        $this->filesCollection->drop(['typeMap' => []]);
        $this->chunksCollection->drop(['typeMap' => []]);
87 88
    }

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    /**
     * Finds GridFS chunk documents for a given file ID and optional offset.
     *
     * @param mixed   $id        File ID
     * @param integer $fromChunk Starting chunk (inclusive)
     * @return Cursor
     */
    public function findChunksByFileId($id, $fromChunk = 0)
    {
        return $this->chunksCollection->find(
            [
                'files_id' => $id,
                'n' => ['$gte' => $fromChunk],
            ],
            [
                'sort' => ['n' => 1],
                'typeMap' => ['root' => 'stdClass'],
            ]
        );
    }

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    /**
     * Finds a GridFS file document for a given filename and revision.
     *
     * Revision numbers are defined as follows:
     *
     *  * 0 = the original stored file
     *  * 1 = the first revision
     *  * 2 = the second revision
     *  * etc…
     *  * -2 = the second most recent revision
     *  * -1 = the most recent revision
     *
     * @see Bucket::downloadToStreamByName()
     * @see Bucket::openDownloadStreamByName()
     * @param string $filename
     * @param integer $revision
     * @return stdClass|null
     */
    public function findFileByFilenameAndRevision($filename, $revision)
    {
        $filename = (string) $filename;
        $revision = (integer) $revision;

        if ($revision < 0) {
            $skip = abs($revision) - 1;
            $sortOrder = -1;
        } else {
            $skip = $revision;
            $sortOrder = 1;
        }

        return $this->filesCollection->findOne(
            ['filename' => $filename],
            [
                'skip' => $skip,
                'sort' => ['uploadDate' => $sortOrder],
                'typeMap' => ['root' => 'stdClass'],
            ]
        );
    }

    /**
     * Finds a GridFS file document for a given ID.
     *
     * @param mixed $id
     * @return stdClass|null
     */
    public function findFileById($id)
    {
        return $this->filesCollection->findOne(
            ['_id' => $id],
            ['typeMap' => ['root' => 'stdClass']]
        );
    }

    /**
     * Finds documents from the GridFS bucket's files collection.
     *
     * @see Find::__construct() for supported options
     * @param array|object $filter  Query by which to filter documents
     * @param array        $options Additional options
     * @return Cursor
     */
    public function findFiles($filter, array $options = [])
    {
        return $this->filesCollection->find($filter, $options);
    }

178 179 180 181 182 183 184 185 186 187 188 189
    /**
     * Finds a single document from the GridFS bucket's files collection.
     *
     * @param array|object $filter  Query by which to filter documents
     * @param array        $options Additional options
     * @return array|object|null
     */
    public function findOneFile($filter, array $options = [])
    {
        return $this->filesCollection->findOne($filter, $options);
    }

190 191 192 193 194 195
    /**
     * Return the bucket name.
     *
     * @return string
     */
    public function getBucketName()
196
    {
197
        return $this->bucketName;
198
    }
199

200 201 202 203 204 205 206 207 208 209
    /**
     * Return the chunks collection.
     *
     * @return Collection
     */
    public function getChunksCollection()
    {
        return $this->chunksCollection;
    }

210 211 212 213 214 215
    /**
     * Return the database name.
     *
     * @return string
     */
    public function getDatabaseName()
216
    {
217
        return $this->databaseName;
218 219
    }

220 221 222 223 224 225 226 227 228 229
    /**
     * Return the files collection.
     *
     * @return Collection
     */
    public function getFilesCollection()
    {
        return $this->filesCollection;
    }

230 231 232 233 234
    /**
     * Inserts a document into the chunks collection.
     *
     * @param array|object $chunk Chunk document
     */
235 236
    public function insertChunk($chunk)
    {
237 238 239 240
        if ( ! $this->checkedIndexes) {
            $this->ensureIndexes();
        }

241 242
        $this->chunksCollection->insertOne($chunk);
    }
243

244 245 246 247 248 249 250
    /**
     * Inserts a document into the files collection.
     *
     * The file document should be inserted after all chunks have been inserted.
     *
     * @param array|object $file File document
     */
251
    public function insertFile($file)
252
    {
253 254 255 256
        if ( ! $this->checkedIndexes) {
            $this->ensureIndexes();
        }

257
        $this->filesCollection->insertOne($file);
258
    }
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    /**
     * Updates the filename field in the file document for a given ID.
     *
     * @param mixed  $id
     * @param string $filename 
     * @return UpdateResult
     */
    public function updateFilenameForId($id, $filename)
    {
        return $this->filesCollection->updateOne(
            ['_id' => $id],
            ['$set' => ['filename' => (string) $filename]]
        );
    }

    /**
     * Create an index on the chunks collection if it does not already exist.
     */
278 279 280 281 282 283 284
    private function ensureChunksIndex()
    {
        foreach ($this->chunksCollection->listIndexes() as $index) {
            if ($index->isUnique() && $index->getKey() === ['files_id' => 1, 'n' => 1]) {
                return;
            }
        }
285

286 287
        $this->chunksCollection->createIndex(['files_id' => 1, 'n' => 1], ['unique' => true]);
    }
288

289 290 291
    /**
     * Create an index on the files collection if it does not already exist.
     */
292 293 294 295 296 297 298
    private function ensureFilesIndex()
    {
        foreach ($this->filesCollection->listIndexes() as $index) {
            if ($index->getKey() === ['filename' => 1, 'uploadDate' => 1]) {
                return;
            }
        }
299

300 301
        $this->filesCollection->createIndex(['filename' => 1, 'uploadDate' => 1]);
    }
302

303 304 305 306 307 308
    /**
     * Ensure indexes on the files and chunks collections exist.
     *
     * This method is called once before the first write operation on a GridFS
     * bucket. Indexes are only be created if the files collection is empty.
     */
309 310
    private function ensureIndexes()
    {
311
        if ($this->checkedIndexes) {
312 313 314
            return;
        }

315 316
        $this->checkedIndexes = true;

317 318 319 320 321 322 323 324
        if ( ! $this->isFilesCollectionEmpty()) {
            return;
        }

        $this->ensureFilesIndex();
        $this->ensureChunksIndex();
    }

325 326 327 328 329
    /**
     * Returns whether the files collection is empty.
     *
     * @return boolean
     */
330 331 332 333 334
    private function isFilesCollectionEmpty()
    {
        return null === $this->filesCollection->findOne([], [
            'readPreference' => new ReadPreference(ReadPreference::RP_PRIMARY),
            'projection' => ['_id' => 1],
335
            'typeMap' => [],
336 337 338
        ]);
    }
}