| Total Complexity | 77 |
| Total Lines | 647 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like Optimize 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.
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 Optimize, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 41 | class Optimize extends Component |
||
| 42 | { |
||
| 43 | // Public Methods |
||
| 44 | // ========================================================================= |
||
| 45 | |||
| 46 | /** |
||
| 47 | * Handle responding to EVENT_GET_ASSET_URL events |
||
| 48 | * |
||
| 49 | * @param GetAssetUrlEvent $event |
||
| 50 | * |
||
| 51 | * @return string |
||
| 52 | * @throws InvalidConfigException |
||
| 53 | */ |
||
| 54 | public function handleGetAssetUrlEvent(GetAssetUrlEvent $event) |
||
| 55 | { |
||
| 56 | $url = null; |
||
| 57 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 58 | if ($settings->transformMethod != 'craft') { |
||
| 59 | $asset = $event->asset; |
||
| 60 | $transform = $event->transform; |
||
| 61 | // If there's no transform requested, and we can't manipulate the image anyway, just return the URL |
||
| 62 | if ($transform === null |
||
| 63 | || !ImageHelper::canManipulateAsImage(pathinfo($asset->filename, PATHINFO_EXTENSION))) { |
||
| 64 | $volume = $asset->getVolume(); |
||
| 65 | |||
| 66 | return AssetsHelper::generateUrl($volume, $asset); |
||
| 67 | } |
||
| 68 | // If we're passed in null, make a dummy AssetTransform model |
||
| 69 | if (empty($transform)) { |
||
| 70 | $transform = new AssetTransform([ |
||
| 71 | 'height' => $asset->height, |
||
| 72 | 'width' => $asset->width, |
||
| 73 | 'interlace' => 'line', |
||
| 74 | ]); |
||
| 75 | } |
||
| 76 | // If we're passed an array, make an AssetTransform model out of it |
||
| 77 | if (is_array($transform)) { |
||
| 78 | $transform = new AssetTransform($transform); |
||
| 79 | } |
||
| 80 | // If we're passing in a string, look up the asset transform in the db |
||
| 81 | if (is_string($transform)) { |
||
| 82 | $assetTransforms = Craft::$app->getAssetTransforms(); |
||
| 83 | $transform = $assetTransforms->getTransformByHandle($transform); |
||
| 84 | } |
||
| 85 | // Generate an image transform url |
||
| 86 | $url = ImageOptimize::$transformClass::getTransformUrl( |
||
| 87 | $asset, |
||
| 88 | $transform, |
||
| 89 | ImageOptimize::$transformParams |
||
| 90 | ); |
||
| 91 | } |
||
| 92 | |||
| 93 | return $url; |
||
| 94 | } |
||
| 95 | |||
| 96 | /** |
||
| 97 | * Handle responding to EVENT_GENERATE_TRANSFORM events |
||
| 98 | * |
||
| 99 | * @param GenerateTransformEvent $event |
||
| 100 | * |
||
| 101 | * @return string |
||
| 102 | */ |
||
| 103 | public function handleGenerateTransformEvent(GenerateTransformEvent $event) |
||
| 104 | { |
||
| 105 | $tempPath = null; |
||
| 106 | |||
| 107 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 108 | // Only do this for local Craft transforms |
||
| 109 | if ($settings->transformMethod == 'craft' && !empty($event->asset)) { |
||
| 110 | // Apply any filters to the image |
||
| 111 | if (!empty($event->transformIndex->transform)) { |
||
| 112 | $this->applyFiltersToImage($event->transformIndex->transform, $event->asset, $event->image); |
||
| 113 | } |
||
| 114 | // Save the transformed image to a temp file |
||
| 115 | $tempPath = $this->saveTransformToTempFile( |
||
| 116 | $event->transformIndex, |
||
| 117 | $event->image |
||
| 118 | ); |
||
| 119 | $originalFileSize = @filesize($tempPath); |
||
| 120 | // Optimize the image |
||
| 121 | $this->optimizeImage( |
||
| 122 | $event->transformIndex, |
||
| 123 | $tempPath |
||
| 124 | ); |
||
| 125 | clearstatcache(true, $tempPath); |
||
| 126 | // Log the results of the image optimization |
||
| 127 | $optimizedFileSize = @filesize($tempPath); |
||
| 128 | $index = $event->transformIndex; |
||
| 129 | Craft::info( |
||
| 130 | pathinfo($index->filename, PATHINFO_FILENAME) |
||
| 131 | .'.' |
||
| 132 | .$index->detectedFormat |
||
| 133 | .' -> ' |
||
| 134 | .Craft::t('image-optimize', 'Original') |
||
| 135 | .': ' |
||
| 136 | .$this->humanFileSize($originalFileSize, 1) |
||
| 137 | .', ' |
||
| 138 | .Craft::t('image-optimize', 'Optimized') |
||
| 139 | .': ' |
||
| 140 | .$this->humanFileSize($optimizedFileSize, 1) |
||
| 141 | .' -> ' |
||
| 142 | .Craft::t('image-optimize', 'Savings') |
||
| 143 | .': ' |
||
| 144 | .number_format(abs(100 - (($optimizedFileSize * 100) / $originalFileSize)), 1) |
||
| 145 | .'%', |
||
| 146 | __METHOD__ |
||
| 147 | ); |
||
| 148 | // Create any image variants |
||
| 149 | $this->createImageVariants( |
||
| 150 | $event->transformIndex, |
||
| 151 | $event->asset, |
||
| 152 | $tempPath |
||
| 153 | ); |
||
| 154 | } |
||
| 155 | |||
| 156 | return $tempPath; |
||
| 157 | } |
||
| 158 | |||
| 159 | /** |
||
| 160 | * Handle cleaning up any variant creator images |
||
| 161 | * |
||
| 162 | * @param AssetTransformImageEvent $event |
||
| 163 | */ |
||
| 164 | public function handleAfterDeleteTransformsEvent(AssetTransformImageEvent $event) |
||
| 165 | { |
||
| 166 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 167 | // Only do this for local Craft transforms |
||
| 168 | if ($settings->transformMethod == 'craft' && !empty($event->asset)) { |
||
| 169 | $this->cleanupImageVariants($event->asset, $event->transformIndex); |
||
| 170 | } |
||
| 171 | } |
||
| 172 | |||
| 173 | /** |
||
| 174 | * Save out the image to a temp file |
||
| 175 | * |
||
| 176 | * @param AssetTransformIndex $index |
||
| 177 | * @param Image $image |
||
| 178 | * |
||
| 179 | * @return string |
||
| 180 | */ |
||
| 181 | public function saveTransformToTempFile(AssetTransformIndex $index, Image $image): string |
||
| 182 | { |
||
| 183 | $tempFilename = uniqid(pathinfo($index->filename, PATHINFO_FILENAME), true).'.'.$index->detectedFormat; |
||
| 184 | $tempPath = Craft::$app->getPath()->getTempPath().DIRECTORY_SEPARATOR.$tempFilename; |
||
| 185 | try { |
||
| 186 | $image->saveAs($tempPath); |
||
| 187 | } catch (ImageException $e) { |
||
| 188 | Craft::error('Transformed image save failed: '.$e->getMessage(), __METHOD__); |
||
| 189 | } |
||
| 190 | Craft::info('Transformed image saved to: '.$tempPath, __METHOD__); |
||
| 191 | |||
| 192 | return $tempPath; |
||
| 193 | } |
||
| 194 | |||
| 195 | /** |
||
| 196 | * Run any image post-processing/optimization on the image file |
||
| 197 | * |
||
| 198 | * @param AssetTransformIndex $index |
||
| 199 | * @param string $tempPath |
||
| 200 | */ |
||
| 201 | public function optimizeImage(AssetTransformIndex $index, string $tempPath) |
||
| 202 | { |
||
| 203 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 204 | // Get the active processors for the transform format |
||
| 205 | $activeImageProcessors = $settings->activeImageProcessors; |
||
| 206 | $fileFormat = $index->detectedFormat; |
||
| 207 | if (!empty($activeImageProcessors[$fileFormat])) { |
||
| 208 | // Iterate through all of the processors for this format |
||
| 209 | $imageProcessors = $settings->imageProcessors; |
||
| 210 | if (!empty($activeImageProcessors[$fileFormat])) { |
||
| 211 | foreach ($activeImageProcessors[$fileFormat] as $processor) { |
||
| 212 | if (!empty($processor) && !empty($imageProcessors[$processor])) { |
||
| 213 | $this->executeImageProcessor($imageProcessors[$processor], $tempPath); |
||
| 214 | } |
||
| 215 | } |
||
| 216 | } |
||
| 217 | } |
||
| 218 | } |
||
| 219 | |||
| 220 | /** |
||
| 221 | * Translate bytes into something human-readable |
||
| 222 | * |
||
| 223 | * @param $bytes |
||
| 224 | * @param int $decimals |
||
| 225 | * |
||
| 226 | * @return string |
||
| 227 | */ |
||
| 228 | public function humanFileSize($bytes, $decimals = 1): string |
||
| 229 | { |
||
| 230 | $oldSize = Craft::$app->formatter->sizeFormatBase; |
||
| 231 | Craft::$app->formatter->sizeFormatBase = 1000; |
||
| 232 | $result = Craft::$app->formatter->asShortSize($bytes, $decimals); |
||
| 233 | Craft::$app->formatter->sizeFormatBase = $oldSize; |
||
| 234 | |||
| 235 | return $result; |
||
| 236 | } |
||
| 237 | |||
| 238 | /** |
||
| 239 | * Create any image variants for the image file |
||
| 240 | * |
||
| 241 | * @param AssetTransformIndex $index |
||
| 242 | * @param Asset $asset |
||
| 243 | * @param string $tempPath |
||
| 244 | */ |
||
| 245 | public function createImageVariants(AssetTransformIndex $index, Asset $asset, string $tempPath) |
||
| 246 | { |
||
| 247 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 248 | // Get the active image variant creators |
||
| 249 | $activeImageVariantCreators = $settings->activeImageVariantCreators; |
||
| 250 | $fileFormat = $index->detectedFormat ?? $index->format; |
||
| 251 | if (!empty($activeImageVariantCreators[$fileFormat])) { |
||
| 252 | // Iterate through all of the image variant creators for this format |
||
| 253 | $imageVariantCreators = $settings->imageVariantCreators; |
||
| 254 | if (!empty($activeImageVariantCreators[$fileFormat])) { |
||
| 255 | foreach ($activeImageVariantCreators[$fileFormat] as $variantCreator) { |
||
| 256 | if (!empty($variantCreator) && !empty($imageVariantCreators[$variantCreator])) { |
||
| 257 | // Create the image variant in a temporary folder |
||
| 258 | $generalConfig = Craft::$app->getConfig()->getGeneral(); |
||
| 259 | $quality = $index->transform->quality ?: $generalConfig->defaultImageQuality; |
||
| 260 | $outputPath = $this->executeVariantCreator( |
||
| 261 | $imageVariantCreators[$variantCreator], |
||
| 262 | $tempPath, |
||
| 263 | $quality |
||
| 264 | ); |
||
| 265 | |||
| 266 | if (!empty($outputPath)) { |
||
| 267 | // Get info on the original and the created variant |
||
| 268 | $originalFileSize = @filesize($tempPath); |
||
| 269 | $variantFileSize = @filesize($outputPath); |
||
| 270 | |||
| 271 | Craft::info( |
||
| 272 | pathinfo($tempPath, PATHINFO_FILENAME) |
||
| 273 | .'.' |
||
| 274 | .pathinfo($tempPath, PATHINFO_EXTENSION) |
||
| 275 | .' -> ' |
||
| 276 | .pathinfo($outputPath, PATHINFO_FILENAME) |
||
| 277 | .'.' |
||
| 278 | .pathinfo($outputPath, PATHINFO_EXTENSION) |
||
| 279 | .' -> ' |
||
| 280 | .Craft::t('image-optimize', 'Original') |
||
| 281 | .': ' |
||
| 282 | .$this->humanFileSize($originalFileSize, 1) |
||
| 283 | .', ' |
||
| 284 | .Craft::t('image-optimize', 'Variant') |
||
| 285 | .': ' |
||
| 286 | .$this->humanFileSize($variantFileSize, 1) |
||
| 287 | .' -> ' |
||
| 288 | .Craft::t('image-optimize', 'Savings') |
||
| 289 | .': ' |
||
| 290 | .number_format(abs(100 - (($variantFileSize * 100) / $originalFileSize)), 1) |
||
| 291 | .'%', |
||
| 292 | __METHOD__ |
||
| 293 | ); |
||
| 294 | |||
| 295 | // Copy the image variant into place |
||
| 296 | $this->copyImageVariantToVolume( |
||
| 297 | $imageVariantCreators[$variantCreator], |
||
| 298 | $asset, |
||
| 299 | $index, |
||
| 300 | $outputPath |
||
| 301 | ); |
||
| 302 | } |
||
| 303 | } |
||
| 304 | } |
||
| 305 | } |
||
| 306 | } |
||
| 307 | } |
||
| 308 | |||
| 309 | /** |
||
| 310 | * Return an array of active image processors |
||
| 311 | * |
||
| 312 | * @return array |
||
| 313 | */ |
||
| 314 | public function getActiveImageProcessors(): array |
||
| 339 | } |
||
| 340 | |||
| 341 | /** |
||
| 342 | * Return an array of active image variant creators |
||
| 343 | * |
||
| 344 | * @return array |
||
| 345 | */ |
||
| 346 | public function getActiveVariantCreators(): array |
||
| 371 | } |
||
| 372 | |||
| 373 | // Protected Methods |
||
| 374 | // ========================================================================= |
||
| 375 | |||
| 376 | /** @noinspection PhpUnusedParameterInspection |
||
| 377 | * @param AssetTransform $transform |
||
| 378 | * @param Asset $asset |
||
| 379 | * @param Image $image |
||
| 380 | */ |
||
| 381 | protected function applyFiltersToImage(AssetTransform $transform, Asset $asset, Image $image) |
||
| 382 | { |
||
| 383 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 384 | // Only try to apply filters to Raster images |
||
| 385 | if ($image instanceof Raster) { |
||
| 386 | $imagineImage = $image->getImagineImage(); |
||
| 387 | if ($settings->autoSharpenScaledImages) { |
||
| 388 | // See if the image has been scaled >= 50% |
||
| 389 | $widthScale = $asset->getWidth() / $image->getWidth(); |
||
| 390 | $heightScale = $asset->getHeight() / $image->getHeight(); |
||
| 391 | if (($widthScale >= 2.0) || ($heightScale >= 2.0)) { |
||
| 392 | $imagineImage->effects() |
||
| 393 | ->sharpen(); |
||
| 394 | Craft::debug( |
||
| 395 | Craft::t( |
||
| 396 | 'image-optimize', |
||
| 397 | 'Image transform >= 50%, sharpened the transformed image: {name}', |
||
| 398 | [ |
||
| 399 | 'name' => $asset->title, |
||
| 400 | ] |
||
| 401 | ), |
||
| 402 | __METHOD__ |
||
| 403 | ); |
||
| 404 | } |
||
| 405 | } |
||
| 406 | } |
||
| 407 | } |
||
| 408 | |||
| 409 | /** |
||
| 410 | * @param string $tempPath |
||
| 411 | * @param $thisProcessor |
||
| 412 | */ |
||
| 413 | protected function executeImageProcessor($thisProcessor, string $tempPath) |
||
| 414 | { |
||
| 415 | // Make sure the command exists |
||
| 416 | if (is_file($thisProcessor['commandPath'])) { |
||
| 417 | // Set any options for the command |
||
| 418 | $commandOptions = ''; |
||
| 419 | if (!empty($thisProcessor['commandOptions'])) { |
||
| 420 | $commandOptions = ' ' |
||
| 421 | .$thisProcessor['commandOptions'] |
||
| 422 | .' '; |
||
| 423 | } |
||
| 424 | // Redirect the command output if necessary for this processor |
||
| 425 | $outputFileFlag = ''; |
||
| 426 | if (!empty($thisProcessor['commandOutputFileFlag'])) { |
||
| 427 | $outputFileFlag = ' ' |
||
| 428 | .$thisProcessor['commandOutputFileFlag'] |
||
| 429 | .' ' |
||
| 430 | .escapeshellarg($tempPath) |
||
| 431 | .' '; |
||
| 432 | } |
||
| 433 | // Build the command to execute |
||
| 434 | $cmd = |
||
| 435 | $thisProcessor['commandPath'] |
||
| 436 | .$commandOptions |
||
| 437 | .$outputFileFlag |
||
| 438 | .escapeshellarg($tempPath); |
||
| 439 | // Execute the command |
||
| 440 | $shellOutput = $this->executeShellCommand($cmd); |
||
| 441 | Craft::info($cmd."\n".$shellOutput, __METHOD__); |
||
| 442 | } else { |
||
| 443 | Craft::error( |
||
| 444 | $thisProcessor['commandPath'] |
||
| 445 | .' ' |
||
| 446 | .Craft::t('image-optimize', 'does not exist'), |
||
| 447 | __METHOD__ |
||
| 448 | ); |
||
| 449 | } |
||
| 450 | } |
||
| 451 | |||
| 452 | /** |
||
| 453 | * Execute a shell command |
||
| 454 | * |
||
| 455 | * @param string $command |
||
| 456 | * |
||
| 457 | * @return string |
||
| 458 | */ |
||
| 459 | protected function executeShellCommand(string $command): string |
||
| 478 | } |
||
| 479 | |||
| 480 | /** |
||
| 481 | * @param $variantCreatorCommand |
||
| 482 | * @param string $tempPath |
||
| 483 | * @param int $imageQuality |
||
| 484 | * |
||
| 485 | * @return string|null the path to the created variant |
||
| 486 | */ |
||
| 487 | protected function executeVariantCreator($variantCreatorCommand, string $tempPath, int $imageQuality) |
||
| 540 | } |
||
| 541 | |||
| 542 | /** |
||
| 543 | * @param Asset $asset |
||
| 544 | * @param AssetTransformIndex $transformIndex |
||
| 545 | */ |
||
| 546 | protected function cleanupImageVariants(Asset $asset, AssetTransformIndex $transformIndex) |
||
| 592 | ); |
||
| 593 | } |
||
| 594 | } |
||
| 595 | } |
||
| 596 | } |
||
| 597 | } |
||
| 598 | |||
| 599 | /** |
||
| 600 | * @param $variantCreatorCommand |
||
| 601 | * @param Asset $asset |
||
| 602 | * @param AssetTransformIndex $index |
||
| 603 | * @param $outputPath |
||
| 604 | */ |
||
| 605 | protected function copyImageVariantToVolume( |
||
| 668 | ); |
||
| 669 | } |
||
| 670 | } |
||
| 671 | |||
| 672 | /** |
||
| 673 | * @param string $path |
||
| 674 | * @param string $extension |
||
| 675 | * |
||
| 676 | * @return string |
||
| 677 | */ |
||
| 678 | protected function swapPathExtension(string $path, string $extension): string |
||
| 690 |