Completed
Push — master ( 24fba4...970de3 )
by
unknown
04:30
created

MongoFileService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * Minotaur
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
7
 * use this file except in compliance with the License. You may obtain a copy of
8
 * the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
 * License for the specific language governing permissions and limitations under
16
 * the License.
17
 *
18
 * @copyright 2015-2017 Appertly
19
 * @license   Apache-2.0
20
 */
21
namespace Minotaur\Db;
22
23
use MongoDB\BSON\ObjectID;
24
use MongoDB\GridFS\Bucket;
25
use Psr\Http\Message\StreamInterface;
26
use Psr\Http\Message\UploadedFileInterface;
27
28
/**
29
 * File upload service backed by GridFS.
30
 *
31
 * Requires the `mongodb/mongodb` composer package to be installed.
32
 */
33
class MongoFileService implements \Minotaur\Io\FileService
34
{
35
    use MongoHelper;
36
37
    /**
38
     * @var \MongoDB\GridFS\Bucket
39
     */
40
    private $bucket;
41
42
    /**
43
     * Creates a new MongoFileService
44
     *
45
     * @param $bucket - The GridFS Bucket
46
     */
47 2
    public function __construct(Bucket $bucket)
48
    {
49 2
        $this->bucket = $bucket;
50 2
    }
51
52
    /**
53
     * Stores an uploaded file.
54
     *
55
     * You should specify `contentType` in the `metadata` Map.
56
     *
57
     * @param \Psr\Http\Message\UploadedFileInterface $file The uploaded file
58
     * @param array<string,mixed> $metadata Any additional fields to persist. At the very least, try to supply `contentType`.
59
     * @return ObjectID The document ID of the stored file
60
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
61
     * @throws \Caridea\Dao\Exception\Violating If a constraint is violated
62
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
63
     */
64 1
    public function store(UploadedFileInterface $file, array $metadata): ObjectID
65
    {
66
        $meta = [
67 1
            "contentType" => $metadata['contentType'] ?? $file->getClientMediaType(),
68 1
            'metadata' => $metadata
69
        ];
70 1
        return $this->bucket->uploadFromStream(
71 1
            $file->getClientFilename(),
72 1
            $file->getStream()->detach(),
73 1
            $meta
74
        );
75
    }
76
77
    /**
78
     * Gets the file as a PSR-7 Stream.
79
     *
80
     * @param $id - The document identifier, either a string or `ObjectID`
81
     * @return \Psr\Http\Message\StreamInterface The readable stream
82
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
83
     * @throws \Caridea\Dao\Exception\Unretrievable If the document doesn't exist
84
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
85
     */
86
    public function messageStream($id): StreamInterface
87
    {
88
        $file = $this->read($id);
89
        $collectionWrapper = $this->getCollectionWrapper($this->bucket);
90
        return new MongoDownloadStream(
91
            new \MongoDB\GridFS\ReadableStream($collectionWrapper, $file)
0 ignored issues
show
Bug introduced by
It seems like $file defined by $this->read($id) on line 88 can be null; however, MongoDB\GridFS\ReadableStream::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
92
        );
93
    }
94
95
    /**
96
     * Gets a readable stream resource for the given ID.
97
     *
98
     * @param $id - The document identifier, either a string or `ObjectID`
99
     * @return resource The readable stream
100
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
101
     * @throws \Caridea\Dao\Exception\Unretrievable If the document doesn't exist
102
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
103
     */
104
    public function resource($id)
105
    {
106
        return $this->bucket->openDownloadStream($id instanceof ObjectID ? $id : new ObjectID((string) $id));
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\ObjectID does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
107
    }
108
109
    /**
110
     * Efficiently writes the contents of a file to a Stream.
111
     *
112
     * @param \stdClass $file The file
113
     * @param \Psr\Http\Message\StreamInterface $stream The stream
114
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
115
     * @throws \Caridea\Dao\Exception\Violating If a constraint is violated
116
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
117
     */
118
    public function stream($file, StreamInterface $stream): void
119
    {
120
        if (!is_object($file)) {
121
            throw new \InvalidArgumentException("Expected object, got: " . gettype($file));
122
        }
123
        $this->bucket->downloadToStream(
124
            $file->_id,
125
            \Labrys\Io\StreamWrapper::getResource($stream)
126
        );
127
    }
128
129
    /**
130
     * Gets a stored file.
131
     *
132
     * @param mixed $id The document identifier, either a string or `ObjectID`
133
     * @return \stdClass|null The stored file, or `null`
134
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
135
     * @throws \Caridea\Dao\Exception\Unretrievable If the result cannot be retrieved
136
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
137
     */
138 1
    public function read($id): ?\stdClass
139
    {
140 1
        $mid = $this->toId($id);
141 1
        return $this->doExecute(function (Bucket $bucket) use ($mid) {
142 1
            return $this->getCollectionWrapper($bucket)->findFileById($mid);
143 1
        });
144
    }
145
146
    /**
147
     * Deletes a stored file.
148
     *
149
     * @param mixed $id The document identifier, either a string or `ObjectID`
150
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
151
     * @throws \Caridea\Dao\Exception\Unretrievable If the document doesn't exist
152
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
153
     */
154
    public function delete($id): void
155
    {
156
        $mid = $this->toId($id);
157
        $this->doExecute(function (Bucket $bucket) use ($mid) {
158
            $bucket->delete($mid);
159
        });
160
    }
161
162
    /**
163
     * Finds several files by some arbitrary criteria.
164
     *
165
     * @param array<string,mixed> $criteria Field to value pairs
166
     * @return Traversable<\stdClass> The objects found
0 ignored issues
show
Documentation introduced by
The doc-type Traversable<\stdClass> could not be parsed: Expected "|" or "end of type", but got "<" at position 11. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
167
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
168
     * @throws \Caridea\Dao\Exception\Unretrievable If the result cannot be retrieved
169
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
170
     */
171
    public function readAll(array $criteria): \Traversable
172
    {
173
        return $this->doExecute(function (Bucket $bucket) use ($criteria) {
174
            return $bucket->find(
175
                $criteria,
176
                ['sort' => ['filename' => 1]]
177
            );
178
        });
179
    }
180
181
    /**
182
     * Executes something in the context of the collection.
183
     *
184
     * Exceptions are caught and translated.
185
     *
186
     * @param callable $cb The closure to execute, takes the Bucket.
187
     * @return - Whatever the function returns, this method also returns
0 ignored issues
show
Documentation introduced by
The doc-type - could not be parsed: Unknown type name "-" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
188
     * @throws \Caridea\Dao\Exception If a database problem occurs
189
     */
190 1
    protected function doExecute(callable $cb)
191
    {
192
        try {
193 1
            return $cb($this->bucket);
194
        } catch (\Exception $e) {
195
            throw \Caridea\Dao\Exception\Translator\MongoDb::translate($e);
196
        }
197
    }
198
199
    /**
200
     * @return \MongoDB\GridFS\CollectionWrapper
201
     */
202 1
    private function getCollectionWrapper(Bucket $b)
203
    {
204 1
        $p = new \ReflectionProperty(Bucket::class, 'collectionWrapper');
205 1
        $p->setAccessible(true);
206 1
        return $p->getValue($b);
207
    }
208
}
209