Completed
Push — master ( 970de3...679bb4 )
by
unknown
02:05
created

MongoFileService   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 177
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 42%

Importance

Changes 0
Metric Value
dl 0
loc 177
ccs 21
cts 50
cp 0.42
rs 10
c 0
b 0
f 0
wmc 13
lcom 1
cbo 6

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A store() 0 12 1
A messageStream() 0 8 1
A resource() 0 4 2
A stream() 0 10 2
A read() 0 7 1
A delete() 0 7 1
A readAll() 0 10 1
A doExecute() 0 8 2
A getCollectionWrapper() 0 6 1
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\Driver\ReadPreference;
24
use MongoDB\BSON\ObjectID;
25
use MongoDB\GridFS\Bucket;
26
use Psr\Http\Message\StreamInterface;
27
use Psr\Http\Message\UploadedFileInterface;
28
29
/**
30
 * File upload service backed by GridFS.
31
 *
32
 * Requires the `mongodb/mongodb` composer package to be installed.
33
 */
34
class MongoFileService implements \Minotaur\Io\FileService
35
{
36
    use MongoHelper;
37
38
    /**
39
     * @var \MongoDB\GridFS\Bucket
40
     */
41
    private $bucket;
42
43
    /**
44
     * Creates a new MongoFileService
45
     *
46
     * @param $bucket - The GridFS Bucket
47
     */
48 2
    public function __construct(Bucket $bucket)
49
    {
50 2
        $this->bucket = $bucket;
51 2
    }
52
53
    /**
54
     * Stores an uploaded file.
55
     *
56
     * You should specify `contentType` in the `metadata` Map.
57
     *
58
     * @param \Psr\Http\Message\UploadedFileInterface $file The uploaded file
59
     * @param array<string,mixed> $metadata Any additional fields to persist. At the very least, try to supply `contentType`.
60
     * @return ObjectID The document ID of the stored file
61
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
62
     * @throws \Caridea\Dao\Exception\Violating If a constraint is violated
63
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
64
     */
65 1
    public function store(UploadedFileInterface $file, array $metadata): ObjectID
66
    {
67
        $meta = [
68 1
            "contentType" => $metadata['contentType'] ?? $file->getClientMediaType(),
69 1
            'metadata' => $metadata
70
        ];
71 1
        return $this->bucket->uploadFromStream(
72 1
            $file->getClientFilename(),
73 1
            $file->getStream()->detach(),
74 1
            $meta
75
        );
76
    }
77
78
    /**
79
     * Gets the file as a PSR-7 Stream.
80
     *
81
     * @param $id - The document identifier, either a string or `ObjectID`
82
     * @return \Psr\Http\Message\StreamInterface The readable stream
83
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
84
     * @throws \Caridea\Dao\Exception\Unretrievable If the document doesn't exist
85
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
86
     */
87
    public function messageStream($id): StreamInterface
88
    {
89
        $file = $this->read($id);
90
        $collectionWrapper = $this->getCollectionWrapper($this->bucket);
91
        return new MongoDownloadStream(
92
            new \MongoDB\GridFS\ReadableStream($collectionWrapper, $file)
0 ignored issues
show
Bug introduced by
It seems like $file defined by $this->read($id) on line 89 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...
93
        );
94
    }
95
96
    /**
97
     * Gets a readable stream resource for the given ID.
98
     *
99
     * @param $id - The document identifier, either a string or `ObjectID`
100
     * @return resource The readable stream
101
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
102
     * @throws \Caridea\Dao\Exception\Unretrievable If the document doesn't exist
103
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
104
     */
105
    public function resource($id)
106
    {
107
        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...
108
    }
109
110
    /**
111
     * Efficiently writes the contents of a file to a Stream.
112
     *
113
     * @param \stdClass $file The file
114
     * @param \Psr\Http\Message\StreamInterface $stream The stream
115
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
116
     * @throws \Caridea\Dao\Exception\Violating If a constraint is violated
117
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
118
     */
119
    public function stream($file, StreamInterface $stream): void
120
    {
121
        if (!is_object($file)) {
122
            throw new \InvalidArgumentException("Expected object, got: " . gettype($file));
123
        }
124
        $this->bucket->downloadToStream(
125
            $file->_id,
126
            \Labrys\Io\StreamWrapper::getResource($stream)
127
        );
128
    }
129
130
    /**
131
     * Gets a stored file.
132
     *
133
     * @param mixed $id The document identifier, either a string or `ObjectID`
134
     * @return \stdClass|null The stored file, or `null`
135
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
136
     * @throws \Caridea\Dao\Exception\Unretrievable If the result cannot be retrieved
137
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
138
     */
139 1
    public function read($id): ?\stdClass
140
    {
141 1
        $mid = $this->toId($id);
142 1
        return $this->doExecute(function (Bucket $bucket) use ($mid) {
143 1
            return $this->getCollectionWrapper($bucket)->findFileById($mid);
144 1
        });
145
    }
146
147
    /**
148
     * Deletes a stored file.
149
     *
150
     * @param mixed $id The document identifier, either a string or `ObjectID`
151
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
152
     * @throws \Caridea\Dao\Exception\Unretrievable If the document doesn't exist
153
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
154
     */
155
    public function delete($id): void
156
    {
157
        $mid = $this->toId($id);
158
        $this->doExecute(function (Bucket $bucket) use ($mid) {
159
            $bucket->delete($mid);
160
        });
161
    }
162
163
    /**
164
     * Finds several files by some arbitrary criteria.
165
     *
166
     * @param array<string,mixed> $criteria Field to value pairs
167
     * @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...
168
     * @throws \Caridea\Dao\Exception\Unreachable If the connection fails
169
     * @throws \Caridea\Dao\Exception\Unretrievable If the result cannot be retrieved
170
     * @throws \Caridea\Dao\Exception\Generic If any other database problem occurs
171
     */
172
    public function readAll(array $criteria): \Traversable
173
    {
174
        $readPreference = new ReadPreference(ReadPreference::RP_PRIMARY);
0 ignored issues
show
Unused Code introduced by
$readPreference is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
175
        return $this->doExecute(function (Bucket $bucket) use ($criteria) {
176
            return $bucket->find(
177
                $criteria,
178
                ['sort' => ['filename' => 1], 'readPreference' => $readPreference]
0 ignored issues
show
Bug introduced by
The variable $readPreference does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
179
            );
180
        });
181
    }
182
183
    /**
184
     * Executes something in the context of the collection.
185
     *
186
     * Exceptions are caught and translated.
187
     *
188
     * @param callable $cb The closure to execute, takes the Bucket.
189
     * @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...
190
     * @throws \Caridea\Dao\Exception If a database problem occurs
191
     */
192 1
    protected function doExecute(callable $cb)
193
    {
194
        try {
195 1
            return $cb($this->bucket);
196
        } catch (\Exception $e) {
197
            throw \Caridea\Dao\Exception\Translator\MongoDb::translate($e);
198
        }
199
    }
200
201
    /**
202
     * @return \MongoDB\GridFS\CollectionWrapper
203
     */
204 1
    private function getCollectionWrapper(Bucket $b)
205
    {
206 1
        $p = new \ReflectionProperty(Bucket::class, 'collectionWrapper');
207 1
        $p->setAccessible(true);
208 1
        return $p->getValue($b);
209
    }
210
}
211