Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like MongoGridFS often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use MongoGridFS, and based on these observations, apply Extract Interface, too.
| 1 | <?php  | 
            ||
| 16 | class MongoGridFS extends MongoCollection  | 
            ||
| 17 | { | 
            ||
| 18 | const ASCENDING = 1;  | 
            ||
| 19 | const DESCENDING = -1;  | 
            ||
| 20 | |||
| 21 | /**  | 
            ||
| 22 | * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.chunks  | 
            ||
| 23 | * @var $chunks MongoCollection  | 
            ||
| 24 | */  | 
            ||
| 25 | public $chunks;  | 
            ||
| 26 | |||
| 27 | /**  | 
            ||
| 28 | * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.filesname  | 
            ||
| 29 | * @var $filesName string  | 
            ||
| 30 | */  | 
            ||
| 31 | protected $filesName;  | 
            ||
| 32 | |||
| 33 | /**  | 
            ||
| 34 | * @link http://php.net/manual/en/class.mongogridfs.php#mongogridfs.props.chunksname  | 
            ||
| 35 | * @var $chunksName string  | 
            ||
| 36 | */  | 
            ||
| 37 | protected $chunksName;  | 
            ||
| 38 | |||
| 39 | /**  | 
            ||
| 40 | * @var MongoDB  | 
            ||
| 41 | */  | 
            ||
| 42 | private $database;  | 
            ||
| 43 | |||
| 44 | private $prefix;  | 
            ||
| 45 | |||
| 46 | private $defaultChunkSize = 261120;  | 
            ||
| 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 | * @throws \Exception  | 
            ||
| 58 | */  | 
            ||
| 59 | public function __construct(MongoDB $db, $prefix = "fs", $chunks = null)  | 
            ||
| 60 |     { | 
            ||
| 61 |         if ($chunks) { | 
            ||
| 62 |             trigger_error("The 'chunks' argument is deprecated and ignored", E_DEPRECATED); | 
            ||
| 63 | }  | 
            ||
| 64 |         if (empty($prefix)) { | 
            ||
| 65 |             throw new \Exception('MongoGridFS::__construct(): invalid prefix'); | 
            ||
| 66 | }  | 
            ||
| 67 | |||
| 68 | $this->database = $db;  | 
            ||
| 69 | $this->prefix = $prefix;  | 
            ||
| 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 | * Delete a file from the database  | 
            ||
| 80 | *  | 
            ||
| 81 | * @link http://php.net/manual/en/mongogridfs.delete.php  | 
            ||
| 82 | * @param mixed $id _id of the file to remove  | 
            ||
| 83 | * @return boolean Returns true if the remove was successfully sent to the database.  | 
            ||
| 84 | */  | 
            ||
| 85 | public function delete($id)  | 
            ||
| 86 |     { | 
            ||
| 87 | $this->createChunksIndex();  | 
            ||
| 88 | |||
| 89 | $this->chunks->remove(['files_id' => $id], ['justOne' => false]);  | 
            ||
| 90 | return parent::remove(['_id' => $id]);  | 
            ||
| 
                                                                                                    
                        
                         | 
                |||
| 91 | }  | 
            ||
| 92 | |||
| 93 | /**  | 
            ||
| 94 | * Drops the files and chunks collections  | 
            ||
| 95 | * @link http://php.net/manual/en/mongogridfs.drop.php  | 
            ||
| 96 | * @return array The database response  | 
            ||
| 97 | */  | 
            ||
| 98 | public function drop()  | 
            ||
| 99 |     { | 
            ||
| 100 | $this->chunks->drop();  | 
            ||
| 101 | return parent::drop();  | 
            ||
| 102 | }  | 
            ||
| 103 | |||
| 104 | /**  | 
            ||
| 105 | * @link http://php.net/manual/en/mongogridfs.find.php  | 
            ||
| 106 | * @param array $query The query  | 
            ||
| 107 | * @param array $fields Fields to return  | 
            ||
| 108 | * @param array $options Options for the find command  | 
            ||
| 109 | * @return MongoGridFSCursor A MongoGridFSCursor  | 
            ||
| 110 | */  | 
            ||
| 111 | View Code Duplication | public function find(array $query = [], array $fields = [])  | 
            |
| 112 |     { | 
            ||
| 113 | $cursor = new MongoGridFSCursor($this, $this->db->getConnection(), (string) $this, $query, $fields);  | 
            ||
| 114 | $cursor->setReadPreference($this->getReadPreference());  | 
            ||
| 115 | |||
| 116 | return $cursor;  | 
            ||
| 117 | }  | 
            ||
| 118 | |||
| 119 | /**  | 
            ||
| 120 | * Returns a single file matching the criteria  | 
            ||
| 121 | *  | 
            ||
| 122 | * @link http://www.php.net/manual/en/mongogridfs.findone.php  | 
            ||
| 123 | * @param array $query The fields for which to search.  | 
            ||
| 124 | * @param array $fields Fields of the results to return.  | 
            ||
| 125 | * @param array $options Options for the find command  | 
            ||
| 126 | * @return MongoGridFSFile|null  | 
            ||
| 127 | */  | 
            ||
| 128 | public function findOne(array $query = [], array $fields = [], array $options = [])  | 
            ||
| 129 |     { | 
            ||
| 130 |         if (is_string($query)) { | 
            ||
| 131 | $query = ['filename' => $query];  | 
            ||
| 132 | }  | 
            ||
| 133 | |||
| 134 | $items = iterator_to_array($this->find($query, $fields)->limit(1));  | 
            ||
| 135 | return count($items) ? current($items) : null;  | 
            ||
| 136 | }  | 
            ||
| 137 | |||
| 138 | /**  | 
            ||
| 139 | * Retrieve a file from the database  | 
            ||
| 140 | *  | 
            ||
| 141 | * @link http://www.php.net/manual/en/mongogridfs.get.php  | 
            ||
| 142 | * @param mixed $id _id of the file to find.  | 
            ||
| 143 | * @return MongoGridFSFile|null  | 
            ||
| 144 | */  | 
            ||
| 145 | public function get($id)  | 
            ||
| 146 |     { | 
            ||
| 147 | return $this->findOne(['_id' => $id]);  | 
            ||
| 148 | }  | 
            ||
| 149 | |||
| 150 | /**  | 
            ||
| 151 | * Stores a file in the database  | 
            ||
| 152 | *  | 
            ||
| 153 | * @link http://php.net/manual/en/mongogridfs.put.php  | 
            ||
| 154 | * @param string $filename The name of the file  | 
            ||
| 155 | * @param array $extra Other metadata to add to the file saved  | 
            ||
| 156 | * @param array $options An array of options for the insert operations executed against the chunks and files collections.  | 
            ||
| 157 | * @return mixed Returns the _id of the saved object  | 
            ||
| 158 | */  | 
            ||
| 159 | public function put($filename, array $extra = [], array $options = [])  | 
            ||
| 160 |     { | 
            ||
| 161 | return $this->storeFile($filename, $extra, $options);  | 
            ||
| 162 | }  | 
            ||
| 163 | |||
| 164 | /**  | 
            ||
| 165 | * Removes files from the collections  | 
            ||
| 166 | *  | 
            ||
| 167 | * @link http://www.php.net/manual/en/mongogridfs.remove.php  | 
            ||
| 168 | * @param array $criteria Description of records to remove.  | 
            ||
| 169 | * @param array $options Options for remove.  | 
            ||
| 170 | * @throws MongoCursorException  | 
            ||
| 171 | * @return boolean  | 
            ||
| 172 | */  | 
            ||
| 173 | public function remove(array $criteria = [], array $options = [])  | 
            ||
| 174 |     { | 
            ||
| 175 | $this->createChunksIndex();  | 
            ||
| 176 | |||
| 177 | $matchingFiles = parent::find($criteria, ['_id' => 1]);  | 
            ||
| 
                                                                                                    
                         1 ignored issue 
                            –
                            show
                         | 
                |||
| 178 | $ids = [];  | 
            ||
| 179 |         foreach ($matchingFiles as $file) { | 
            ||
| 180 | $ids[] = $file['_id'];  | 
            ||
| 181 | }  | 
            ||
| 182 | $this->chunks->remove(['files_id' => ['$in' => $ids]], ['justOne' => false] + $options);  | 
            ||
| 183 | return parent::remove(['_id' => ['$in' => $ids]], ['justOne' => false] + $options);  | 
            ||
| 184 | }  | 
            ||
| 185 | |||
| 186 | /**  | 
            ||
| 187 | * Chunkifies and stores bytes in the database  | 
            ||
| 188 | * @link http://php.net/manual/en/mongogridfs.storebytes.php  | 
            ||
| 189 | * @param string $bytes A string of bytes to store  | 
            ||
| 190 | * @param array $extra Other metadata to add to the file saved  | 
            ||
| 191 | * @param array $options Options for the store. "safe": Check that this store succeeded  | 
            ||
| 192 | * @return mixed The _id of the object saved  | 
            ||
| 193 | */  | 
            ||
| 194 | public function storeBytes($bytes, array $extra = [], array $options = [])  | 
            ||
| 195 |     { | 
            ||
| 196 | $this->createChunksIndex();  | 
            ||
| 197 | |||
| 198 | $record = $extra + [  | 
            ||
| 199 | 'length' => mb_strlen($bytes, '8bit'),  | 
            ||
| 200 | 'md5' => md5($bytes),  | 
            ||
| 201 | ];  | 
            ||
| 202 | |||
| 203 |         try { | 
            ||
| 204 | $file = $this->insertFile($record, $options);  | 
            ||
| 205 |         } catch (MongoException $e) { | 
            ||
| 206 |             throw new MongoGridFSException('Could not store file: '. $e->getMessage(), 0, $e); | 
            ||
| 207 | }  | 
            ||
| 208 | |||
| 209 |         try { | 
            ||
| 210 | $this->insertChunksFromBytes($bytes, $file);  | 
            ||
| 211 |         } catch (MongoException $e) { | 
            ||
| 212 | $this->delete($file['_id']);  | 
            ||
| 213 |             throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), 0, $e); | 
            ||
| 214 | }  | 
            ||
| 215 | |||
| 216 | return $file['_id'];  | 
            ||
| 217 | }  | 
            ||
