Completed
Pull Request — master (#15)
by
unknown
14:43
created

MongoGridFS::insertChunksFromBytes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 14
Ratio 100 %
Metric Value
dl 14
loc 14
rs 9.4286
cc 2
eloc 10
nc 2
nop 2
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
    /**
50
     * Files as stored across two collections, the first containing file meta
51
     * information, the second containing chunks of the actual file. By default,
52
     * fs.files and fs.chunks are the collection names used.
53
     *
54
     * @link http://php.net/manual/en/mongogridfs.construct.php
55
     * @param MongoDB $db Database
56
     * @param string $prefix [optional] <p>Optional collection name prefix.</p>
57
     * @param mixed $chunks  [optional]
58
     * @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...
59
     */
60
    public function __construct(MongoDB $db, $prefix = "fs", $chunks = null)
61
    {
62
        if ($chunks) {
63
            trigger_error(E_DEPRECATED, "The 'chunks' argument is deprecated and ignored");
64
        }
65
        if (empty($prefix)) {
66
            throw new \InvalidArgumentException('prefix can not be empty');
67
        }
68
69
        $this->database = $db;
70
        $this->filesName = $prefix . '.files';
71
        $this->chunksName = $prefix . '.chunks';
72
73
        $this->chunks = $db->selectCollection($this->chunksName);
74
75
        parent::__construct($db, $this->filesName);
76
    }
77
78
    /**
79
     * Drops the files and chunks collections
80
     * @link http://php.net/manual/en/mongogridfs.drop.php
81
     * @return array The database response
82
     */
83
    public function drop()
84
    {
85
        $this->chunks->drop();
86
        parent::drop();
87
    }
88
89
    /**
90
     * @link http://php.net/manual/en/mongogridfs.find.php
91
     * @param array $query The query
92
     * @param array $fields Fields to return
93
     * @return MongoGridFSCursor A MongoGridFSCursor
94
     */
95 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...
96
    {
97
        $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...
98
        $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...
99
100
        return $cursor;
101
    }
102
103
    /**
104
     * Stores a file in the database
105
     * @link http://php.net/manual/en/mongogridfs.storefile.php
106
     * @param string $filename The name of the file
107
     * @param array $extra Other metadata to add to the file saved
108
     * @param array $options Options for the store. "safe": Check that this store succeeded
109
     * @return mixed Returns the _id of the saved object
110
     */
111
    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...
112
    {
113
        if (is_string($filename)) {
114
            $md5 = md5_file($filename);
115
            $shortName = basename($filename);
116
            $filename = fopen($filename, 'r');
117
        }
118
        if (! is_resource($filename)) {
119
            throw new \InvalidArgumentException();
120
        }
121
        $length = fstat($filename)['size'];
122
        $extra['chunkSize'] = isset($extra['chunkSize']) ? $extra['chunkSize']: self::DEFAULT_CHUNK_SIZE;
123
        $extra['_id'] = isset($extra['_id']) ?: new MongoId();
124
        $extra['length'] = $length;
125
        $extra['md5'] = isset($md5) ? $md5 : $this->calculateMD5($filename, $length);
126
        $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...
127
128
        $fileDocument = $this->insertFile($extra);
129
        $this->insertChunksFromFile($filename, $fileDocument);
130
131
        return $fileDocument['_id'];
132
    }
133
134
    /**
135
     * Chunkifies and stores bytes in the database
136
     * @link http://php.net/manual/en/mongogridfs.storebytes.php
137
     * @param string $bytes A string of bytes to store
138
     * @param array $extra Other metadata to add to the file saved
139
     * @param array $options Options for the store. "safe": Check that this store succeeded
140
     * @return mixed The _id of the object saved
141
     */
142
    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...
143
    {
144
        $length = mb_strlen($bytes, '8bit');
145
        $extra['chunkSize'] = isset($extra['chunkSize']) ? $extra['chunkSize'] : self::DEFAULT_CHUNK_SIZE;
146
        $extra['_id'] = isset($extra['_id']) ?: new MongoId();
147
        $extra['length'] = $length;
148
        $extra['md5'] = md5($bytes);
149
150
        $file = $this->insertFile($extra);
151
        $this->insertChunksFromBytes($bytes, $file);
152
153
        return $file['_id'];
154
    }
155
156
157
158
    /**
159
     * Returns a single file matching the criteria
160
     * @link http://www.php.net/manual/en/mongogridfs.findone.php
161
     * @param array $query The fields for which to search.
162
     * @param array $fields Fields of the results to return.
163
     * @return MongoGridFSFile|null
164
     */
165
    public function findOne(array $query = array(), array $fields = array())
166
    {
167
        $file = parent::findOne($query, $fields);
168
        if (! $file) {
169
            return;
170
        }
171
        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 array|null.

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...
172
    }
173
174
    /**
175
     * Removes files from the collections
176
     * @link http://www.php.net/manual/en/mongogridfs.remove.php
177
     * @param array $criteria Description of records to remove.
178
     * @param array $options Options for remove. Valid options are: "safe"- Check that the remove succeeded.
179
     * @throws MongoCursorException
180
     * @return boolean
181
     */
182
    public function remove(array $criteria = array(), array $options = array())
183
    {
184
        $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...
185
        $ids = [];
186
        foreach ($matchingFiles as $file) {
187
            $ids[] = $file['_id'];
188
        }
189
        $this->chunks->remove(['files_id' => ['$in' => $ids]], ['justOne' => false]);
190
        return parent::remove($criteria, ['justOne' => false] + $options);
191
    }
192
193
    /**
194
     * Delete a file from the database
195
     * @link http://php.net/manual/en/mongogridfs.delete.php
196
     * @param mixed $id _id of the file to remove
197
     * @return boolean Returns true if the remove was successfully sent to the database.
198
     */
199
    public function delete($id)
200
    {
201
        if (is_string($id)) {
202
            $id = new MongoId($id);
203
        }
204
        if (! $id instanceof MongoId) {
205
            return false;
206
        }
207
        $this->chunks->remove(['files_id' => $id], ['justOne' => false]);
208
        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...
209
    }
210
211
    /**
212
     * Saves an uploaded file directly from a POST to the database
213
     * @link http://www.php.net/manual/en/mongogridfs.storeupload.php
214
     * @param string $name The name attribute of the uploaded file, from <input type="file" name="something"/>.
215
     * @param array $metadata An array of extra fields for the uploaded file.
216
     * @return mixed Returns the _id of the uploaded file.
217
     */
218
    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...
219
    {
220
        if (! isset($_FILES[$name]) || $_FILES[$name]['error'] !== UPLOAD_ERR_OK) {
221
            throw new \InvalidArgumentException();
222
        }
223
        $metadata += ['filename' => $_FILES[$name]['name']];
224
        return $this->storeFile($_FILES[$name]['tmp_name'], $metadata);
225
    }
226
227
    /**
228
     * Retrieve a file from the database
229
     * @link http://www.php.net/manual/en/mongogridfs.get.php
230
     * @param mixed $id _id of the file to find.
231
     * @return MongoGridFSFile|null Returns the file, if found, or NULL.
232
     */
233
    public function __get($id)
234
    {
235
        if (is_string($id)) {
236
            $id = new MongoId($id);
237
        }
238
        if (! $id instanceof MongoId) {
239
            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...
240
        }
241
        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 241 which is incompatible with the return type of the parent method MongoCollection::__get of type MongoCollection.
Loading history...
242
    }
243
244
    /**
245
     * Stores a file in the database
246
     * @link http://php.net/manual/en/mongogridfs.put.php
247
     * @param string $filename The name of the file
248
     * @param array $extra Other metadata to add to the file saved
249
     * @return mixed Returns the _id of the saved object
250
     */
251
    public function put($filename, array $extra = array())
252
    {
253
        return $this->storeFile($filename, $extra);
254
    }
255
256
    private function ensureIndexes()
257
    {
258
        if ($this->ensureIndexes) {
259
            return;
260
        }
261
        $this->ensureFilesIndex();
262
        $this->ensureChunksIndex();
263
        $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...
264
    }
265
266
    private function ensureChunksIndex()
267
    {
268
        foreach ($this->chunks->getIndexInfo() as $index) {
269
            if (isset($index['unique']) && $index['unique'] && $index['key'] === ['files_id' => 1, 'n' => 1]) {
270
                return;
271
            }
272
        }
273
        $this->chunks->createIndex(['files_id' => 1, 'n' => 1], ['unique' => true]);
274
    }
275
276
    private function ensureFilesIndex()
277
    {
278
        foreach ($this->getIndexInfo() as $index) {
279
            if ($index['key'] === ['filename' => 1, 'uploadDate' => 1]) {
280
                return;
281
            }
282
        }
283
        $this->createIndex(['filename' => 1, 'uploadDate' => 1]);
284
    }
285
286 View Code Duplication
    private function insertChunksFromFile($file, $fileInfo)
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...
287
    {
288
        $length = $fileInfo['length'];
289
        $chunkSize = $fileInfo['chunkSize'];
290
        $fileId = $fileInfo['_id'];
291
        $offset = 0;
292
        $i = 0;
293
294
        while ($offset < $length) {
295
            $data = fread($file, $chunkSize);
296
            $this->insertChunk($fileId, $data, $i++);
297
            $offset += $chunkSize;
298
        }
299
    }
300
301
    private function calculateMD5($file, $length)
302
    {
303
        // XXX: this could be really a bad idea with big files...
304
        $data = fread($file, $length);
305
        fseek($file, 0);
306
        return md5($data);
307
    }
308
309 View Code Duplication
    private function insertChunksFromBytes($bytes, $fileInfo)
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...
310
    {
311
        $length = $fileInfo['length'];
312
        $chunkSize = $fileInfo['chunkSize'];
313
        $fileId = $fileInfo['_id'];
314
        $offset = 0;
315
        $i = 0;
316
317
        while ($offset < $length) {
318
            $data = mb_substr($bytes, $offset, $chunkSize, '8bit');
319
            $this->insertChunk($fileId, $data, $i++);
320
            $offset += $chunkSize;
321
        }
322
    }
323
324
    private function insertChunk($id, $data, $chunkNumber)
325
    {
326
        $chunk = [
327
            'files_id' => $id,
328
            'n' => $chunkNumber,
329
            'data' => new MongoBinData($data),
330
        ];
331
        return $this->chunks->insert($chunk);
332
    }
333
334
    private function insertFile($metadata)
335
    {
336
        $this->ensureIndexes();
337
        $metadata['uploadDate'] = new MongoDate();
338
        $this->insert($metadata);
339
        return $metadata;
340
    }
341
342
}
343