| Total Complexity | 104 |
| Total Lines | 870 |
| Duplicated Lines | 0 % |
| Changes | 11 | ||
| Bugs | 4 | 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 |
||
| 55 | class Optimize extends Component |
||
| 56 | { |
||
| 57 | // Constants |
||
| 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 | * @var string |
||
| 79 | */ |
||
| 80 | public const EVENT_REGISTER_IMAGE_TRANSFORM_TYPES = 'registerImageTransformTypes'; |
||
| 81 | |||
| 82 | /** |
||
| 83 | * @var array<class-string<Configurable>> |
||
| 84 | */ |
||
| 85 | public const DEFAULT_IMAGE_TRANSFORM_TYPES = [ |
||
| 86 | CraftImageTransform::class, |
||
| 87 | ImgixImageTransform::class, |
||
| 88 | SharpImageTransform::class, |
||
| 89 | ThumborImageTransform::class, |
||
| 90 | ]; |
||
| 91 | |||
| 92 | // Public Methods |
||
| 93 | // ========================================================================= |
||
| 94 | |||
| 95 | /** |
||
| 96 | * Returns all available field type classes. |
||
| 97 | * |
||
| 98 | * @return string[] The available field type classes |
||
| 99 | */ |
||
| 100 | public function getAllImageTransformTypes(): array |
||
| 101 | { |
||
| 102 | $imageTransformTypes = array_unique(array_merge( |
||
| 103 | ImageOptimize::$plugin->getSettings()->defaultImageTransformTypes ?? [], |
||
| 104 | self::DEFAULT_IMAGE_TRANSFORM_TYPES |
||
| 105 | ), SORT_REGULAR); |
||
| 106 | |||
| 107 | $event = new RegisterComponentTypesEvent([ |
||
| 108 | 'types' => $imageTransformTypes, |
||
| 109 | ]); |
||
| 110 | $this->trigger(self::EVENT_REGISTER_IMAGE_TRANSFORM_TYPES, $event); |
||
| 111 | |||
| 112 | return $event->types; |
||
| 113 | } |
||
| 114 | |||
| 115 | /** |
||
| 116 | * Creates an Image Transform with a given config. |
||
| 117 | * |
||
| 118 | * @param string|array $config The Image Transform’s class name, or its config, |
||
| 119 | * with a `type` value and optionally a `settings` value |
||
| 120 | * |
||
| 121 | * @return ?ImageTransformInterface The Image Transform |
||
| 122 | */ |
||
| 123 | public function createImageTransformType(string|array $config): ?ImageTransformInterface |
||
| 124 | { |
||
| 125 | if (is_string($config)) { |
||
| 126 | $config = ['type' => $config]; |
||
| 127 | } |
||
| 128 | |||
| 129 | try { |
||
| 130 | /** @var ImageTransform $imageTransform */ |
||
| 131 | $imageTransform = ComponentHelper::createComponent($config, ImageTransformInterface::class); |
||
| 132 | } catch (Throwable $e) { |
||
| 133 | $imageTransform = null; |
||
| 134 | Craft::error($e->getMessage(), __METHOD__); |
||
| 135 | } |
||
| 136 | |||
| 137 | return $imageTransform; |
||
| 138 | } |
||
| 139 | |||
| 140 | /** |
||
| 141 | * Handle responding to EVENT_GET_ASSET_URL events |
||
| 142 | * |
||
| 143 | * @param DefineAssetUrlEvent $event |
||
| 144 | * |
||
| 145 | * @return ?string |
||
| 146 | */ |
||
| 147 | public function handleGetAssetUrlEvent(DefineAssetUrlEvent $event): ?string |
||
| 148 | { |
||
| 149 | Craft::beginProfile('handleGetAssetUrlEvent', __METHOD__); |
||
| 150 | $url = null; |
||
| 151 | if (!ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform) { |
||
| 152 | $asset = $event->asset; |
||
| 153 | $transform = $event->transform; |
||
| 154 | // If the transform is empty in some regard, normalize it to null |
||
| 155 | if (empty($transform)) { |
||
| 156 | $transform = null; |
||
| 157 | } |
||
| 158 | // If there's no transform requested, return `null` so other plugins have a crack at it |
||
| 159 | if ($transform === null) { |
||
| 160 | return null; |
||
| 161 | } |
||
| 162 | // If we're passed in null, make a dummy AssetTransform model for Thumbor |
||
| 163 | // For backwards compatibility |
||
| 164 | if (ImageOptimize::$plugin->transformMethod instanceof ThumborImageTransform) { |
||
| 165 | $transform = new AssetTransform([ |
||
| 166 | 'width' => $asset->width, |
||
| 167 | 'interlace' => 'line', |
||
| 168 | ]); |
||
| 169 | } |
||
| 170 | // If we're passed an array, make an AssetTransform model out of it |
||
| 171 | if (is_array($transform)) { |
||
| 172 | $transform = new AssetTransform($transform); |
||
| 173 | } |
||
| 174 | // If we're passing in a string, look up the asset transform in the db |
||
| 175 | if (is_string($transform)) { |
||
| 176 | $imageTransforms = Craft::$app->getImageTransforms(); |
||
| 177 | $transform = $imageTransforms->getTransformByHandle($transform); |
||
| 178 | } |
||
| 179 | $finalFormat = empty($transform['format']) ? $asset->getExtension() : $transform['format']; |
||
| 180 | // Normalize the extension to lowercase, for some transform methods that require this |
||
| 181 | $finalFormat = strtolower($finalFormat); |
||
| 182 | // Special-case for 'jpeg' |
||
| 183 | if ($finalFormat === 'jpeg') { |
||
| 184 | $finalFormat = 'jpg'; |
||
| 185 | } |
||
| 186 | // If the final format is an SVG, don't attempt to transform it |
||
| 187 | if ($finalFormat === 'svg') { |
||
| 188 | return null; |
||
| 189 | } |
||
| 190 | // Normalize the extension to lowercase, for some transform methods that require this |
||
| 191 | if (!empty($transform) && !empty($finalFormat)) { |
||
| 192 | $format = $transform['format'] ?? null; |
||
| 193 | $transform['format'] = $format === null ? null : strtolower($finalFormat); |
||
| 194 | } |
||
| 195 | // Generate an image transform url |
||
| 196 | $url = ImageOptimize::$plugin->transformMethod->getTransformUrl( |
||
| 197 | $asset, |
||
| 198 | $transform |
||
| 199 | ); |
||
| 200 | } |
||
| 201 | Craft::endProfile('handleGetAssetUrlEvent', __METHOD__); |
||
| 202 | |||
| 203 | return $url; |
||
| 204 | } |
||
| 205 | |||
| 206 | /** |
||
| 207 | * Handle responding to EVENT_GET_ASSET_THUMB_URL events |
||
| 208 | * |
||
| 209 | * @param DefineAssetThumbUrlEvent $event |
||
| 210 | * |
||
| 211 | * @return ?string |
||
| 212 | */ |
||
| 213 | public function handleGetAssetThumbUrlEvent(DefineAssetThumbUrlEvent $event): ?string |
||
| 214 | { |
||
| 215 | Craft::beginProfile('handleGetAssetThumbUrlEvent', __METHOD__); |
||
| 216 | $url = $event->url; |
||
| 217 | if (!ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform) { |
||
| 218 | $asset = $event->asset; |
||
| 219 | if (ImageHelper::canManipulateAsImage($asset->getExtension())) { |
||
| 220 | $transform = new AssetTransform([ |
||
| 221 | 'width' => $event->width, |
||
| 222 | 'height' => $event->height, |
||
| 223 | 'interlace' => 'line', |
||
| 224 | ]); |
||
| 225 | /** @var ImageTransform $transformMethod */ |
||
| 226 | $transformMethod = ImageOptimize::$plugin->transformMethod; |
||
| 227 | $finalFormat = empty($transform['format']) ? $asset->getExtension() : $transform['format']; |
||
| 228 | // Normalize the extension to lowercase, for some transform methods that require this |
||
| 229 | $finalFormat = strtolower($finalFormat); |
||
| 230 | // Special-case for 'jpeg' |
||
| 231 | if ($finalFormat === 'jpeg') { |
||
| 232 | $finalFormat = 'jpg'; |
||
| 233 | } |
||
| 234 | // If the final format is an SVG, don't attempt to transform it |
||
| 235 | if ($finalFormat === 'svg') { |
||
| 236 | return null; |
||
| 237 | } |
||
| 238 | // Generate an image transform url |
||
| 239 | if ($transformMethod->hasProperty('generateTransformsBeforePageLoad')) { |
||
| 240 | // This is a dynamic property that some image transforms have |
||
| 241 | /** @phpstan-ignore-next-line */ |
||
| 242 | $transformMethod->generateTransformsBeforePageLoad = true; |
||
| 243 | } |
||
| 244 | $url = $transformMethod->getTransformUrl($asset, $transform); |
||
| 245 | } |
||
| 246 | } |
||
| 247 | Craft::endProfile('handleGetAssetThumbUrlEvent', __METHOD__); |
||
| 248 | |||
| 249 | return $url; |
||
| 250 | } |
||
| 251 | |||
| 252 | /** |
||
| 253 | * Returns whether `.webp` is a format supported by the server |
||
| 254 | * |
||
| 255 | * @return bool |
||
| 256 | */ |
||
| 257 | public function serverSupportsWebP(): bool |
||
| 258 | { |
||
| 259 | $result = false; |
||
| 260 | $variantCreators = ImageOptimize::$plugin->optimize->getActiveVariantCreators(); |
||
| 261 | foreach ($variantCreators as $variantCreator) { |
||
| 262 | if ($variantCreator['creator'] === 'cwebp' && $variantCreator['installed']) { |
||
| 263 | $result = true; |
||
| 264 | } |
||
| 265 | } |
||
| 266 | |||
| 267 | return $result; |
||
| 268 | } |
||
| 269 | |||
| 270 | /** |
||
| 271 | * Render the LazySizes fallback JS |
||
| 272 | * |
||
| 273 | * @param array $scriptAttrs |
||
| 274 | * @param array $variables |
||
| 275 | * @return string |
||
| 276 | */ |
||
| 277 | public function renderLazySizesFallbackJs(array $scriptAttrs = [], array $variables = []): string |
||
| 278 | { |
||
| 279 | $minifier = 'minify'; |
||
| 280 | $vars = array_merge([ |
||
| 281 | 'scriptSrc' => 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.0/lazysizes.min.js', |
||
| 282 | ], |
||
| 283 | $variables |
||
| 284 | ); |
||
| 285 | $content = PluginTemplateHelper::renderPluginTemplate( |
||
| 286 | 'frontend/lazysizes-fallback.twig.js', |
||
| 287 | $vars, |
||
| 288 | $minifier |
||
| 289 | ); |
||
| 290 | if ($scriptAttrs !== null) { |
||
| 291 | $attrs = array_merge([ |
||
| 292 | ], |
||
| 293 | $scriptAttrs |
||
| 294 | ); |
||
| 295 | $content = Html::tag('script', $content, $attrs); |
||
| 296 | } |
||
| 297 | |||
| 298 | return $content; |
||
| 299 | } |
||
| 300 | |||
| 301 | /** |
||
| 302 | * Render the LazySizes fallback JS |
||
| 303 | * |
||
| 304 | * @param array $scriptAttrs |
||
| 305 | * @param array $variables |
||
| 306 | * @return string |
||
| 307 | */ |
||
| 308 | public function renderLazySizesJs(array $scriptAttrs = [], array $variables = []): string |
||
| 309 | { |
||
| 310 | $minifier = 'minify'; |
||
| 311 | $vars = array_merge([ |
||
| 312 | 'scriptSrc' => 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.0/lazysizes.min.js', |
||
| 313 | ], |
||
| 314 | $variables |
||
| 315 | ); |
||
| 316 | $content = PluginTemplateHelper::renderPluginTemplate( |
||
| 317 | 'frontend/lazysizes.twig.js', |
||
| 318 | $vars, |
||
| 319 | $minifier |
||
| 320 | ); |
||
| 321 | if ($scriptAttrs !== null) { |
||
| 322 | $attrs = array_merge([ |
||
| 323 | ], |
||
| 324 | $scriptAttrs |
||
| 325 | ); |
||
| 326 | $content = Html::tag('script', $content, $attrs); |
||
| 327 | } |
||
| 328 | |||
| 329 | return $content; |
||
| 330 | } |
||
| 331 | |||
| 332 | /** |
||
| 333 | * Handle responding to EVENT_TRANSFORM_IMAGE events |
||
| 334 | * |
||
| 335 | * @param ImageTransformerOperationEvent $event |
||
| 336 | * |
||
| 337 | * @return ?string |
||
| 338 | * @throws InvalidConfigException |
||
| 339 | */ |
||
| 340 | public function handleGenerateTransformEvent(ImageTransformerOperationEvent $event): ?string |
||
| 341 | { |
||
| 342 | Craft::beginProfile('handleGenerateTransformEvent', __METHOD__); |
||
| 343 | $tempPath = null; |
||
| 344 | // Only do this for local Craft transforms |
||
| 345 | $asset = $event->asset; |
||
| 346 | |||
| 347 | if (ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform) { |
||
| 348 | // Apply any filters to the image |
||
| 349 | $imageTransformIndex = $event->imageTransformIndex; |
||
| 350 | $image = $event->image; |
||
| 351 | |||
| 352 | if ($imageTransformIndex->getTransform() !== null) { |
||
| 353 | $this->applyFiltersToImage($imageTransformIndex->getTransform(), $asset, $image); |
||
| 354 | } |
||
| 355 | // Save the transformed image to a temp file |
||
| 356 | $tempPath = $this->saveTransformToTempFile( |
||
| 357 | $imageTransformIndex, |
||
| 358 | $image |
||
| 359 | ); |
||
| 360 | $originalFileSize = @filesize($tempPath); |
||
| 361 | // Optimize the image |
||
| 362 | $this->optimizeImage( |
||
| 363 | $imageTransformIndex, |
||
| 364 | $tempPath |
||
| 365 | ); |
||
| 366 | clearstatcache(true, $tempPath); |
||
| 367 | // Log the results of the image optimization |
||
| 368 | $optimizedFileSize = @filesize($tempPath); |
||
| 369 | $message = |
||
| 370 | pathinfo($imageTransformIndex->filename, PATHINFO_FILENAME) |
||
| 371 | . '.' |
||
| 372 | . $imageTransformIndex->detectedFormat |
||
| 373 | . ' -> ' |
||
| 374 | . Craft::t('image-optimize', 'Original') |
||
| 375 | . ': ' |
||
| 376 | . $this->humanFileSize($originalFileSize, 1) |
||
| 377 | . ', ' |
||
| 378 | . Craft::t('image-optimize', 'Optimized') |
||
| 379 | . ': ' |
||
| 380 | . $this->humanFileSize($optimizedFileSize, 1) |
||
| 381 | . ' -> ' |
||
| 382 | . Craft::t('image-optimize', 'Savings') |
||
| 383 | . ': ' |
||
| 384 | . number_format(abs(100 - (($optimizedFileSize * 100) / $originalFileSize)), 1) |
||
| 385 | . '%'; |
||
| 386 | Craft::info($message, __METHOD__); |
||
| 387 | if (Craft::$app instanceof ConsoleApplication) { |
||
| 388 | echo $message . PHP_EOL; |
||
| 389 | } |
||
| 390 | // Create any image variants |
||
| 391 | $this->createImageVariants( |
||
| 392 | $imageTransformIndex, |
||
| 393 | $asset, |
||
| 394 | $tempPath, |
||
| 395 | $event->path |
||
| 396 | ); |
||
| 397 | } |
||
| 398 | Craft::endProfile('handleGenerateTransformEvent', __METHOD__); |
||
| 399 | |||
| 400 | return $tempPath; |
||
| 401 | } |
||
| 402 | |||
| 403 | /** |
||
| 404 | * Handle cleaning up any variant creator images |
||
| 405 | * |
||
| 406 | * @param ImageTransformerOperationEvent $event |
||
| 407 | */ |
||
| 408 | public function handleAfterDeleteTransformsEvent(ImageTransformerOperationEvent $event): void |
||
| 409 | { |
||
| 410 | // Only do this for local Craft transforms |
||
| 411 | if (ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform) { |
||
| 412 | $this->cleanupImageVariants($event->asset, $event->imageTransformIndex, $event->path); |
||
| 413 | } |
||
| 414 | } |
||
| 415 | |||
| 416 | /** |
||
| 417 | * Save out the image to a temp file |
||
| 418 | * |
||
| 419 | * @param AssetTransformIndex $index |
||
| 420 | * @param Image $image |
||
| 421 | * |
||
| 422 | * @return string |
||
| 423 | */ |
||
| 424 | public function saveTransformToTempFile(AssetTransformIndex $index, Image $image): string |
||
| 425 | { |
||
| 426 | $tempFilename = uniqid(pathinfo($index->filename, PATHINFO_FILENAME), true) . '.' . $index->detectedFormat; |
||
| 427 | $tempPath = Craft::$app->getPath()->getTempPath() . DIRECTORY_SEPARATOR . $tempFilename; |
||
| 428 | try { |
||
| 429 | $image->saveAs($tempPath); |
||
| 430 | } catch (ImageException $e) { |
||
| 431 | Craft::error('Transformed image save failed: ' . $e->getMessage(), __METHOD__); |
||
| 432 | } |
||
| 433 | Craft::info('Transformed image saved to: ' . $tempPath, __METHOD__); |
||
| 434 | |||
| 435 | return $tempPath; |
||
| 436 | } |
||
| 437 | |||
| 438 | /** |
||
| 439 | * Run any image post-processing/optimization on the image file |
||
| 440 | * |
||
| 441 | * @param AssetTransformIndex $index |
||
| 442 | * @param string $tempPath |
||
| 443 | */ |
||
| 444 | public function optimizeImage(AssetTransformIndex $index, string $tempPath): void |
||
| 445 | { |
||
| 446 | Craft::beginProfile('optimizeImage', __METHOD__); |
||
| 447 | /** @var Settings $settings */ |
||
| 448 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 449 | // Get the active processors for the transform format |
||
| 450 | $activeImageProcessors = $settings->activeImageProcessors; |
||
| 451 | $fileFormat = $index->detectedFormat ?? $index->format; |
||
| 452 | $fileFormat = strtolower($fileFormat); |
||
| 453 | // Special-case for 'jpeg' |
||
| 454 | if ($fileFormat === 'jpeg') { |
||
| 455 | $fileFormat = 'jpg'; |
||
| 456 | } |
||
| 457 | if (!empty($activeImageProcessors[$fileFormat])) { |
||
| 458 | // Iterate through all the processors for this format |
||
| 459 | $imageProcessors = $settings->imageProcessors; |
||
| 460 | foreach ($activeImageProcessors[$fileFormat] as $processor) { |
||
| 461 | if (!empty($processor) && !empty($imageProcessors[$processor])) { |
||
| 462 | $this->executeImageProcessor($imageProcessors[$processor], $tempPath); |
||
| 463 | } |
||
| 464 | } |
||
| 465 | } |
||
| 466 | Craft::endProfile('optimizeImage', __METHOD__); |
||
| 467 | } |
||
| 468 | |||
| 469 | /** |
||
| 470 | * Translate bytes into something human-readable |
||
| 471 | * |
||
| 472 | * @param $bytes |
||
| 473 | * @param int $decimals |
||
| 474 | * |
||
| 475 | * @return string |
||
| 476 | */ |
||
| 477 | public function humanFileSize($bytes, int $decimals = 1): string |
||
| 485 | } |
||
| 486 | |||
| 487 | /** |
||
| 488 | * Create any image variants for the image file |
||
| 489 | * |
||
| 490 | * @param AssetTransformIndex $index |
||
| 491 | * @param Asset $asset |
||
| 492 | * @param string $tempPath |
||
| 493 | * @param string $uri |
||
| 494 | */ |
||
| 495 | public function createImageVariants(AssetTransformIndex $index, Asset $asset, string $tempPath, string $uri): void |
||
| 496 | { |
||
| 497 | Craft::beginProfile('createImageVariants', __METHOD__); |
||
| 498 | /** @var Settings $settings */ |
||
| 499 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 500 | // Get the active image variant creators |
||
| 501 | $activeImageVariantCreators = $settings->activeImageVariantCreators; |
||
| 502 | $fileFormat = $index->detectedFormat ?? $index->format; |
||
| 503 | $fileFormat = strtolower($fileFormat); |
||
| 504 | // Special-case for 'jpeg' |
||
| 505 | if ($fileFormat === 'jpeg') { |
||
| 506 | $fileFormat = 'jpg'; |
||
| 507 | } |
||
| 508 | if (!empty($activeImageVariantCreators[$fileFormat])) { |
||
| 509 | // Iterate through all of the image variant creators for this format |
||
| 510 | $imageVariantCreators = $settings->imageVariantCreators; |
||
| 511 | foreach ($activeImageVariantCreators[$fileFormat] as $variantCreator) { |
||
| 512 | if (!empty($variantCreator) && !empty($imageVariantCreators[$variantCreator])) { |
||
| 513 | // Create the image variant in a temporary folder |
||
| 514 | $generalConfig = Craft::$app->getConfig()->getGeneral(); |
||
| 515 | $quality = $index->transform->quality ?: $generalConfig->defaultImageQuality; |
||
| 516 | $outputPath = $this->executeVariantCreator( |
||
| 517 | $imageVariantCreators[$variantCreator], |
||
| 518 | $tempPath, |
||
| 519 | $quality |
||
| 520 | ); |
||
| 521 | if ($outputPath !== null) { |
||
| 522 | // Get info on the original and the created variant |
||
| 523 | $originalFileSize = @filesize($tempPath); |
||
| 524 | $variantFileSize = @filesize($outputPath); |
||
| 525 | $message = |
||
| 526 | pathinfo($tempPath, PATHINFO_FILENAME) |
||
| 527 | . '.' |
||
| 528 | . pathinfo($tempPath, PATHINFO_EXTENSION) |
||
| 529 | . ' -> ' |
||
| 530 | . pathinfo($outputPath, PATHINFO_FILENAME) |
||
| 531 | . '.' |
||
| 532 | . pathinfo($outputPath, PATHINFO_EXTENSION) |
||
| 533 | . ' -> ' |
||
| 534 | . Craft::t('image-optimize', 'Original') |
||
| 535 | . ': ' |
||
| 536 | . $this->humanFileSize($originalFileSize, 1) |
||
| 537 | . ', ' |
||
| 538 | . Craft::t('image-optimize', 'Variant') |
||
| 539 | . ': ' |
||
| 540 | . $this->humanFileSize($variantFileSize, 1) |
||
| 541 | . ' -> ' |
||
| 542 | . Craft::t('image-optimize', 'Savings') |
||
| 543 | . ': ' |
||
| 544 | . number_format(abs(100 - (($variantFileSize * 100) / $originalFileSize)), 1) |
||
| 545 | . '%'; |
||
| 546 | Craft::info($message, __METHOD__); |
||
| 547 | if (Craft::$app instanceof ConsoleApplication) { |
||
| 548 | echo $message . PHP_EOL; |
||
| 549 | } |
||
| 550 | // Copy the image variant into place |
||
| 551 | $this->copyImageVariantToVolume( |
||
| 552 | $imageVariantCreators[$variantCreator], |
||
| 553 | $asset, |
||
| 554 | $index, |
||
| 555 | $outputPath, |
||
| 556 | $uri |
||
| 557 | ); |
||
| 558 | } |
||
| 559 | } |
||
| 560 | } |
||
| 561 | } |
||
| 562 | Craft::endProfile('createImageVariants', __METHOD__); |
||
| 563 | } |
||
| 564 | |||
| 565 | /** |
||
| 566 | * Return an array of active image processors |
||
| 567 | * |
||
| 568 | * @return array |
||
| 569 | */ |
||
| 570 | public function getActiveImageProcessors(): array |
||
| 596 | } |
||
| 597 | |||
| 598 | /** |
||
| 599 | * Return an array of active image variant creators |
||
| 600 | * |
||
| 601 | * @return array |
||
| 602 | */ |
||
| 603 | public function getActiveVariantCreators(): array |
||
| 629 | } |
||
| 630 | |||
| 631 | // Protected Methods |
||
| 632 | // ========================================================================= |
||
| 633 | |||
| 634 | /** @noinspection PhpUnusedParameterInspection |
||
| 635 | * @param AssetTransform $transform |
||
| 636 | * @param Asset $asset |
||
| 637 | * @param Image $image |
||
| 638 | */ |
||
| 639 | protected function applyFiltersToImage(AssetTransform $transform, Asset $asset, Image $image): void |
||
| 640 | { |
||
| 641 | /** @var Settings $settings */ |
||
| 642 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 643 | // Only try to apply filters to Raster images |
||
| 644 | if ($image instanceof Raster && $asset->getWidth() > 0 && $asset->getHeight() > 0) { |
||
| 645 | $imagineImage = $image->getImagineImage(); |
||
| 646 | // Handle auto-sharpening scaled down images |
||
| 647 | if ($imagineImage !== null && $settings->autoSharpenScaledImages) { |
||
| 648 | // See if the image has been scaled >= 50% |
||
| 649 | $widthScale = (int)(($image->getWidth() / $asset->getWidth()) * 100); |
||
| 650 | $heightScale = (int)(($image->getHeight() / $asset->getHeight()) * 100); |
||
| 651 | if (($widthScale >= $settings->sharpenScaledImagePercentage) || ($heightScale >= $settings->sharpenScaledImagePercentage)) { |
||
| 652 | $imagineImage->effects() |
||
| 653 | ->sharpen(); |
||
| 654 | Craft::debug( |
||
| 655 | Craft::t( |
||
| 656 | 'image-optimize', |
||
| 657 | 'Image transform >= 50%, sharpened the transformed image: {name}', |
||
| 658 | [ |
||
| 659 | 'name' => $asset->title, |
||
| 660 | ] |
||
| 661 | ), |
||
| 662 | __METHOD__ |
||
| 663 | ); |
||
| 664 | } |
||
| 665 | } |
||
| 666 | } |
||
| 667 | } |
||
| 668 | |||
| 669 | /** |
||
| 670 | * @param $thisProcessor |
||
| 671 | * @param string $tempPath |
||
| 672 | */ |
||
| 673 | protected function executeImageProcessor($thisProcessor, string $tempPath): void |
||
| 674 | { |
||
| 675 | // Make sure the command exists |
||
| 676 | if (is_file($thisProcessor['commandPath'])) { |
||
| 677 | // Set any options for the command |
||
| 678 | $commandOptions = ''; |
||
| 679 | if (!empty($thisProcessor['commandOptions'])) { |
||
| 680 | $commandOptions = ' ' |
||
| 681 | . $thisProcessor['commandOptions'] |
||
| 682 | . ' '; |
||
| 683 | } |
||
| 684 | // Redirect the command output if necessary for this processor |
||
| 685 | $outputFileFlag = ''; |
||
| 686 | if (!empty($thisProcessor['commandOutputFileFlag'])) { |
||
| 687 | $outputFileFlag = ' ' |
||
| 688 | . $thisProcessor['commandOutputFileFlag'] |
||
| 689 | . ' ' |
||
| 690 | . escapeshellarg($tempPath) |
||
| 691 | . ' '; |
||
| 692 | } |
||
| 693 | // If both $commandOptions & $outputFileFlag are empty, pad it with a space |
||
| 694 | if (empty($commandOptions) && empty($outputFileFlag)) { |
||
| 695 | $commandOptions = ' '; |
||
| 696 | } |
||
| 697 | // Build the command to execute |
||
| 698 | $cmd = |
||
| 699 | $thisProcessor['commandPath'] |
||
| 700 | . $commandOptions |
||
| 701 | . $outputFileFlag |
||
| 702 | . escapeshellarg($tempPath); |
||
| 703 | // Execute the command |
||
| 704 | $shellOutput = $this->executeShellCommand($cmd); |
||
| 705 | Craft::info($cmd . "\n" . $shellOutput, __METHOD__); |
||
| 706 | } else { |
||
| 707 | Craft::error( |
||
| 708 | $thisProcessor['commandPath'] |
||
| 709 | . ' ' |
||
| 710 | . Craft::t('image-optimize', 'does not exist'), |
||
| 711 | __METHOD__ |
||
| 712 | ); |
||
| 713 | } |
||
| 714 | } |
||
| 715 | |||
| 716 | /** |
||
| 717 | * Execute a shell command |
||
| 718 | * |
||
| 719 | * @param string $command |
||
| 720 | * |
||
| 721 | * @return string |
||
| 722 | */ |
||
| 723 | protected function executeShellCommand(string $command): string |
||
| 742 | } |
||
| 743 | |||
| 744 | /** |
||
| 745 | * @param $variantCreatorCommand |
||
| 746 | * @param string $tempPath |
||
| 747 | * @param int $imageQuality |
||
| 748 | * |
||
| 749 | * @return ?string the path to the created variant |
||
| 750 | */ |
||
| 751 | protected function executeVariantCreator($variantCreatorCommand, string $tempPath, int $imageQuality): ?string |
||
| 804 | } |
||
| 805 | |||
| 806 | /** |
||
| 807 | * @param Asset $asset |
||
| 808 | * @param AssetTransformIndex $transformIndex |
||
| 809 | * @param string $uri |
||
| 810 | */ |
||
| 811 | protected function cleanupImageVariants(Asset $asset, AssetTransformIndex $transformIndex, string $uri): void |
||
| 850 | ); |
||
| 851 | } |
||
| 852 | } |
||
| 853 | } |
||
| 854 | } |
||
| 855 | } |
||
| 856 | |||
| 857 | /** |
||
| 858 | * @param $variantCreatorCommand |
||
| 859 | * @param Asset $asset |
||
| 860 | * @param AssetTransformIndex $index |
||
| 861 | * @param $outputPath |
||
| 862 | * @param $uri |
||
| 863 | * @throws FsException |
||
| 864 | */ |
||
| 865 | protected function copyImageVariantToVolume( |
||
| 905 | ); |
||
| 906 | } |
||
| 907 | } |
||
| 908 | |||
| 909 | /** |
||
| 910 | * @param string $path |
||
| 911 | * @param string $extension |
||
| 912 | * |
||
| 913 | * @return string |
||
| 914 | */ |
||
| 915 | protected function swapPathExtension(string $path, string $extension): string |
||
| 925 | } |
||
| 926 | } |
||
| 927 |