| 218 | |||
| 219 | /**  | 
            ||
| 220 | * Stores a file in the database  | 
            ||
| 221 | *  | 
            ||
| 222 | * @link http://php.net/manual/en/mongogridfs.storefile.php  | 
            ||
| 223 | * @param string $filename The name of the file  | 
            ||
| 224 | * @param array $extra Other metadata to add to the file saved  | 
            ||
| 225 | * @param array $options Options for the store. "safe": Check that this store succeeded  | 
            ||
| 226 | * @return mixed Returns the _id of the saved object  | 
            ||
| 227 | * @throws MongoGridFSException  | 
            ||
| 228 | * @throws Exception  | 
            ||
| 229 | */  | 
            ||
| 230 | public function storeFile($filename, array $extra = [], array $options = [])  | 
            ||
| 231 |     { | 
            ||
| 232 | $this->createChunksIndex();  | 
            ||
| 233 | |||
| 234 | $record = $extra;  | 
            ||
| 235 |         if (is_string($filename)) { | 
            ||
| 236 | $record += [  | 
            ||
| 237 | 'md5' => md5_file($filename),  | 
            ||
| 238 | 'length' => filesize($filename),  | 
            ||
| 239 | 'filename' => $filename,  | 
            ||
| 240 | ];  | 
            ||
| 241 | |||
| 242 | $handle = fopen($filename, 'r');  | 
            ||
| 243 |             if (! $handle) { | 
            ||
| 244 |                 throw new MongoGridFSException('could not open file: ' . $filename); | 
            ||
| 245 | }  | 
            ||
| 246 |         } elseif (! is_resource($filename)) { | 
            ||
| 247 |             throw new \Exception('first argument must be a string or stream resource'); | 
            ||
| 248 |         } else { | 
            ||
| 249 | $handle = $filename;  | 
            ||
| 250 | }  | 
            ||
| 251 | |||
| 252 | $md5 = null;  | 
            ||
| 253 |         try { | 
            ||
| 254 | $file = $this->insertFile($record, $options);  | 
            ||
| 255 |         } catch (MongoException $e) { | 
            ||
| 256 |             throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), 0, $e); | 
            ||
