Completed
Pull Request — master (#15)
by
unknown
33:10 queued 19:53
created

MongoGridFS::insertChunksFromFile()   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
    const DEFAULT_CHUNK_SIZE = 262144; // 256 kb
18
19
    const ASCENDING = 1;
20
    const DESCENDING = -1;
21
22
    /**
23
     * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.chunks
24
     * @var $chunks MongoCollection
25
     */
26
    public $chunks;
27
28
    /**
29
     * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.filesname
30
     * @var $filesName string
31
     */
32
    protected $filesName;
33
34
    /**
35
     * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.chunksname
36
     * @var $chunksName string
37
     */
38
    protected $chunksName;
39
40
    /**
41
     * @var MongoDB
42
     */
43
    protected $database;
44
45
    protected $ensureIndexes = false;
46
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, $extra = 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, $length);
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 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...
134
    {
135
        $length = $fileInfo['length'];
136
        $chunkSize = $fileInfo['chunkSize'];
137
        $fileId = $fileInfo['_id'];
138
        $offset = 0;
139
        $i = 0;
140
141
        while ($offset < $length) {
142
            $data = fread($file, $chunkSize);
143
            $this->insertChunk($fileId, $data, $i++);
144
            $offset += $chunkSize;
145
        }
146
    }
147
148
    private function calculateMD5($file, $length)
149
    {
150
        // XXX: this could be really a bad idea with big files...
151
        $data = fread($file, $length);
152
        fseek($file, 0);
153
        return md5($data);
154
    }
155
156
    /**
157
     * Chunkifies and stores bytes in the database
158
     * @link http://php.net/manual/en/mongogridfs.storebytes.php
159
     * @param string $bytes A string of bytes to store
160
     * @param array $extra Other metadata to add to the file saved
161
     * @param array $options Options for the store. "safe": Check that this store succeeded
162
     * @return mixed The _id of the object saved
163
     */
