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 Uploadable 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 Uploadable, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 20 | trait Uploadable |
||
| 21 | { |
||
| 22 | /** @var UploadOptions */ |
||
| 23 | protected $uploadOptions; |
||
| 24 | |||
| 25 | /** |
||
| 26 | * Boot the trait. |
||
| 27 | */ |
||
| 28 | public static function bootUploadable() |
||
| 35 | |||
| 36 | /** |
||
| 37 | * Bind create model events. |
||
| 38 | */ |
||
| 39 | protected static function bindCreateEvents() |
||
| 46 | |||
| 47 | /** |
||
| 48 | * Bind save model events. |
||
| 49 | */ |
||
| 50 | protected static function bindSaveEvents() |
||
| 51 | { |
||
| 52 | static::saved(function (Model $model) { |
||
| 53 | $model->uploadFiles(); |
||
| 54 | }); |
||
| 55 | } |
||
| 56 | |||
| 57 | /** |
||
| 58 | * Bind update model events. |
||
| 59 | */ |
||
| 60 | protected static function bindUpdateEvents() |
||
| 61 | { |
||
| 62 | static::updating(function (Model $model) { |
||
| 63 | //check if there is old files to delete |
||
| 64 | $model->checkIfNeedToDeleteOldFiles(); |
||
| 65 | }); |
||
| 66 | } |
||
| 67 | |||
| 68 | /** |
||
| 69 | * Bind delete model events. |
||
| 70 | */ |
||
| 71 | protected static function bindDeleteEvents() |
||
| 72 | { |
||
| 73 | static::deleting(function (Model $model) { |
||
| 74 | $model->uploadOptions = $model->getUploadOptionsOrDefault(); |
||
| 75 | $model->guardAgainstInvalidUploadOptions(); |
||
| 76 | //check if there is old files to delete |
||
| 77 | $model->checkIfNeedToDeleteOldFiles(); |
||
| 78 | }); |
||
| 79 | |||
| 80 | static::deleted(function (Model $model) { |
||
| 81 | $model->deleteUploadedFiles(); |
||
| 82 | }); |
||
| 83 | } |
||
| 84 | |||
| 85 | /** |
||
| 86 | * Retrive a specifice UploadOptions for this model, or return default UploadOptions |
||
| 87 | * @return UploadOptions |
||
| 88 | */ |
||
| 89 | public function getUploadOptionsOrDefault() : UploadOptions |
||
| 90 | { |
||
| 91 | if ($this->uploadOptions) { |
||
| 92 | return $this->uploadOptions; |
||
| 93 | } |
||
| 94 | |||
| 95 | if (method_exists($this, 'getUploadOptions')) { |
||
| 96 | $method = 'getUploadOptions'; |
||
| 97 | $this->uploadOptions = $this->{$method}(); |
||
| 98 | } else { |
||
| 99 | $this->uploadOptions = UploadOptions::create()->getUploadOptionsDefault() |
||
| 100 | ->setUploadBasePath(public_path('upload/' . $this->getTable())); |
||
|
|
|||
| 101 | } |
||
| 102 | |||
| 103 | return $this->uploadOptions; |
||
| 104 | } |
||
| 105 | |||
| 106 | /** |
||
| 107 | * This function will throw an exception when any of the options is missing or invalid. |
||
| 108 | * @throws InvalidOption |
||
| 109 | */ |
||
| 110 | public function guardAgainstInvalidUploadOptions() |
||
| 111 | { |
||
| 112 | if (!count($this->uploadOptions->uploads)) { |
||
| 113 | throw InvalidOption::missingUploadFields(); |
||
| 114 | } |
||
| 115 | if ($this->uploadOptions->uploadBasePath === null || $this->uploadOptions->uploadBasePath == '') { |
||
| 116 | throw InvalidOption::missingUploadBasePath(); |
||
| 117 | } |
||
| 118 | } |
||
| 119 | |||
| 120 | /** |
||
| 121 | * Handle file upload. |
||
| 122 | */ |
||
| 123 | public function uploadFiles() |
||
| 124 | { |
||
| 125 | //invalid model |
||
| 126 | if ($this->id < 1) { |
||
| 127 | return; |
||
| 128 | } |
||
| 129 | |||
| 130 | //loop for every upload model attributes and do upload if has a file in request |
||
| 131 | foreach ($this->getUploadsAttributesSafe() as $uploadField) { |
||
| 132 | $this->uploadFile($uploadField); |
||
| 133 | } |
||
| 134 | } |
||
| 135 | |||
| 136 | /** |
||
| 137 | * Upload a file releted to a passed attribute name |
||
| 138 | * @param string $uploadField |
||
| 139 | */ |
||
| 140 | public function uploadFile(string $uploadField) |
||
| 141 | { |
||
| 142 | //check if there is a valid file in request for current attribute |
||
| 143 | if (!RequestHelper::isValidCurrentRequestUploadFile($uploadField, |
||
| 144 | $this->getUploadOptionsOrDefault()->uploadsMimeType) |
||
| 145 | ) { |
||
| 146 | return; |
||
| 147 | } |
||
| 148 | |||
| 149 | //retrive the uploaded file |
||
| 150 | $uploadedFile = RequestHelper::getCurrentRequestFileSafe($uploadField); |
||
| 151 | if ($uploadedFile === null) { |
||
| 152 | return; |
||
| 153 | } |
||
| 154 | |||
| 155 | //calcolate new file name and set it to model attribute |
||
| 156 | $this->generateNewUploadFileNameAndSetAttribute($uploadField); |
||
| 157 | |||
| 158 | //do the work |
||
| 159 | $newName = $this->doUpload($uploadedFile, $uploadField); |
||
| 160 | |||
| 161 | //save on db (not call model save because invoke event and entering in loop) |
||
| 162 | $this->updateDb($uploadField, $newName); |
||
| 163 | } |
||
| 164 | |||
| 165 | /** |
||
| 166 | * Get an UploadedFile, generate new name, and save it in destination path. |
||
| 167 | * Return empty string if it fails, otherwise return the saved file name. |
||
| 168 | * @param UploadedFile $uploadedFile |
||
| 169 | * @param string $uploadAttribute |
||
| 170 | * @return string |
||
| 171 | */ |
||
| 172 | public function doUpload(UploadedFile $uploadedFile, $uploadAttribute) : string |
||
| 173 | { |
||
| 174 | if (!$uploadAttribute) { |
||
| 175 | return ''; |
||
| 176 | } |
||
| 177 | |||
| 178 | //get file name by attribute |
||
| 179 | $newName = $this->{$uploadAttribute}; |
||
| 180 | |||
| 181 | //get upload path to store (method create dir if not exists and return '' if it failed) |
||
| 182 | $pathToStore = $this->getUploadFileBasePath($uploadAttribute); |
||
| 183 | |||
| 184 | //delete if file already exists |
||
| 185 | FileHelper::unlinkSafe(DirHelper::njoin($pathToStore, $newName)); |
||
| 186 | |||
| 187 | //move file to destination folder |
||
| 188 | try { |
||
| 189 | $targetFile = $uploadedFile->move($pathToStore, $newName); |
||
| 190 | } catch (\Symfony\Component\HttpFoundation\File\Exception\FileException $e) { |
||
| 191 | $targetFile = null; |
||
| 192 | Log::warning('Error in doUpload() when try to move ' . $newName . ' to folder: ' . $pathToStore . PHP_EOL . $e->getMessage() . PHP_EOL . $e->getTraceAsString()); |
||
| 193 | } |
||
| 194 | |||
| 195 | return $targetFile ? $newName : ''; |
||
| 196 | } |
||
| 197 | |||
| 198 | /** |
||
| 199 | * Check request for valid files and server for correct paths defined in model |
||
| 200 | * @return bool |
||
| 201 | */ |
||
| 202 | public function requestHasValidFilesAndCorrectPaths() : bool |
||
| 216 | |||
| 217 | /** |
||
| 218 | * Generate a new file name for uploaded file. |
||
| 219 | * Return empty string if uploadedFile is null, otherwise return the new file name.. |
||
| 220 | * @param UploadedFile $uploadedFile |
||
| 221 | * @return string |
||
| 222 | * @internal param string $uploadField |
||
| 223 | */ |
||
| 224 | public function generateNewUploadFileName(UploadedFile $uploadedFile) : string |
||
| 225 | { |
||
| 226 | if (!$uploadedFile) { |
||
| 227 | return ''; |
||
| 228 | } |
||
| 229 | if (!$this->id && $this->getUploadOptionsOrDefault()->appendModelIdSuffixInUploadedFileName) { |
||
| 230 | return ''; |
||
| 231 | } |
||
| 232 | |||
| 233 | //check if file need a new name |
||
| 234 | $newName = $this->calcolateNewUploadFileName($uploadedFile); |
||
| 235 | if ($newName != '') { |
||
| 236 | return $newName; |
||
| 237 | } |
||
| 238 | |||
| 239 | //no new file name, return original file name |
||
| 240 | return $uploadedFile->getFilename(); |
||
| 241 | } |
||
| 242 | |||
| 243 | /** |
||
| 244 | * Check if file need a new name and return it, otherwise return empty string. |
||
| 245 | * @param UploadedFile $uploadedFile |
||
| 246 | * @return string |
||
| 247 | */ |
||
| 248 | public function calcolateNewUploadFileName(UploadedFile $uploadedFile) : string |
||
| 261 | |||
| 262 | /** |
||
| 263 | * delete all Uploaded Files |
||
| 264 | */ |
||
| 265 | public function deleteUploadedFiles() |
||
| 272 | |||
| 273 | /** |
||
| 274 | * Delete upload file related to passed attribute name |
||
| 275 | * @param string $uploadField |
||
| 276 | */ |
||
| 277 | public function deleteUploadedFile(string $uploadField) |
||
| 297 | |||
| 298 | /** |
||
| 299 | * Reset model attribute and update db field |
||
| 300 | * @param string $uploadField |
||
| 301 | */ |
||
| 302 | public function setBlanckAttributeAndDB(string $uploadField) |
||
| 314 | |||
| 315 | /** |
||
| 316 | * Return true If All Upload atrributes Are Empty or |
||
| 317 | * if the uploads array is not set. |
||
| 318 | * @return bool |
||
| 319 | */ |
||
| 320 | public function checkIfAllUploadFieldsAreEmpty() : bool |
||
| 331 | |||
| 332 | /** |
||
| 333 | * Check all attributes upload path, and try to create dir if not already exists. |
||
| 334 | * Return false if it fails to create all founded dirs. |
||
| 335 | * @return bool |
||
| 336 | */ |
||
| 337 | public function checkOrCreateAllUploadBasePaths() : bool |
||
| 347 | |||
| 348 | /** |
||
| 349 | * Check uploads property and return a uploads class field |
||
| 350 | * or empty array if somethings wrong. |
||
| 351 | * @return array |
||
| 352 | */ |
||
| 353 | public function getUploadsAttributesSafe() : array |
||
| 361 | |||
| 362 | /** |
||
| 363 | * Check attribute upload path, and try to create dir if not already exists. |
||
| 364 | * Return false if it fails to create the dir. |
||
| 365 | * @param string $uploadField |
||
| 366 | * @return bool |
||
| 367 | */ |
||
| 368 | public function checkOrCreateUploadBasePath(string $uploadField) : bool |
||
| 369 | { |
||
| 370 | $uploadFieldPath = $this->getUploadFileBasePath($uploadField); |
||
| 371 | |||
| 372 | return $uploadFieldPath == '' ? '' : DirHelper::checkDirExistOrCreate($uploadFieldPath, |
||
| 373 | $this->getUploadOptionsOrDefault()->uploadCreateDirModeMask); |
||
| 374 | } |
||
| 375 | |||
| 376 | /** |
||
| 377 | * Return the upload path for the passed attribute and try to create it if not exists. |
||
| 378 | * Returns empty string if dir if not exists and fails to create it. |
||
| 379 | * @param string $uploadField |
||
| 380 | * @return string |
||
| 381 | */ |
||
| 382 | public function getUploadFileBasePath(string $uploadField) : string |
||
| 402 | |||
| 403 | /** |
||
| 404 | * Return the specific upload path (by uploadPaths prop) for the passed attribute if exists, |
||
| 405 | * otherwise return empty string. |
||
| 406 | * If uploadPaths for this field is relative, a public_path was appended. |
||
| 407 | * @param string $uploadField |
||
| 408 | * @return string |
||
| 409 | */ |
||
| 410 | public function getUploadFileBasePathSpecific(string $uploadField) : string |
||
| 411 | { |
||
| 412 | //check if there is a specified upload path |
||
| 427 | |||
| 428 | /** |
||
| 429 | * Return the full (path+filename) upload abs path for the passed attribute. |
||
| 430 | * Returns empty string if dir if not exists. |
||
| 431 | * @param string $uploadField |
||
| 432 | * @return string |
||
| 433 | */ |
||
| 434 | View Code Duplication | public |
|
| 448 | |||
| 449 | /** |
||
| 450 | * Return the full url (base url + filename) for the passed attribute. |
||
| 451 | * Returns empty string if dir if not exists. |
||
| 452 | * Ex.: http://localhost/laravel/public/upload/news/pippo.jpg |
||
| 453 | * @param string $uploadField |
||
| 454 | * @return string |
||
| 455 | */ |
||
| 456 | View Code Duplication | public |
|
| 467 | |||
| 468 | /** |
||
| 469 | * get a path and remove public_path. |
||
| 470 | * @param string $path |
||
| 471 | * @return string |
||
| 472 | */ |
||
| 473 | public |
||
| 488 | |||
| 489 | /** |
||
| 490 | * Return the base url (without filename) for the passed attribute. |
||
| 491 | * Returns empty string if dir if not exists. |
||
| 492 | * Ex.: http://localhost/laravel/public/upload/ |
||
| 493 | * @param string $uploadField |
||
| 494 | * @return string |
||
| 495 | */ |
||
| 496 | View Code Duplication | public |
|
| 511 | |||
| 512 | /** |
||
| 513 | * Calcolate the new name for ALL uploaded files and set relative upload attributes |
||
| 514 | */ |
||
| 515 | public |
||
| 522 | |||
| 523 | /** |
||
| 524 | * Calcolate the new name for uploaded file relative to passed attribute name and set the upload attribute |
||
| 525 | * @param string $uploadField |
||
| 526 | */ |
||
| 527 | public |
||
| 548 | |||
| 549 | /** |
||
| 550 | * @param string $uploadField |
||
| 551 | * @param string $newName |
||
| 552 | */ |
||
| 553 | public |
||
| 565 | |||
| 566 | /** |
||
| 567 | * @param string $path |
||
| 568 | * @return bool |
||
| 569 | */ |
||
| 570 | public |
||
| 577 | |||
| 578 | /** |
||
| 579 | * Check if all uploadedFields are changed, so there is an old value |
||
| 580 | * for attribute and if true try to unlink old file. |
||
| 581 | */ |
||
| 582 | public |
||
| 589 | |||
| 590 | /** |
||
| 591 | * Check if $uploadField are changed, so there is an old value |
||
| 592 | * for $uploadField attribute and if true try to unlink old file. |
||
| 593 | * @param string $uploadField |
||
| 594 | */ |
||
| 595 | public |
||
| 610 | } |
||
| 611 |
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idableprovides a methodequalsIdthat in turn relies on the methodgetId(). If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()as an abstract method to the trait will make sure it is available.