Completed
Pull Request — master (#15)
by
unknown
18:16 queued 06:23
created

MongoGridFS::calculateMD5()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 7
rs 9.4286
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 */
15
16
class MongoGridFS extends MongoCollection
1 ignored issue
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
17
{
18
    const DEFAULT_CHUNK_SIZE = 262144; // 256 kb
19
20
    const ASCENDING = 1;
21
    const DESCENDING = -1;
22
23
    /**
24
     * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.chunks
25
     * @var $chunks MongoCollection
26
     */
27
    public $chunks;
28
29
    /**
30
     * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.filesname
31
     * @var $filesName string
32
     */
33
    protected $filesName;
34
35
    /**
36
     * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.chunksname
37
     * @var $chunksName string
38
     */
39
    protected $chunksName;
40
41
    /**
42
     * @var MongoDB
43
     */
44
    protected $database;
45
46
    protected $ensureIndexes = false;
47
48
    /**
49
     * Files as stored across two collections, the first containing file meta
50
     * information, the second containing chunks of the actual file. By default,
51
     * fs.files and fs.chunks are the collection names used.
52
     *
53
     * @link http://php.net/manual/en/mongogridfs.construct.php
54
     * @param MongoDB $db Database
55
     * @param string $prefix [optional] <p>Optional collection name prefix.</p>
56
     * @param mixed $chunks  [optional]
57
     * @return MongoGridFS
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
58
     */
59
    public function __construct(MongoDB $db, $prefix = "fs", $chunks = null)
60
    {
61
        if ($chunks) {
62
            trigger_error(E_DEPRECATED, "The 'chunks' argument is deprecated and ignored");
63
        }
64
        if (empty($prefix)) {
65
            throw new \InvalidArgumentException('prefix can not be empty');
66
        }
67
68
        $this->database = $db;
69
        $this->filesName = $prefix . '.files';
70
        $this->chunksName = $prefix . '.chunks';
71
72
        $this->chunks = $db->selectCollection($this->chunksName);
73
74
        parent::__construct($db, $this->filesName);
75
    }
76
77
    /**
78
     * Drops the files and chunks collections
79
     * @link http://php.net/manual/en/mongogridfs.drop.php
80
     * @return array The database response
81
     */
82
    public function drop()
83
    {
84
        $this->chunks->drop();
85
        parent::drop();
86
    }
87
88
    /**
89
     * @link http://php.net/manual/en/mongogridfs.find.php
90
     * @param array $query The query
91
     * @param array $fields Fields to return
92
     * @return MongoGridFSCursor A MongoGridFSCursor
93
     */
94 View Code Duplication
    public function find(array $query = array(), array $fields = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
    {
96
        $cursor = new MongoGridFSCursor($this, $this->db->getConnection(), (string)$this, $query, $fields);
0 ignored issues
show
Documentation introduced by
$this->db->getConnection() is of type object<MongoClient>, but the function expects a resource.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
97
        $cursor->setReadPreference($this->getReadPreference());
0 ignored issues
show
Documentation introduced by
$this->getReadPreference() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
98
99
        return $cursor;
100
    }
101
102
    /**
103
     * Stores a file in the database
104
     * @link http://php.net/manual/en/mongogridfs.storefile.php
105
     * @param string $filename The name of the file
106
     * @param array $extra Other metadata to add to the file saved
107
     * @param array $options Options for the store. "safe": Check that this store succeeded
108
     * @return mixed Returns the _id of the saved object
109
     */
110
    public function storeFile($filename, array $extra = array(), array $options = array())
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
111
    {
112
        if (is_string($filename)) {
113
            $md5 = md5_file($filename);
114
            $shortName = basename($filename);
115
            $filename = fopen($filename, 'r');
116
        }
117
        if (! is_resource($filename)) {
118
            throw new \InvalidArgumentException();
119
        }
120
        $length = fstat($filename)['size'];
121
        $extra['chunkSize'] = isset($extra['chunkSize']) ? $extra['chunkSize']: self::DEFAULT_CHUNK_SIZE;
122
        $extra['_id'] = isset($extra['_id']) ?: new MongoId();
123
        $extra['length'] = $length;
124
        $extra['md5'] = isset($md5) ? $md5 : $this->calculateMD5($filename);
125
        $extra['filename'] = isset($extra['filename']) ? $extra['filename'] : $shortName;
0 ignored issues
show
Bug introduced by
The variable $shortName does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
126
127
        $fileDocument = $this->insertFile($extra);
128
        $this->insertChunksFromFile($filename, $fileDocument);
129
130
        return $fileDocument['_id'];
131
    }
132
133
    /**
134
     * Chunkifies and stores bytes in the database
135
     * @link http://php.net/manual/en/mongogridfs.storebytes.php
136
     * @param string $bytes A string of bytes to store
137
     * @param array $extra Other metadata to add to the file saved
138
     * @param array $options Options for the store. "safe": Check that this store succeeded
139
     * @return mixed The _id of the object saved
140
     */
141
    public function storeBytes($bytes, array $extra = array(), array $options = array())
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
142
    {
143
        $length = mb_strlen($bytes, '8bit');
144
        $extra['chunkSize'] = isset($extra['chunkSize']) ? $extra['chunkSize'] : self::DEFAULT_CHUNK_SIZE;
145
        $extra['_id'] = isset($extra['_id']) ?: new MongoId();
146
        $extra['length'] = $length;
147
        $extra['md5'] = md5($bytes);
148
149
        $file = $this->insertFile($extra);
150
        $this->insertChunksFromBytes($bytes, $file);
151
152
        return $file['_id'];
153
    }
154
155
    /**
156
     * Returns a single file matching the criteria
157
     * @link http://www.php.net/manual/en/mongogridfs.findone.php
158
     * @param array $query The fields for which to search.
159
     * @param array $fields Fields of the results to return.
160
     * @return MongoGridFSFile|null
161
     */
162
    public function findOne(array $query = array(), array $fields = array(), array $options = array())
163
    {
164
        $file = parent::findOne($query, $fields);
165
        if (! $file) {
166
            return;
167
        }
168
        return new MongoGridFSFile($this, $file);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \MongoGridFSFile($this, $file); (MongoGridFSFile) is incompatible with the return type of the parent method MongoCollection::findOne of type MongoId|MongoBinData|Mon...ble|string|null|boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
169
    }
170
171
    /**
172
     * Removes files from the collections
173
     * @link http://www.php.net/manual/en/mongogridfs.remove.php
174
     * @param array $criteria Description of records to remove.
175
     * @param array $options Options for remove. Valid options are: "safe"- Check that the remove succeeded.
176
     * @throws MongoCursorException
177
     * @return boolean
178
     */
179
    public function remove(array $criteria = array(), array $options = array())
180
    {
181
        $matchingFiles = parent::find($criteria, ['_id' => 1]);
1 ignored issue
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (find() instead of remove()). Are you sure this is correct? If so, you might want to change this to $this->find().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
182
        $ids = [];
183
        foreach ($matchingFiles as $file) {
184
            $ids[] = $file['_id'];
185
        }
186
        $this->chunks->remove(['files_id' => ['$in' => $ids]], ['justOne' => false]);
187
        return parent::remove($criteria, ['justOne' => false] + $options);
188
    }
189
190
    /**
191
     * Delete a file from the database
192
     * @link http://php.net/manual/en/mongogridfs.delete.php
193
     * @param mixed $id _id of the file to remove
194
     * @return boolean Returns true if the remove was successfully sent to the database.
195
     */
196
    public function delete($id)
197
    {
198
        if (is_string($id)) {
199
            $id = new MongoId($id);
200
        }
201
        if (! $id instanceof MongoId) {
202
            return false;
203
        }
204
        $this->chunks->remove(['files_id' => $id], ['justOne' => false]);
205
        return parent::remove(['_id' => $id]);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (remove() instead of delete()). Are you sure this is correct? If so, you might want to change this to $this->remove().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
206
    }
207
208
    /**
209
     * Saves an uploaded file directly from a POST to the database
210
     * @link http://www.php.net/manual/en/mongogridfs.storeupload.php
211
     * @param string $name The name attribute of the uploaded file, from <input type="file" name="something"/>.
212
     * @param array $metadata An array of extra fields for the uploaded file.
213
     * @return mixed Returns the _id of the uploaded file.
214
     */
215
    public function storeUpload($name, array $metadata = array())
0 ignored issues
show
Coding Style introduced by
storeUpload uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
216
    {
217
        if (! isset($_FILES[$name]) || $_FILES[$name]['error'] !== UPLOAD_ERR_OK) {
218
            throw new \InvalidArgumentException();
219
        }
220
        $metadata += ['filename' => $_FILES[$name]['name']];
221
        return $this->storeFile($_FILES[$name]['tmp_name'], $metadata);
222
    }
223
224
    /**
225
     * Retrieve a file from the database
226
     * @link http://www.php.net/manual/en/mongogridfs.get.php
227
     * @param mixed $id _id of the file to find.
228
     * @return MongoGridFSFile|null Returns the file, if found, or NULL.
229
     */
230
    public function __get($id)
231
    {
232
        if (is_string($id)) {
233
            $id = new MongoId($id);
234
        }
235
        if (! $id instanceof MongoId) {
236
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type of the parent method MongoCollection::__get of type MongoCollection.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
237
        }
238
        return $this->findOne(['_id' => $id]);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->findOne(array('_id' => $id)); of type null|MongoGridFSFile adds the type MongoGridFSFile to the return on line 238 which is incompatible with the return type of the parent method MongoCollection::__get of type MongoCollection.
Loading history...
239
    }
240
241
    /**
242
     * Stores a file in the database
243
     * @link http://php.net/manual/en/mongogridfs.put.php
244
     * @param string $filename The name of the file
245
     * @param array $extra Other metadata to add to the file saved
246
     * @return mixed Returns the _id of the saved object
247
     */
248
    public function put($filename, array $extra = array())
249
    {
250
        return $this->storeFile($filename, $extra);
251
    }
252
253
    private function ensureIndexes()
254
    {
255
        if ($this->ensureIndexes) {
256
            return;
257
        }
258
        $this->ensureFilesIndex();
259
        $this->ensureChunksIndex();
260
        $this->ensuredIndexes = true;
0 ignored issues
show
Bug introduced by
The property ensuredIndexes does not seem to exist. Did you mean ensureIndexes?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
261
    }
262
263
    private function ensureChunksIndex()
264
    {
265
        foreach ($this->chunks->getIndexInfo() as $index) {
266
            if (isset($index['unique']) && $index['unique'] && $index['key'] === ['files_id' => 1, 'n' => 1]) {
267
                return;
268
            }
269
        }
270
        $this->chunks->createIndex(['files_id' => 1, 'n' => 1], ['unique' => true]);
271
    }
272
273
    private function ensureFilesIndex()
274
    {
275
        foreach ($this->getIndexInfo() as $index) {
276
            if ($index['key'] === ['filename' => 1, 'uploadDate' => 1]) {
277
                return;
278
            }
279
        }
280
        $this->createIndex(['filename' => 1, 'uploadDate' => 1]);
281
    }
282
283
    private function insertChunksFromFile($file, $fileInfo)
284
    {
285
        $length = $fileInfo['length'];
286
        $chunkSize = $fileInfo['chunkSize'];
287
        $fileId = $fileInfo['_id'];
288
        $offset = 0;
289
        $i = 0;
290
291
        while ($offset < $length) {
292
            $data = stream_get_contents($file, $chunkSize);
293
            $this->insertChunk($fileId, $data, $i++);
294
            $offset += $chunkSize;
295
        }
296
    }
297
298
    private function calculateMD5($file)
299
    {
300
        // XXX: this could be really a bad idea with big files...
301
        $data = stream_get_contents($file);
302
        rewind($file);
303
        return md5($data);
304
    }
305
306
    private function insertChunksFromBytes($bytes, $fileInfo)
307
    {
308
        $length = $fileInfo['length'];
0 ignored issues
show
Unused Code introduced by
$length 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...
309
        $chunkSize = $fileInfo['chunkSize'];
310
        $fileId = $fileInfo['_id'];
311
        $i = 0;
312
313
        $chunks = str_split($bytes, $chunkSize);
314
        foreach ($chunks as $chunk) {
315
            $this->insertChunk($fileId, $chunk, $i++);
316
        }
317
    }
318
319
    private function insertChunk($id, $data, $chunkNumber)
320
    {
321
        $chunk = [
322
            'files_id' => $id,
323
            'n' => $chunkNumber,
324
            'data' => new MongoBinData($data),
325
        ];
326
        return $this->chunks->insert($chunk);
327
    }
328
329
    private function insertFile($metadata)
330
    {
331
        $this->ensureIndexes();
332
        $metadata['uploadDate'] = new MongoDate();
333
        $this->insert($metadata);
334
        return $metadata;
335
    }
336
337
}
338