164
    public function storeBytes($bytes, $extra = 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...
165
    {
166
        $length = mb_strlen($bytes, '8bit');
167
        $extra['chunkSize'] = isset($extra['chunkSize']) ? $extra['chunkSize'] : self::DEFAULT_CHUNK_SIZE;
168
        $extra['_id'] = isset($extra['_id']) ?: new MongoId();
169
        $extra['length'] = $length;
170
        $extra['md5'] = md5($bytes);
171
172
        $file = $this->insertFile($extra);
173
        $this->insertChunksFromBytes($bytes, $file);
174
175
        return $file['_id'];
176
    }
177
178
    private function insertFile($metadata)
179
    {
180
        $this->ensureIndexes();
181
        $metadata['uploadDate'] = new MongoDate();
182
        $this->insert($metadata);
183
        return $metadata;
184
    }
185
186 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...
187
    {
188
        $length = $fileInfo['length'];
189
        $chunkSize = $fileInfo['chunkSize'];
190
        $fileId = $fileInfo['_id'];
191
        $offset = 0;
192
        $i = 0;
193
194
        while ($offset < $length) {
195
            $data = mb_substr($bytes, $offset, $chunkSize, '8bit');
196
            $this->insertChunk($fileId, $data, $i++);
197
            $offset += $chunkSize;
198
        }
199
    }
200
201
    private function insertChunk($id, $data, $chunkNumber)
202
    {
203
        $chunk = [
204
            'files_id' => $id,
205
            'n' => $chunkNumber,
206
            'data' => new MongoBinData($data),
207
        ];
208
        return $this->chunks->insert($chunk);
209
    }
210
211
212
    /**
213
     * Returns a single file matching the criteria
214
     * @link http://www.php.net/manual/en/mongogridfs.findone.php
215
     * @param array $query The fields for which to search.
216
     * @param array $fields Fields of the results to return.
217
     * @return MongoGridFSFile|null
218
     */
219
    public function findOne(array $query = array(), array $fields = array())
220
    {
221
        $file = parent::findOne($query, $fields);
222
        if (! $file) {
223
            return;
224
        }
225
        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...
226
    }
227
228
    /**
229
     * Removes files from the collections
230
     * @link http://www.php.net/manual/en/mongogridfs.remove.php
231
     * @param array $criteria Description of records to remove.
232
     * @param array $options Options for remove. Valid options are: "safe"- Check that the remove succeeded.
233
     * @throws MongoCursorException
234
     * @return boolean
235
     */
236
    public function remove(array $criteria = [], array $options = [])
237
    {
238
        $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...
239
        $ids = [];
240
        foreach ($matchingFiles as $file) {
241
            $ids[] = $file['_id'];
242
        }
243
        $this->chunks->remove(['files_id' => ['$in' => $ids]], ['justOne' => false]);
244
        return parent::remove($criteria, ['justOne' => false] + $options);
245
    }
246
247
    /**
248
     * Delete a file from the database
249
     * @link http://php.net/manual/en/mongogridfs.delete.php
250
     * @param mixed $id _id of the file to remove
251
     * @return boolean Returns true if the remove was successfully sent to the database.
252
     */
253
    public function delete($id)
254
    {
255
        if (is_string($id)) {
256
            $id = new MongoId($id);
257
        }
258
        if (! $id instanceof MongoId) {
259
            return false;
260
        }
261
        $this->chunks->remove(['files_id' => $id], ['justOne' => false]);
262
        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...
263
    }
264
265
    /**
266
     * Saves an uploaded file directly from a POST to the database
267
     * @link http://www.php.net/manual/en/mongogridfs.storeupload.php
268
     * @param string $name The name attribute of the uploaded file, from <input type="file" name="something"/>.
269
     * @param array $metadata An array of extra fields for the uploaded file.
270
     * @return mixed Returns the _id of the uploaded file.
271
     */
272
    public function storeUpload($name, array $metadata = [])
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...
273
    {
274
        if (! isset($_FILES[$name]) || $_FILES[$name]['error'] !== UPLOAD_ERR_OK) {
275
            throw new \InvalidArgumentException();
276
        }
277
        $metadata += ['filename' => $_FILES[$name]['name']];
278
        return $this->storeFile($_FILES[$name]['tmp_name'], $metadata);
279
    }
280
281
    /**
282
     * Retrieve a file from the database
283
     * @link http://www.php.net/manual/en/mongogridfs.get.php
284
     * @param mixed $id _id of the file to find.
285
     * @return MongoGridFSFile|null Returns the file, if found, or NULL.
286
     */
287
    public function __get($id)
288
    {
289
        if (is_string($id)) {
290
            $id = new MongoId($id);
291
        }
292
        if (! $id instanceof MongoId) {
293
            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...
294
        }
295
        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 295 which is incompatible with the return type of the parent method MongoCollection::__get of type MongoCollection.
Loading history...
296
    }
297
298
    /**
299
     * Stores a file in the database
300
     * @link http://php.net/manual/en/mongogridfs.put.php
301
     * @param string $filename The name of the file
302
     * @param array $extra Other metadata to add to the file saved
303
     * @return mixed Returns the _id of the saved object
304
     */
305
    public function put($filename, array $extra = array())
306
    {
307
        return $this->storeFile($filename, $extra);
308
    }
309
310
    private function ensureIndexes()
311
    {
312
        if ($this->ensureIndexes) {
313
            return;
314
        }
315
        $this->ensureFilesIndex();
316
        $this->ensureChunksIndex();
317
        $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...
318
    }
319
320
    private function ensureChunksIndex()
321
    {
322
        foreach ($this->chunks->getIndexInfo() as $index) {
323
            if (isset($index['unique']) && $index['unique'] && $index['key'] === ['files_id' => 1, 'n' => 1]) {
324
                return;
325
            }
326
        }
327
        $this->chunks->createIndex(['files_id' => 1, 'n' => 1], ['unique' => true]);
328
    }
329
330
    private function ensureFilesIndex()
331
    {
332
        foreach ($this->getIndexInfo() as $index) {
333
            if ($index['key'] === ['filename' => 1, 'uploadDate' => 1]) {
334
                return;
335
            }
336
        }
337
        $this->createIndex(['filename' => 1, 'uploadDate' => 1]);
338
    }
339
340
}
341