| 257 | }  | 
            ||
| 258 | |||
| 259 |         try { | 
            ||
| 260 | $length = $this->insertChunksFromFile($handle, $file, $md5);  | 
            ||
| 261 |         } catch (MongoException $e) { | 
            ||
| 262 | $this->delete($file['_id']);  | 
            ||
| 263 |             throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), 0, $e); | 
            ||
| 264 | }  | 
            ||
| 265 | |||
| 266 | |||
| 267 | // Add length and MD5 if they were not present before  | 
            ||
| 268 | $update = [];  | 
            ||
| 269 |         if (! isset($record['length'])) { | 
            ||
| 270 | $update['length'] = $length;  | 
            ||
| 271 | }  | 
            ||
| 272 |         if (! isset($record['md5'])) { | 
            ||
| 273 |             try { | 
            ||
| 274 | $update['md5'] = $md5;  | 
            ||
| 275 |             } catch (MongoException $e) { | 
            ||
| 276 |                 throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), 0, $e); | 
            ||
| 277 | }  | 
            ||
| 278 | }  | 
            ||
| 279 | |||
| 280 |         if (count($update)) { | 
            ||
| 281 |             try { | 
            ||
| 282 | $result = $this->update(['_id' => $file['_id']], ['$set' => $update]);  | 
            ||
| 283 |                 if (! $this->isOKResult($result)) { | 
            ||
| 284 |                     throw new MongoGridFSException('Could not store file'); | 
            ||
| 285 | }  | 
            ||
| 286 |             } catch (MongoException $e) { | 
            ||
| 287 | $this->delete($file['_id']);  | 
            ||
| 288 |                 throw new MongoGridFSException('Could not store file: ' . $e->getMessage(), 0, $e); | 
            ||
| 289 | }  | 
            ||
| 290 | |||
| 291 | }  | 
            ||
