Completed
Pull Request — master (#15)
by
unknown
09:46
created

MongoGridFS::insertFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 6
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
    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
46
    /**
47
     * Files as stored across two collections, the first containing file meta
48
     * information, the second containing chunks of the actual file. By default,
49
     * fs.files and fs.chunks are the collection names used.
50
     *
51
     * @link http://php.net/manual/en/mongogridfs.construct.php
52
     * @param MongoDB $db Database
53
     * @param string $prefix [optional] <p>Optional collection name prefix.</p>
54
     * @param mixed $chunks  [optional]
55
     * @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...
56
     */
57
    public function __construct(MongoDB $db, $prefix = "fs", $chunks = null)
58
    {
59
        if ($chunks) {
60
            trigger_error(E_DEPRECATED, "The 'chunks' argument is deprecated and ignored");
61
        }
62
        if (empty($prefix)) {
63
            throw new \InvalidArgumentException('prefix can not be empty');
64
        }
65
66
        $this->database = $db;
67
        $this->filesName = $prefix . '.files';
68
        $this->chunksName = $prefix . '.chunks';
69
70
        $this->chunks = $db->selectCollection($this->chunksName);
71
72
        parent::__construct($db, $this->filesName);
73
    }
74
75
    /**
76
     * Drops the files and chunks collections
77
     * @link http://php.net/manual/en/mongogridfs.drop.php
78
     * @return array The database response
79
     */
80
    public function drop()
81
    {
82
        $this->chunks->drop();
83
        parent::drop();
84
    }
85
86
    /**
87
     * @link http://php.net/manual/en/mongogridfs.find.php
88
     * @param array $query The query
89
     * @param array $fields Fields to return
90
     * @return MongoGridFSCursor A MongoGridFSCursor
91
     */
92 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...
93
    {
94
        $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...
95
        $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...
96
97
        return $cursor;
98
    }
99
100
    /**
101
     * Stores a file in the database
102
     * @link http://php.net/manual/en/mongogridfs.storefile.php
103
     * @param string $filename The name of the file
104
     * @param array $extra Other metadata to add to the file saved
105
     * @param array $options Options for the store. "safe": Check that this store succeeded
106
     * @return mixed Returns the _id of the saved object
107
     */
108
    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...
109
    {
110
        if (is_string($filename)) {
111
            $md5 = md5_file($filename);
112
            $shortName = basename($filename);
113
            $filename = fopen($filename, 'r');
114
        }
115
        if (! is_resource($filename)) {
116
            throw new \InvalidArgumentException();
117
        }
118
        $length = fstat($filename)['size'];
119
        $extra['chunkSize'] = isset($extra['chunkSize']) ? $extra['chunkSize']: self::DEFAULT_CHUNK_SIZE;
120
        $extra['_id'] = isset($extra['_id']) ?: new MongoId();
121
        $extra['length'] = $length;
122
        $extra['md5'] = isset($md5) ? $md5 : $this->calculateMD5($filename, $length);
123
        $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...
124
125
        $fileDocument = $this->insertFile($extra);
126
        $this->insertChunksFromFile($filename, $fileDocument);
127
128
        return $fileDocument['_id'];
129
    }
130
131 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...
132
    {
133
        $length = $fileInfo['length'];
134
        $chunkSize = $fileInfo['chunkSize'];
135
        $fileId = $fileInfo['_id'];
136
        $offset = 0;
137
        $i = 0;
138
139
        while ($offset < $length) {
140
            $data = fread($file, $chunkSize);
141
            $this->insertChunk($fileId, $data, $i++);
142
            $offset += $chunkSize;
143
        }
144
    }
145
146
    private function calculateMD5($file, $length)
147
    {
148
        // XXX: this could be really a bad idea with big files...
149
        $data = fread($file, $length);
150
        fseek($file, 0);
151
        return md5($data);
152
    }
153
154
    /**
155
     * Chunkifies and stores bytes in the database
156
     * @link http://php.net/manual/en/mongogridfs.storebytes.php
157
     * @param string $bytes A string of bytes to store
158
     * @param array $extra Other metadata to add to the file saved
159
     * @param array $options Options for the store. "safe": Check that this store succeeded
160
     * @return mixed The _id of the object saved
161
     */
162
    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...
163
    {
164
        $length = mb_strlen($bytes, '8bit');
165
        $extra['chunkSize'] = isset($extra['chunkSize']) ? $extra['chunkSize'] : self::DEFAULT_CHUNK_SIZE;
166
        $extra['_id'] = isset($extra['_id']) ?: new MongoId();
167
        $extra['length'] = $length;
168
        $extra['md5'] = md5($bytes);
169
170
        $file = $this->insertFile($extra);
171
        $this->insertChunksFromBytes($bytes, $file);
172
173
        return $file['_id'];
174
    }
175
176
    private function insertFile($metadata)
177
    {
178
        $metadata['uploadDate'] = new MongoDate();
179
        $this->insert($metadata);
180
        return $metadata;
181
    }
182
183 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...
184
    {
185
        $length = $fileInfo['length'];
186
        $chunkSize = $fileInfo['chunkSize'];
187
        $fileId = $fileInfo['_id'];
188
        $offset = 0;
189
        $i = 0;
190
191
        while ($offset < $length) {
192
            $data = mb_substr($bytes, $offset, $chunkSize, '8bit');
193
            $this->insertChunk($fileId, $data, $i++);
194
            $offset += $chunkSize;
195
        }
196
    }
197
198
    private function insertChunk($id, $data, $chunkNumber)
199
    {
200
        $chunk = [
201
            'file_id' => $id,
202
            'n' => $chunkNumber,
203
            'data' => new MongoBinData($data),
204
        ];
205
        return $this->chunks->insert($chunk);
206
    }
207
208
209
    /**
210
     * Returns a single file matching the criteria
211
     * @link http://www.php.net/manual/en/mongogridfs.findone.php
212
     * @param array $query The fields for which to search.
213
     * @param array $fields Fields of the results to return.
214
     * @return MongoGridFSFile|null
215
     */
216
    public function findOne(array $query = array(), array $fields = array())
217
    {
218
        $file = parent::findOne($query, $fields);
219
        if (! $file) {
220
            return;
221
        }
222
        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...
223
    }
224
225
    /**
226
     * Removes files from the collections
227
     * @link http://www.php.net/manual/en/mongogridfs.remove.php
228
     * @param array $criteria Description of records to remove.
229
     * @param array $options Options for remove. Valid options are: "safe"- Check that the remove succeeded.
230
     * @throws MongoCursorException
231
     * @return boolean
232
     */
233
    public function remove(array $criteria = [], array $options = [])
234
    {
235
        $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...
236
        $ids = [];
237
        foreach ($matchingFiles as $file) {
238
            $ids[] = $file['_id'];
239
        }
240
        $this->chunks->remove(['file_id' => ['$in' => $ids]], ['justOne' => false]);
241
        return parent::remove($criteria, ['justOne' => false] + $options);
242
    }
243
244
    /**
245
     * Delete a file from the database
246
     * @link http://php.net/manual/en/mongogridfs.delete.php
247
     * @param mixed $id _id of the file to remove
248
     * @return boolean Returns true if the remove was successfully sent to the database.
249
     */
250
    public function delete($id)
251
    {
252
        if (is_string($id)) {
253
            $id = new MongoId($id);
254
        }
255
        if (! $id instanceof MongoId) {
256
            return false;
257
        }
258
        $this->chunks->remove(['file_id' => $id], ['justOne' => false]);
259
        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...
260
    }
261
262
    /**
263
     * Saves an uploaded file directly from a POST to the database
264
     * @link http://www.php.net/manual/en/mongogridfs.storeupload.php
265
     * @param string $name The name attribute of the uploaded file, from <input type="file" name="something"/>.
266
     * @param array $metadata An array of extra fields for the uploaded file.
267
     * @return mixed Returns the _id of the uploaded file.
268
     */
269
    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...
270
    {
271
        if (! isset($_FILES[$name]) || $_FILES[$name]['error'] !== UPLOAD_ERR_OK) {
272
            throw new \InvalidArgumentException();
273
        }
274
        $metadata += ['filename' => $_FILES[$name]['name']];
275
        return $this->storeFile($_FILES[$name]['tmp_name'], $metadata);
276
    }
277
278
    /**
279
     * Retrieve a file from the database
280
     * @link http://www.php.net/manual/en/mongogridfs.get.php
281
     * @param mixed $id _id of the file to find.
282
     * @return MongoGridFSFile|null Returns the file, if found, or NULL.
283
     */
284
    public function __get($id)
285
    {
286
        if (is_string($id)) {
287
            $id = new MongoId($id);
288
        }
289
        if (! $id instanceof MongoId) {
290
            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...
291
        }
292
        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 292 which is incompatible with the return type of the parent method MongoCollection::__get of type MongoCollection.
Loading history...
293
    }
294
295
    /**
296
     * Stores a file in the database
297
     * @link http://php.net/manual/en/mongogridfs.put.php
298
     * @param string $filename The name of the file
299
     * @param array $extra Other metadata to add to the file saved
300
     * @return mixed Returns the _id of the saved object
301
     */
302
    public function put($filename, array $extra = array())
303
    {
304
        return $this->storeFile($filename, $extra);
305
    }
306
307
}
308