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 DocxMustache 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 DocxMustache, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 9 | class DocxMustache |
||
| 10 | { |
||
| 11 | public $items; |
||
| 12 | public $word_doc; |
||
| 13 | public $template_file_name; |
||
| 14 | public $template_file; |
||
| 15 | public $local_path; |
||
| 16 | public $storageDisk; |
||
| 17 | public $storagePathPrefix; |
||
| 18 | public $zipper; |
||
| 19 | public $imageManipulation; |
||
| 20 | public $verbose; |
||
| 21 | |||
| 22 | public function __construct($items, $local_template_file) |
||
| 23 | { |
||
| 24 | $this->items = $items; |
||
| 25 | $this->template_file_name = basename($local_template_file); |
||
| 26 | $this->template_file = $local_template_file; |
||
| 27 | $this->word_doc = false; |
||
| 28 | $this->zipper = new \Chumper\Zipper\Zipper(); |
||
| 29 | |||
| 30 | //name of disk for storage |
||
| 31 | $this->storageDisk = 'local'; |
||
| 32 | |||
| 33 | //prefix within your storage path |
||
| 34 | $this->storagePathPrefix = 'app/'; |
||
| 35 | |||
| 36 | //if you use img urls that support manipulation via parameter |
||
| 37 | $this->imageManipulation = ''; //'&w=1800'; |
||
| 38 | |||
| 39 | $this->verbose = false; |
||
| 40 | } |
||
| 41 | |||
| 42 | public function Execute() |
||
| 43 | { |
||
| 44 | $this->CopyTmplate(); |
||
| 45 | $this->ReadTeamplate(); |
||
| 46 | } |
||
| 47 | |||
| 48 | /** |
||
| 49 | * @param string $file |
||
| 50 | */ |
||
| 51 | public function StoragePath($file) |
||
| 52 | { |
||
| 53 | return storage_path($file); |
||
| 54 | } |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @param string $msg |
||
| 58 | */ |
||
| 59 | protected function Log($msg) |
||
| 60 | { |
||
| 61 | //introduce logging method here to keep track of process |
||
| 62 | // can be overwritten in extended class to log with custom preocess logger |
||
| 63 | if ($this->verbose) { |
||
| 64 | Log::error($msg); |
||
| 65 | } |
||
| 66 | } |
||
| 67 | |||
| 68 | public function CleanUpTmpDirs() |
||
| 69 | { |
||
| 70 | $now = time(); |
||
| 71 | $isExpired = ($now - (60 * 240)); |
||
| 72 | $disk = \Storage::disk($this->storageDisk); |
||
| 73 | $all_dirs = $disk->directories($this->storagePathPrefix.'DocxMustache'); |
||
| 74 | foreach ($all_dirs as $dir) { |
||
| 75 | //delete dirs older than 20min |
||
| 76 | if ($disk->lastModified($dir) < $isExpired) { |
||
| 77 | $disk->deleteDirectory($dir); |
||
| 78 | } |
||
| 79 | } |
||
| 80 | } |
||
| 81 | |||
| 82 | public function GetTmpDir() |
||
| 83 | { |
||
| 84 | $this->CleanUpTmpDirs(); |
||
| 85 | $path = $this->storagePathPrefix.'DocxMustache/'.uniqid($this->template_file).'/'; |
||
| 86 | \File::makeDirectory($this->StoragePath($path), 0775, true); |
||
| 87 | |||
| 88 | return $path; |
||
| 89 | } |
||
| 90 | |||
| 91 | public function CopyTmplate() |
||
| 92 | { |
||
| 93 | $this->Log('Get Copy of Template'); |
||
| 94 | $this->local_path = $this->GetTmpDir(); |
||
| 95 | \Storage::disk($this->storageDisk)->copy($this->storagePathPrefix.$this->template_file, $this->local_path.$this->template_file_name); |
||
| 96 | } |
||
| 97 | |||
| 98 | protected function exctractOpenXmlFile($file) |
||
| 103 | |||
| 104 | protected function ReadOpenXmlFile($file, $type = 'file') |
||
| 105 | { |
||
| 106 | $this->exctractOpenXmlFile($file); |
||
| 107 | if ($type == 'file') { |
||
| 108 | if ($file_contents = \Storage::disk($this->storageDisk)->get($this->local_path.$file)) { |
||
| 109 | return $file_contents; |
||
| 110 | } else { |
||
| 121 | |||
| 122 | protected function SaveOpenXmlFile($file, $folder, $content) |
||
| 135 | |||
| 136 | protected function SaveOpenXmlObjectToFile($xmlObject, $file, $folder) |
||
| 144 | |||
| 145 | public function ReadTeamplate() |
||
| 164 | |||
| 165 | protected function AddContentType($imageCt = 'jpeg') |
||
| 192 | |||
| 193 | protected function FetchReplaceableImages(&$main_file, $ns) |
||
| 240 | |||
| 241 | protected function RemoveReplaceImages($imgs_replaced, &$rels_file) |
||
| 256 | |||
| 257 | protected function InsertImages($ns, &$imgs, &$rels_file, &$main_file) |
||
| 258 | { |
||
| 259 | $docimage = new DocImage(); |
||
| 260 | $allowed_imgs = $docimage->AllowedContentTypeImages(); |
||
| 261 | $image_i = 1; |
||
| 262 | //iterate through replacable images |
||
| 263 | foreach ($imgs as $k=>$img) { |
||
| 264 | $this->Log('Merge Images into Template - '.round($image_i / count($imgs) * 100).'%'); |
||
| 265 | //get file type of img and test it against supported imgs |
||
| 266 | if ($imgageData = $docimage->GetImageFromUrl($img['mode'] == 'url' ? $img['url'] : $img['path'], $img['mode'] == 'url' ? $this->imageManipulation : '')) { |
||
| 267 | $imgs[$k]['img_file_src'] = str_replace('wrklstId', 'wrklst_image', $img['id']).$allowed_imgs[$imgageData['mime']]; |
||
| 268 | $imgs[$k]['img_file_dest'] = str_replace('wrklstId', 'wrklst_image', $img['id']).'.jpeg'; |
||
| 269 | |||
| 270 | $resampled_img = $docimage->ResampleImage($this, $imgs, $k, $imgageData['data']); |
||
| 271 | |||
| 272 | $sxe = $rels_file->addChild('Relationship'); |
||
| 273 | $sxe->addAttribute('Id', $img['id']); |
||
| 274 | $sxe->addAttribute('Type', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'); |
||
| 275 | $sxe->addAttribute('Target', 'media/'.$imgs[$k]['img_file_dest']); |
||
| 276 | |||
| 277 | foreach ($main_file->xpath('//w:drawing') as $k=>$drawing) { |
||
| 278 | if (null !== $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a']) |
||
| 279 | ->graphic->graphicData->children($ns['pic'])->pic->blipFill && |
||
| 280 | $img['id'] == $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a']) |
||
| 281 | ->graphic->graphicData->children($ns['pic'])->pic->blipFill->children($ns['a']) |
||
| 282 | ->blip->attributes($ns['r'])['embed']) { |
||
| 283 | $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a']) |
||
| 284 | ->graphic->graphicData->children($ns['pic'])->pic->spPr->children($ns['a']) |
||
| 285 | ->xfrm->ext->attributes()['cx'] = $resampled_img['width_emus']; |
||
| 286 | $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a']) |
||
| 287 | ->graphic->graphicData->children($ns['pic'])->pic->spPr->children($ns['a']) |
||
| 288 | ->xfrm->ext->attributes()['cy'] = $resampled_img['height_emus']; |
||
| 289 | //anchor images |
||
| 290 | if (isset($main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->anchor)) { |
||
| 291 | $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->anchor->extent->attributes()['cx'] = $resampled_img['width_emus']; |
||
| 292 | $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->anchor->extent->attributes()['cy'] = $resampled_img['height_emus']; |
||
| 293 | } |
||
| 294 | //inline images |
||
| 295 | elseif (isset($main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->inline)) { |
||
| 296 | $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->inline->extent->attributes()['cx'] = $resampled_img['width_emus']; |
||
| 297 | $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->inline->extent->attributes()['cy'] = $resampled_img['height_emus']; |
||
| 298 | } |
||
| 299 | |||
| 300 | break; |
||
| 301 | } |
||
| 302 | } |
||
| 303 | } |
||
| 304 | $image_i++; |
||
| 305 | } |
||
| 306 | } |
||
| 307 | |||
| 308 | protected function ImageReplacer() |
||
| 309 | { |
||
| 310 | $this->Log('Merge Images into Template'); |
||
| 311 | |||
| 312 | //load main doc xml |
||
| 313 | $main_file = simplexml_load_string($this->word_doc); |
||
| 314 | |||
| 315 | //get all namespaces of the document |
||
| 316 | $ns = $main_file->getNamespaces(true); |
||
| 317 | |||
| 318 | $replaceableImage = $this->FetchReplaceableImages($main_file, $ns); |
||
| 319 | $imgs = $replaceableImage['imgs']; |
||
| 320 | $imgs_replaced = $replaceableImage['imgs_replaced']; |
||
|
|
|||
| 321 | |||
| 322 | $rels_file = $this->ReadOpenXmlFile('word/_rels/document.xml.rels', 'object'); |
||
| 323 | |||
| 324 | //do not remove until it is checked if the same img is used at a different position int he file as well, as otherwise broken images are produced. |
||
| 325 | //$this->RemoveReplaceImages($imgs_replaced, $rels_file); |
||
| 326 | |||
| 327 | //add jpg content type if not set |
||
| 328 | $this->AddContentType('jpeg'); |
||
| 329 | |||
| 330 | $this->InsertImages($ns, $imgs, $rels_file, $main_file); |
||
| 331 | |||
| 332 | $this->SaveOpenXmlObjectToFile($rels_file, 'word/_rels/document.xml.rels', 'word/_rels'); |
||
| 333 | |||
| 334 | if ($main_file_xml = $main_file->asXML()) { |
||
| 335 | $this->word_doc = $main_file_xml; |
||
| 336 | } else { |
||
| 337 | throw new Exception('Cannot generate xml for word/document.xml.'); |
||
| 338 | } |
||
| 339 | } |
||
| 340 | |||
| 341 | /** |
||
| 342 | * @param string $string |
||
| 343 | */ |
||
| 344 | protected function AnalyseImgUrlString($string) |
||
| 416 | |||
| 417 | public function SaveAsPdf() |
||
| 418 | { |
||
| 443 | } |
||
| 444 |
This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.
Both the
$myVarassignment in line 1 and the$higherassignment in line 2 are dead. The first because$myVaris never used and the second because$higheris always overwritten for every possible time line.