| 292 | |||
| 293 | return $file['_id'];  | 
            ||
| 294 | }  | 
            ||
| 295 | |||
| 296 | /**  | 
            ||
| 297 | * Saves an uploaded file directly from a POST to the database  | 
            ||
| 298 | *  | 
            ||
| 299 | * @link http://www.php.net/manual/en/mongogridfs.storeupload.php  | 
            ||
| 300 | * @param string $name The name attribute of the uploaded file, from <input type="file" name="something"/>.  | 
            ||
| 301 | * @param array $metadata An array of extra fields for the uploaded file.  | 
            ||
| 302 | * @return mixed Returns the _id of the uploaded file.  | 
            ||
| 303 | * @throws MongoGridFSException  | 
            ||
| 304 | */  | 
            ||
| 305 | public function storeUpload($name, array $metadata = [])  | 
            ||
| 330 | |||
| 331 | /**  | 
            ||
| 332 | * Creates the index on the chunks collection  | 
            ||
| 333 | */  | 
            ||
| 334 | private function createChunksIndex()  | 
            ||
| 341 | |||
| 342 | /**  | 
            ||
| 343 | * Inserts a single chunk into the database  | 
            ||
| 344 | *  | 
            ||
| 345 | * @param mixed $fileId  | 
            ||
| 346 | * @param string $data  | 
            ||
| 347 | * @param int $chunkNumber  | 
            ||
| 348 | * @return array|bool  | 
            ||
| 349 | */  | 
            ||
| 350 | private function insertChunk($fileId, $data, $chunkNumber)  | 
            ||
| 366 | |||
| 367 | /**  | 
            ||
| 368 | * Splits a string into chunks and writes them to the database  | 
            ||
| 369 | *  | 
            ||
| 370 | * @param string $bytes  | 
            ||
| 371 | * @param array $record  | 
            ||
| 372 | */  | 
            ||
| 373 | private function insertChunksFromBytes($bytes, $record)  | 
            ||
| 384 | |||
| 385 | /**  | 
            ||
| 386 | * Reads chunks from a file and writes them to the database  | 
            ||
| 387 | *  | 
            ||
| 388 | * @param resource $handle  | 
            ||
| 389 | * @param array $record  | 
            ||
| 390 | * @param string $md5  | 
            ||
| 391 | * @return int Returns the number of bytes written to the database  | 
            ||
| 392 | */  | 
            ||
| 393 | private function insertChunksFromFile($handle, $record, &$md5)  | 
            ||
| 417 | |||
| 418 | /**  | 
            ||
| 419 | * Writes a file record to the database  | 
            ||
| 420 | *  | 
            ||
| 421 | * @param $record  | 
            ||
| 422 | * @param array $options  | 
            ||
| 423 | * @return array  | 
            ||
| 424 | */  | 
            ||
| 425 | private function insertFile($record, array $options = [])  | 
            ||
| 441 | |||
| 442 | private function isOKResult($result)  | 
            ||
| 447 | |||
| 448 | /**  | 
            ||
| 449 | * @return array  | 
            ||
| 450 | */  | 
            ||
| 451 | public function __sleep()  | 
            ||
| 455 | }  | 
            ||
| 456 | 
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:
The
getFirstName()method in theSoncalls the wrong method in the parent class.