| Total Complexity | 110 |
| Total Lines | 885 |
| Duplicated Lines | 0 % |
| Changes | 21 | ||
| Bugs | 1 | Features | 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 |
||
| 54 | class Optimize extends Component |
||
| 55 | { |
||
| 56 | // Constants |
||
| 57 | // ========================================================================= |
||
| 58 | |||
| 59 | /** |
||
| 60 | * @event RegisterComponentTypesEvent The event that is triggered when registering |
||
| 61 | * Image Transform types |
||
| 62 | * |
||
| 63 | * Image Transform types must implement [[ImageTransformInterface]]. [[ImageTransform]] |
||
| 64 | * provides a base implementation. |
||
| 65 | * |
||
| 66 | * ```php |
||
| 67 | * use nystudio107\imageoptimize\services\Optimize; |
||
| 68 | * use craft\events\RegisterComponentTypesEvent; |
||
| 69 | * use yii\base\Event; |
||
| 70 | * |
||
| 71 | * Event::on(Optimize::class, |
||
| 72 | * Optimize::EVENT_REGISTER_IMAGE_TRANSFORM_TYPES, |
||
| 73 | * function(RegisterComponentTypesEvent $event) { |
||
| 74 | * $event->types[] = MyImageTransform::class; |
||
| 75 | * } |
||
| 76 | * ); |
||
| 77 | * ``` |
||
| 78 | */ |
||
| 79 | const EVENT_REGISTER_IMAGE_TRANSFORM_TYPES = 'registerImageTransformTypes'; |
||
| 80 | |||
| 81 | const DEFAULT_IMAGE_TRANSFORM_TYPES = [ |
||
| 82 | CraftImageTransform::class, |
||
| 83 | ImgixImageTransform::class, |
||
| 84 | SharpImageTransform::class, |
||
| 85 | ThumborImageTransform::class, |
||
| 86 | ]; |
||
| 87 | |||
| 88 | // Public Methods |
||
| 89 | // ========================================================================= |
||
| 90 | |||
| 91 | /** |
||
| 92 | * Returns all available field type classes. |
||
| 93 | * |
||
| 94 | * @return string[] The available field type classes |
||
| 95 | */ |
||
| 96 | public function getAllImageTransformTypes(): array |
||
| 97 | { |
||
| 98 | $imageTransformTypes = array_unique(array_merge( |
||
| 99 | ImageOptimize::$plugin->getSettings()->defaultImageTransformTypes ?? [], |
||
| 100 | self::DEFAULT_IMAGE_TRANSFORM_TYPES |
||
| 101 | ), SORT_REGULAR); |
||
| 102 | |||
| 103 | $event = new RegisterComponentTypesEvent([ |
||
| 104 | 'types' => $imageTransformTypes |
||
| 105 | ]); |
||
| 106 | $this->trigger(self::EVENT_REGISTER_IMAGE_TRANSFORM_TYPES, $event); |
||
| 107 | |||
| 108 | return $event->types; |
||
| 109 | } |
||
| 110 | |||
| 111 | /** |
||
| 112 | * Creates an Image Transform with a given config. |
||
| 113 | * |
||
| 114 | * @param mixed $config The Image Transform’s class name, or its config, |
||
| 115 | * with a `type` value and optionally a `settings` value |
||
| 116 | * |
||
| 117 | * @return null|ImageTransformInterface The Image Transform |
||
| 118 | */ |
||
| 119 | public function createImageTransformType($config): ImageTransformInterface |
||
| 120 | { |
||
| 121 | if (is_string($config)) { |
||
| 122 | $config = ['type' => $config]; |
||
| 123 | } |
||
| 124 | |||
| 125 | try { |
||
| 126 | /** @var ImageTransform $imageTransform */ |
||
| 127 | $imageTransform = ComponentHelper::createComponent($config, ImageTransformInterface::class); |
||
| 128 | } catch (\Throwable $e) { |
||
| 129 | $imageTransform = null; |
||
| 130 | Craft::error($e->getMessage(), __METHOD__); |
||
| 131 | } |
||
| 132 | |||
| 133 | return $imageTransform; |
||
| 134 | } |
||
| 135 | |||
| 136 | /** |
||
| 137 | * Handle responding to EVENT_GET_ASSET_URL events |
||
| 138 | * |
||
| 139 | * @param GetAssetUrlEvent $event |
||
| 140 | * |
||
| 141 | * @return null|string |
||
| 142 | * @throws InvalidConfigException |
||
| 143 | */ |
||
| 144 | public function handleGetAssetUrlEvent(GetAssetUrlEvent $event) |
||
| 145 | { |
||
| 146 | Craft::beginProfile('handleGetAssetUrlEvent', __METHOD__); |
||
| 147 | $url = null; |
||
| 148 | if (!ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform) { |
||
| 149 | $asset = $event->asset; |
||
| 150 | $transform = $event->transform; |
||
| 151 | // If the transform is empty in some regard, normalize it to null |
||
| 152 | if (empty($transform)) { |
||
| 153 | $transform = null; |
||
| 154 | } |
||
| 155 | // If there's no transform requested, return `null` so other plugins have a crack at it |
||
| 156 | if ($transform === null) { |
||
| 157 | return null; |
||
| 158 | } |
||
| 159 | // If we're passed in null, make a dummy AssetTransform model for Thumbor |
||
| 160 | // For backwards compatibility |
||
| 161 | if ($transform === null && ImageOptimize::$plugin->transformMethod instanceof ThumborImageTransform) { |
||
| 162 | $transform = new AssetTransform([ |
||
| 163 | 'width' => $asset->width, |
||
| 164 | 'interlace' => 'line', |
||
| 165 | ]); |
||
| 166 | } |
||
| 167 | // If we're passed an array, make an AssetTransform model out of it |
||
| 168 | if (\is_array($transform)) { |
||
| 169 | $transform = new AssetTransform($transform); |
||
| 170 | } |
||
| 171 | // If we're passing in a string, look up the asset transform in the db |
||
| 172 | if (\is_string($transform)) { |
||
| 173 | $assetTransforms = Craft::$app->getAssetTransforms(); |
||
| 174 | $transform = $assetTransforms->getTransformByHandle($transform); |
||
| 175 | } |
||
| 176 | // If the final format is an SVG, don't attempt to transform it |
||
| 177 | $finalFormat = empty($transform['format']) ? $asset->getExtension() : $transform['format']; |
||
| 178 | if ($finalFormat === 'svg') { |
||
| 179 | return null; |
||
| 180 | } |
||
| 181 | // Normalize the extension to lowercase, for some transform methods that require this |
||
| 182 | if (!empty($transform) && !empty($finalFormat)) { |
||
| 183 | $format = $transform['format'] ?? null; |
||
| 184 | $transform['format'] = $format === null ? null : strtolower($finalFormat); |
||
| 185 | } |
||
| 186 | // Generate an image transform url |
||
| 187 | $url = ImageOptimize::$plugin->transformMethod->getTransformUrl( |
||
| 188 | $asset, |
||
| 189 | $transform |
||
| 190 | ); |
||
| 191 | } |
||
| 192 | Craft::endProfile('handleGetAssetUrlEvent', __METHOD__); |
||
| 193 | |||
| 194 | return $url; |
||
| 195 | } |
||
| 196 | |||
| 197 | /** |
||
| 198 | * Handle responding to EVENT_GET_ASSET_THUMB_URL events |
||
| 199 | * |
||
| 200 | * @param GetAssetThumbUrlEvent $event |
||
| 201 | * |
||
| 202 | * @return null|string |
||
| 203 | */ |
||
| 204 | public function handleGetAssetThumbUrlEvent(GetAssetThumbUrlEvent $event) |
||
| 237 | } |
||
| 238 | |||
| 239 | /** |
||
| 240 | * Returns whether `.webp` is a format supported by the server |
||
| 241 | * |
||
| 242 | * @return bool |
||
| 243 | */ |
||
| 244 | public function serverSupportsWebP(): bool |
||
| 245 | { |
||
| 246 | $result = false; |
||
| 247 | $variantCreators = ImageOptimize::$plugin->optimize->getActiveVariantCreators(); |
||
| 248 | foreach ($variantCreators as $variantCreator) { |
||
| 249 | if ($variantCreator['creator'] === 'cwebp' && $variantCreator['installed']) { |
||
| 250 | $result = true; |
||
| 251 | } |
||
| 252 | } |
||
| 253 | |||
| 254 | return $result; |
||
| 255 | } |
||
| 256 | |||
| 257 | /** |
||
| 258 | * Render the LazySizes fallback JS |
||
| 259 | * |
||
| 260 | * @param array $scriptAttrs |
||
| 261 | * @param array $variables |
||
| 262 | * @return string |
||
| 263 | */ |
||
| 264 | public function renderLazySizesFallbackJs($scriptAttrs = [], $variables = []) |
||
| 265 | { |
||
| 266 | $minifier = 'minify'; |
||
| 267 | if ($scriptAttrs === null) { |
||
| 268 | $minifier = 'jsMin'; |
||
| 269 | } |
||
| 270 | $vars = array_merge([ |
||
| 271 | 'scriptSrc' => 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.0/lazysizes.min.js', |
||
| 272 | ], |
||
| 273 | $variables |
||
| 274 | ); |
||
| 275 | $content = PluginTemplateHelper::renderPluginTemplate( |
||
| 276 | 'frontend/lazysizes-fallback-js', |
||
| 277 | $vars, |
||
| 278 | $minifier |
||
| 279 | ); |
||
| 280 | $content = (string)$content; |
||
| 281 | if ($scriptAttrs !== null) { |
||
| 282 | $attrs = array_merge([ |
||
| 283 | ], |
||
| 284 | $scriptAttrs |
||
| 285 | ); |
||
| 286 | $content = Html::tag('script', $content, $scriptAttrs); |
||
| 287 | } |
||
| 288 | |||
| 289 | return $content; |
||
| 290 | } |
||
| 291 | |||
| 292 | /** |
||
| 293 | * Render the LazySizes fallback JS |
||
| 294 | * |
||
| 295 | * @param array $scriptAttrs |
||
| 296 | * @param array $variables |
||
| 297 | * @return string |
||
| 298 | */ |
||
| 299 | public function renderLazySizesJs($scriptAttrs = [], $variables = []) |
||
| 300 | { |
||
| 301 | $minifier = 'minify'; |
||
| 302 | if ($scriptAttrs === null) { |
||
| 303 | $minifier = 'jsMin'; |
||
| 304 | } |
||
| 305 | $vars = array_merge([ |
||
| 306 | 'scriptSrc' => 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.0/lazysizes.min.js', |
||
| 307 | ], |
||
| 308 | $variables |
||
| 309 | ); |
||
| 310 | $content = PluginTemplateHelper::renderPluginTemplate( |
||
| 311 | 'frontend/lazysizes-js', |
||
| 312 | $vars, |
||
| 313 | $minifier |
||
| 314 | ); |
||
| 315 | $content = (string)$content; |
||
| 316 | if ($scriptAttrs !== null) { |
||
| 317 | $attrs = array_merge([ |
||
| 318 | ], |
||
| 319 | $scriptAttrs |
||
| 320 | ); |
||
| 321 | $content = Html::tag('script', $content, $scriptAttrs); |
||
| 322 | } |
||
| 323 | |||
| 324 | return $content; |
||
| 325 | } |
||
| 326 | |||
| 327 | /** |
||
| 328 | * Handle responding to EVENT_GENERATE_TRANSFORM events |
||
| 329 | * |
||
| 330 | * @param GenerateTransformEvent $event |
||
| 331 | * |
||
| 332 | * @return null|string |
||
| 333 | */ |
||
| 334 | public function handleGenerateTransformEvent(GenerateTransformEvent $event) |
||
| 335 | { |
||
| 336 | Craft::beginProfile('handleGenerateTransformEvent', __METHOD__); |
||
| 337 | $tempPath = null; |
||
| 338 | |||
| 339 | // Only do this for local Craft transforms |
||
| 340 | if (ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform && $event->asset !== null) { |
||
| 341 | // Apply any filters to the image |
||
| 342 | if ($event->transformIndex->transform !== null) { |
||
| 343 | $this->applyFiltersToImage($event->transformIndex->transform, $event->asset, $event->image); |
||
| 344 | } |
||
| 345 | // Save the transformed image to a temp file |
||
| 346 | $tempPath = $this->saveTransformToTempFile( |
||
| 347 | $event->transformIndex, |
||
| 348 | $event->image |
||
| 349 | ); |
||
| 350 | $originalFileSize = @filesize($tempPath); |
||
| 351 | // Optimize the image |
||
| 352 | $this->optimizeImage( |
||
| 353 | $event->transformIndex, |
||
| 354 | $tempPath |
||
| 355 | ); |
||
| 356 | clearstatcache(true, $tempPath); |
||
| 357 | // Log the results of the image optimization |
||
| 358 | $optimizedFileSize = @filesize($tempPath); |
||
| 359 | $index = $event->transformIndex; |
||
| 360 | $message = |
||
| 361 | pathinfo($index->filename, PATHINFO_FILENAME) |
||
| 362 | .'.' |
||
| 363 | .$index->detectedFormat |
||
| 364 | .' -> ' |
||
| 365 | .Craft::t('image-optimize', 'Original') |
||
| 366 | .': ' |
||
| 367 | .$this->humanFileSize($originalFileSize, 1) |
||
| 368 | .', ' |
||
| 369 | .Craft::t('image-optimize', 'Optimized') |
||
| 370 | .': ' |
||
| 371 | .$this->humanFileSize($optimizedFileSize, 1) |
||
| 372 | .' -> ' |
||
| 373 | .Craft::t('image-optimize', 'Savings') |
||
| 374 | .': ' |
||
| 375 | .number_format(abs(100 - (($optimizedFileSize * 100) / $originalFileSize)), 1) |
||
| 376 | .'%'; |
||
| 377 | Craft::info($message, __METHOD__); |
||
| 378 | if (Craft::$app instanceof ConsoleApplication) { |
||
| 379 | echo $message . PHP_EOL; |
||
| 380 | } |
||
| 381 | // Create any image variants |
||
| 382 | $this->createImageVariants( |
||
| 383 | $event->transformIndex, |
||
| 384 | $event->asset, |
||
| 385 | $tempPath |
||
| 386 | ); |
||
| 387 | } |
||
| 388 | Craft::endProfile('handleGenerateTransformEvent', __METHOD__); |
||
| 389 | |||
| 390 | return $tempPath; |
||
| 391 | } |
||
| 392 | |||
| 393 | /** |
||
| 394 | * Handle cleaning up any variant creator images |
||
| 395 | * |
||
| 396 | * @param AssetTransformImageEvent $event |
||
| 397 | */ |
||
| 398 | public function handleAfterDeleteTransformsEvent(AssetTransformImageEvent $event) |
||
| 404 | } |
||
| 405 | } |
||
| 406 | |||
| 407 | /** |
||
| 408 | * Save out the image to a temp file |
||
| 409 | * |
||
| 410 | * @param AssetTransformIndex $index |
||
| 411 | * @param Image $image |
||
| 412 | * |
||
| 413 | * @return string |
||
| 414 | */ |
||
| 415 | public function saveTransformToTempFile(AssetTransformIndex $index, Image $image): string |
||
| 427 | } |
||
| 428 | |||
| 429 | /** |
||
| 430 | * Run any image post-processing/optimization on the image file |
||
| 431 | * |
||
| 432 | * @param AssetTransformIndex $index |
||
| 433 | * @param string $tempPath |
||
| 434 | */ |
||
| 435 | public function optimizeImage(AssetTransformIndex $index, string $tempPath) |
||
| 436 | { |
||
| 437 | Craft::beginProfile('optimizeImage', __METHOD__); |
||
| 438 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 439 | // Get the active processors for the transform format |
||
| 440 | $activeImageProcessors = $settings->activeImageProcessors; |
||
| 441 | $fileFormat = $index->detectedFormat ?? $index->format; |
||
| 442 | $fileFormat = strtolower($fileFormat); |
||
| 443 | // Special-case for 'jpeg' |
||
| 444 | if ($fileFormat === 'jpeg') { |
||
| 445 | $fileFormat = 'jpg'; |
||
| 446 | } |
||
| 447 | if (!empty($activeImageProcessors[$fileFormat])) { |
||
| 448 | // Iterate through all of the processors for this format |
||
| 449 | $imageProcessors = $settings->imageProcessors; |
||
| 450 | foreach ($activeImageProcessors[$fileFormat] as $processor) { |
||
| 451 | if (!empty($processor) && !empty($imageProcessors[$processor])) { |
||
| 452 | $this->executeImageProcessor($imageProcessors[$processor], $tempPath); |
||
| 453 | } |
||
| 454 | } |
||
| 455 | } |
||
| 456 | Craft::endProfile('optimizeImage', __METHOD__); |
||
| 457 | } |
||
| 458 | |||
| 459 | /** |
||
| 460 | * Translate bytes into something human-readable |
||
| 461 | * |
||
| 462 | * @param $bytes |
||
| 463 | * @param int $decimals |
||
| 464 | * |
||
| 465 | * @return string |
||
| 466 | */ |
||
| 467 | public function humanFileSize($bytes, $decimals = 1): string |
||
| 468 | { |
||
| 469 | $oldSize = Craft::$app->formatter->sizeFormatBase; |
||
| 470 | Craft::$app->formatter->sizeFormatBase = 1000; |
||
| 471 | $result = Craft::$app->formatter->asShortSize($bytes, $decimals); |
||
| 472 | Craft::$app->formatter->sizeFormatBase = $oldSize; |
||
| 473 | |||
| 474 | return $result; |
||
| 475 | } |
||
| 476 | |||
| 477 | /** |
||
| 478 | * Create any image variants for the image file |
||
| 479 | * |
||
| 480 | * @param AssetTransformIndex $index |
||
| 481 | * @param Asset $asset |
||
| 482 | * @param string $tempPath |
||
| 483 | */ |
||
| 484 | public function createImageVariants(AssetTransformIndex $index, Asset $asset, string $tempPath) |
||
| 485 | { |
||
| 486 | Craft::beginProfile('createImageVariants', __METHOD__); |
||
| 487 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 488 | // Get the active image variant creators |
||
| 489 | $activeImageVariantCreators = $settings->activeImageVariantCreators; |
||
| 490 | $fileFormat = $index->detectedFormat ?? $index->format; |
||
| 491 | $fileFormat = strtolower($fileFormat); |
||
| 492 | // Special-case for 'jpeg' |
||
| 493 | if ($fileFormat === 'jpeg') { |
||
| 494 | $fileFormat = 'jpg'; |
||
| 495 | } |
||
| 496 | if (!empty($activeImageVariantCreators[$fileFormat])) { |
||
| 497 | // Iterate through all of the image variant creators for this format |
||
| 498 | $imageVariantCreators = $settings->imageVariantCreators; |
||
| 499 | foreach ($activeImageVariantCreators[$fileFormat] as $variantCreator) { |
||
| 500 | if (!empty($variantCreator) && !empty($imageVariantCreators[$variantCreator])) { |
||
| 501 | // Create the image variant in a temporary folder |
||
| 502 | $generalConfig = Craft::$app->getConfig()->getGeneral(); |
||
| 503 | $quality = $index->transform->quality ?: $generalConfig->defaultImageQuality; |
||
| 504 | $outputPath = $this->executeVariantCreator( |
||
| 505 | $imageVariantCreators[$variantCreator], |
||
| 506 | $tempPath, |
||
| 507 | $quality |
||
| 508 | ); |
||
| 509 | if ($outputPath !== null) { |
||
| 510 | // Get info on the original and the created variant |
||
| 511 | $originalFileSize = @filesize($tempPath); |
||
| 512 | $variantFileSize = @filesize($outputPath); |
||
| 513 | $message = |
||
| 514 | pathinfo($tempPath, PATHINFO_FILENAME) |
||
| 515 | .'.' |
||
| 516 | .pathinfo($tempPath, PATHINFO_EXTENSION) |
||
| 517 | .' -> ' |
||
| 518 | .pathinfo($outputPath, PATHINFO_FILENAME) |
||
| 519 | .'.' |
||
| 520 | .pathinfo($outputPath, PATHINFO_EXTENSION) |
||
| 521 | .' -> ' |
||
| 522 | .Craft::t('image-optimize', 'Original') |
||
| 523 | .': ' |
||
| 524 | .$this->humanFileSize($originalFileSize, 1) |
||
| 525 | .', ' |
||
| 526 | .Craft::t('image-optimize', 'Variant') |
||
| 527 | .': ' |
||
| 528 | .$this->humanFileSize($variantFileSize, 1) |
||
| 529 | .' -> ' |
||
| 530 | .Craft::t('image-optimize', 'Savings') |
||
| 531 | .': ' |
||
| 532 | .number_format(abs(100 - (($variantFileSize * 100) / $originalFileSize)), 1) |
||
| 533 | .'%'; |
||
| 534 | Craft::info($message, __METHOD__); |
||
| 535 | if (Craft::$app instanceof ConsoleApplication) { |
||
| 536 | echo $message . PHP_EOL; |
||
| 537 | } |
||
| 538 | // Copy the image variant into place |
||
| 539 | $this->copyImageVariantToVolume( |
||
| 540 | $imageVariantCreators[$variantCreator], |
||
| 541 | $asset, |
||
| 542 | $index, |
||
| 543 | $outputPath |
||
| 544 | ); |
||
| 545 | } |
||
| 546 | } |
||
| 547 | } |
||
| 548 | } |
||
| 549 | Craft::endProfile('createImageVariants', __METHOD__); |
||
| 550 | } |
||
| 551 | |||
| 552 | /** |
||
| 553 | * Return an array of active image processors |
||
| 554 | * |
||
| 555 | * @return array |
||
| 556 | */ |
||
| 557 | public function getActiveImageProcessors(): array |
||
| 582 | } |
||
| 583 | |||
| 584 | /** |
||
| 585 | * Return an array of active image variant creators |
||
| 586 | * |
||
| 587 | * @return array |
||
| 588 | */ |
||
| 589 | public function getActiveVariantCreators(): array |
||
| 614 | } |
||
| 615 | |||
| 616 | // Protected Methods |
||
| 617 | // ========================================================================= |
||
| 618 | |||
| 619 | /** @noinspection PhpUnusedParameterInspection |
||
| 620 | * @param AssetTransform $transform |
||
| 621 | * @param Asset $asset |
||
| 622 | * @param Image $image |
||
| 623 | */ |
||
| 624 | |||
| 625 | protected function applyFiltersToImage(AssetTransform $transform, Asset $asset, Image $image) |
||
| 649 | ); |
||
| 650 | } |
||
| 651 | } |
||
| 652 | } |
||
| 653 | } |
||
| 654 | } |
||
| 655 | |||
| 656 | /** |
||
| 657 | * @param string $tempPath |
||
| 658 | * @param $thisProcessor |
||
| 659 | */ |
||
| 660 | protected function executeImageProcessor($thisProcessor, string $tempPath) |
||
| 661 | { |
||
| 662 | // Make sure the command exists |
||
| 663 | if (is_file($thisProcessor['commandPath'])) { |
||
| 664 | // Set any options for the command |
||
| 665 | $commandOptions = ''; |
||
| 666 | if (!empty($thisProcessor['commandOptions'])) { |
||
| 667 | $commandOptions = ' ' |
||
| 668 | .$thisProcessor['commandOptions'] |
||
| 669 | .' '; |
||
| 670 | } |
||
| 671 | // Redirect the command output if necessary for this processor |
||
| 672 | $outputFileFlag = ''; |
||
| 673 | if (!empty($thisProcessor['commandOutputFileFlag'])) { |
||
| 674 | $outputFileFlag = ' ' |
||
| 675 | .$thisProcessor['commandOutputFileFlag'] |
||
| 676 | .' ' |
||
| 677 | .escapeshellarg($tempPath) |
||
| 678 | .' '; |
||
| 679 | } |
||
| 680 | // If both $commandOptions & $outputFileFlag are empty, pad it with a space |
||
| 681 | if (empty($commandOptions) && empty($outputFileFlag)) { |
||
| 682 | $commandOptions = ' '; |
||
| 683 | } |
||
| 684 | // Build the command to execute |
||
| 685 | $cmd = |
||
| 686 | $thisProcessor['commandPath'] |
||
| 687 | .$commandOptions |
||
| 688 | .$outputFileFlag |
||
| 689 | .escapeshellarg($tempPath); |
||
| 690 | // Execute the command |
||
| 691 | $shellOutput = $this->executeShellCommand($cmd); |
||
| 692 | Craft::info($cmd."\n".$shellOutput, __METHOD__); |
||
| 693 | } else { |
||
| 694 | Craft::error( |
||
| 695 | $thisProcessor['commandPath'] |
||
| 696 | .' ' |
||
| 697 | .Craft::t('image-optimize', 'does not exist'), |
||
| 698 | __METHOD__ |
||
| 699 | ); |
||
| 700 | } |
||
| 701 | } |
||
| 702 | |||
| 703 | /** |
||
| 704 | * Execute a shell command |
||
| 705 | * |
||
| 706 | * @param string $command |
||
| 707 | * |
||
| 708 | * @return string |
||
| 709 | */ |
||
| 710 | protected function executeShellCommand(string $command): string |
||
| 711 | { |
||
| 712 | // Create the shell command |
||
| 713 | $shellCommand = new ShellCommand(); |
||
| 714 | $shellCommand->setCommand($command); |
||
| 715 | |||
| 716 | // If we don't have proc_open, maybe we've got exec |
||
| 717 | if (!\function_exists('proc_open') && \function_exists('exec')) { |
||
| 718 | $shellCommand->useExec = true; |
||
| 719 | } |
||
| 720 | |||
| 721 | // Return the result of the command's output or error |
||
| 722 | if ($shellCommand->execute()) { |
||
| 723 | $result = $shellCommand->getOutput(); |
||
| 724 | } else { |
||
| 725 | $result = $shellCommand->getError(); |
||
| 726 | } |
||
| 727 | |||
| 728 | return $result; |
||
| 729 | } |
||
| 730 | |||
| 731 | /** |
||
| 732 | * @param $variantCreatorCommand |
||
| 733 | * @param string $tempPath |
||
| 734 | * @param int $imageQuality |
||
| 735 | * |
||
| 736 | * @return string|null the path to the created variant |
||
| 737 | */ |
||
| 738 | protected function executeVariantCreator($variantCreatorCommand, string $tempPath, int $imageQuality) |
||
| 739 | { |
||
| 740 | $outputPath = $tempPath; |
||
| 741 | // Make sure the command exists |
||
| 742 | if (is_file($variantCreatorCommand['commandPath'])) { |
||
| 743 | // Get the output file for this image variant |
||
| 744 | $outputPath .= '.'.$variantCreatorCommand['imageVariantExtension']; |
||
| 745 | // Set any options for the command |
||
| 746 | $commandOptions = ''; |
||
| 747 | if (!empty($variantCreatorCommand['commandOptions'])) { |
||
| 748 | $commandOptions = ' ' |
||
| 749 | .$variantCreatorCommand['commandOptions'] |
||
| 750 | .' '; |
||
| 751 | } |
||
| 752 | // Redirect the command output if necessary for this variantCreator |
||
| 753 | $outputFileFlag = ''; |
||
| 754 | if (!empty($variantCreatorCommand['commandOutputFileFlag'])) { |
||
| 755 | $outputFileFlag = ' ' |
||
| 756 | .$variantCreatorCommand['commandOutputFileFlag'] |
||
| 757 | .' ' |
||
| 758 | .escapeshellarg($outputPath) |
||
| 759 | .' '; |
||
| 760 | } |
||
| 761 | // Get the quality setting of this transform |
||
| 762 | $commandQualityFlag = ''; |
||
| 763 | if (!empty($variantCreatorCommand['commandQualityFlag'])) { |
||
| 764 | $commandQualityFlag = ' ' |
||
| 765 | .$variantCreatorCommand['commandQualityFlag'] |
||
| 766 | .' ' |
||
| 767 | .$imageQuality |
||
| 768 | .' '; |
||
| 769 | } |
||
| 770 | // Build the command to execute |
||
| 771 | $cmd = |
||
| 772 | $variantCreatorCommand['commandPath'] |
||
| 773 | .$commandOptions |
||
| 774 | .$commandQualityFlag |
||
| 775 | .$outputFileFlag |
||
| 776 | .escapeshellarg($tempPath); |
||
| 777 | // Execute the command |
||
| 778 | $shellOutput = $this->executeShellCommand($cmd); |
||
| 779 | Craft::info($cmd."\n".$shellOutput, __METHOD__); |
||
| 780 | } else { |
||
| 781 | Craft::error( |
||
| 782 | $variantCreatorCommand['commandPath'] |
||
| 783 | .' ' |
||
| 784 | .Craft::t('image-optimize', 'does not exist'), |
||
| 785 | __METHOD__ |
||
| 786 | ); |
||
| 787 | $outputPath = null; |
||
| 788 | } |
||
| 789 | |||
| 790 | return $outputPath; |
||
| 791 | } |
||
| 792 | |||
| 793 | /** |
||
| 794 | * @param Asset $asset |
||
| 795 | * @param AssetTransformIndex $transformIndex |
||
| 796 | */ |
||
| 797 | protected function cleanupImageVariants(Asset $asset, AssetTransformIndex $transformIndex) |
||
| 798 | { |
||
| 799 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 800 | $assetTransforms = Craft::$app->getAssetTransforms(); |
||
| 801 | // Get the active image variant creators |
||
| 802 | $activeImageVariantCreators = $settings->activeImageVariantCreators; |
||
| 803 | $fileFormat = $transformIndex->detectedFormat ?? $transformIndex->format; |
||
| 804 | if (!empty($activeImageVariantCreators[$fileFormat])) { |
||
| 805 | // Iterate through all of the image variant creators for this format |
||
| 806 | $imageVariantCreators = $settings->imageVariantCreators; |
||
| 807 | if (!empty($activeImageVariantCreators[$fileFormat])) { |
||
| 808 | foreach ($activeImageVariantCreators[$fileFormat] as $variantCreator) { |
||
| 809 | if (!empty($variantCreator) && !empty($imageVariantCreators[$variantCreator])) { |
||
| 810 | // Create the image variant in a temporary folder |
||
| 811 | $variantCreatorCommand = $imageVariantCreators[$variantCreator]; |
||
| 812 | try { |
||
| 813 | $volume = $asset->getVolume(); |
||
| 814 | } catch (InvalidConfigException $e) { |
||
| 815 | $volume = null; |
||
| 816 | Craft::error( |
||
| 817 | 'Asset volume error: '.$e->getMessage(), |
||
| 818 | __METHOD__ |
||
| 819 | ); |
||
| 820 | } |
||
| 821 | try { |
||
| 822 | $variantPath = $asset->getFolder()->path.$assetTransforms->getTransformSubpath( |
||
| 823 | $asset, |
||
| 824 | $transformIndex |
||
| 825 | ); |
||
| 826 | } catch (InvalidConfigException $e) { |
||
| 827 | $variantPath = ''; |
||
| 828 | Craft::error( |
||
| 829 | 'Asset folder does not exist: '.$e->getMessage(), |
||
| 830 | __METHOD__ |
||
| 831 | ); |
||
| 832 | } |
||
| 833 | $variantPath .= '.'.$variantCreatorCommand['imageVariantExtension']; |
||
| 834 | // Delete the variant file in case it is stale |
||
| 835 | try { |
||
| 836 | $volume->deleteFile($variantPath); |
||
| 837 | } catch (VolumeException $e) { |
||
| 838 | // We're fine with that. |
||
| 839 | } |
||
| 840 | Craft::info( |
||
| 841 | 'Deleted variant: '.$variantPath, |
||
| 842 | __METHOD__ |
||
| 843 | ); |
||
| 844 | } |
||
| 845 | } |
||
| 846 | } |
||
| 847 | } |
||
| 848 | } |
||
| 849 | |||
| 850 | /** |
||
| 851 | * @param $variantCreatorCommand |
||
| 852 | * @param Asset $asset |
||
| 853 | * @param AssetTransformIndex $index |
||
| 854 | * @param $outputPath |
||
| 855 | */ |
||
| 856 | protected function copyImageVariantToVolume( |
||
| 919 | ); |
||
| 920 | } |
||
| 921 | } |
||
| 922 | |||
| 923 | /** |
||
| 924 | * @param string $path |
||
| 925 | * @param string $extension |
||
| 926 | * |
||
| 927 | * @return string |
||
| 928 | */ |
||
| 929 | protected function swapPathExtension(string $path, string $extension): string |
||
| 939 | } |
||
| 940 | } |
||
| 941 |