Total Complexity | 100 |
Total Lines | 828 |
Duplicated Lines | 0 % |
Changes | 23 | ||
Bugs | 0 | 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 |
||
53 | class Optimize extends Component |
||
54 | { |
||
55 | // Constants |
||
56 | // ========================================================================= |
||
57 | |||
58 | /** |
||
59 | * @event RegisterComponentTypesEvent The event that is triggered when registering |
||
60 | * Image Transform types |
||
61 | * |
||
62 | * Image Transform types must implement [[ImageTransformInterface]]. [[ImageTransform]] |
||
63 | * provides a base implementation. |
||
64 | * |
||
65 | * ```php |
||
66 | * use nystudio107\imageoptimize\services\Optimize; |
||
67 | * use craft\events\RegisterComponentTypesEvent; |
||
68 | * use yii\base\Event; |
||
69 | * |
||
70 | * Event::on(Optimize::class, |
||
71 | * Optimize::EVENT_REGISTER_IMAGE_TRANSFORM_TYPES, |
||
72 | * function(RegisterComponentTypesEvent $event) { |
||
73 | * $event->types[] = MyImageTransform::class; |
||
74 | * } |
||
75 | * ); |
||
76 | * ``` |
||
77 | */ |
||
78 | const EVENT_REGISTER_IMAGE_TRANSFORM_TYPES = 'registerImageTransformTypes'; |
||
79 | |||
80 | const DEFAULT_IMAGE_TRANSFORM_TYPES = [ |
||
81 | CraftImageTransform::class, |
||
82 | ImgixImageTransform::class, |
||
83 | SharpImageTransform::class, |
||
84 | ThumborImageTransform::class, |
||
85 | ]; |
||
86 | |||
87 | // Public Methods |
||
88 | // ========================================================================= |
||
89 | |||
90 | /** |
||
91 | * Returns all available field type classes. |
||
92 | * |
||
93 | * @return string[] The available field type classes |
||
94 | */ |
||
95 | public function getAllImageTransformTypes(): array |
||
96 | { |
||
97 | $imageTransformTypes = array_unique(array_merge( |
||
98 | ImageOptimize::$plugin->getSettings()->defaultImageTransformTypes ?? [], |
||
99 | self::DEFAULT_IMAGE_TRANSFORM_TYPES |
||
100 | ), SORT_REGULAR); |
||
101 | |||
102 | $event = new RegisterComponentTypesEvent([ |
||
103 | 'types' => $imageTransformTypes |
||
104 | ]); |
||
105 | $this->trigger(self::EVENT_REGISTER_IMAGE_TRANSFORM_TYPES, $event); |
||
106 | |||
107 | return $event->types; |
||
108 | } |
||
109 | |||
110 | /** |
||
111 | * Creates an Image Transform with a given config. |
||
112 | * |
||
113 | * @param mixed $config The Image Transform’s class name, or its config, |
||
114 | * with a `type` value and optionally a `settings` value |
||
115 | * |
||
116 | * @return null|ImageTransformInterface The Image Transform |
||
117 | */ |
||
118 | public function createImageTransformType($config): ImageTransformInterface |
||
119 | { |
||
120 | if (is_string($config)) { |
||
121 | $config = ['type' => $config]; |
||
122 | } |
||
123 | |||
124 | try { |
||
125 | /** @var ImageTransform $imageTransform */ |
||
126 | $imageTransform = ComponentHelper::createComponent($config, ImageTransformInterface::class); |
||
127 | } catch (\Throwable $e) { |
||
128 | $imageTransform = null; |
||
129 | Craft::error($e->getMessage(), __METHOD__); |
||
130 | } |
||
131 | |||
132 | return $imageTransform; |
||
133 | } |
||
134 | |||
135 | /** |
||
136 | * Handle responding to EVENT_GET_ASSET_URL events |
||
137 | * |
||
138 | * @param GetAssetUrlEvent $event |
||
139 | * |
||
140 | * @return null|string |
||
141 | * @throws InvalidConfigException |
||
142 | */ |
||
143 | public function handleGetAssetUrlEvent(GetAssetUrlEvent $event) |
||
144 | { |
||
145 | Craft::beginProfile('handleGetAssetUrlEvent', __METHOD__); |
||
146 | $url = null; |
||
147 | if (!ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform) { |
||
148 | $asset = $event->asset; |
||
149 | $transform = $event->transform; |
||
150 | // If the transform is empty in some regard, normalize it to null |
||
151 | if (empty($transform)) { |
||
152 | $transform = null; |
||
153 | } |
||
154 | // If there's no transform requested, and we can't manipulate the image anyway, just return the URL |
||
155 | if ($transform === null |
||
156 | && !ImageHelper::canManipulateAsImage(pathinfo($asset->filename, PATHINFO_EXTENSION))) { |
||
157 | $volume = $asset->getVolume(); |
||
158 | |||
159 | return AssetsHelper::generateUrl($volume, $asset); |
||
160 | } |
||
161 | // If we're passed in null, make a dummy AssetTransform model for Thumbor |
||
162 | // For backwards compatibility |
||
163 | if ($transform === null && ImageOptimize::$plugin->transformMethod instanceof ThumborImageTransform) { |
||
164 | $transform = new AssetTransform([ |
||
165 | 'width' => $asset->width, |
||
166 | 'interlace' => 'line', |
||
167 | ]); |
||
168 | } |
||
169 | // If we're passed an array, make an AssetTransform model out of it |
||
170 | if (\is_array($transform)) { |
||
171 | $transform = new AssetTransform($transform); |
||
172 | } |
||
173 | // If we're passing in a string, look up the asset transform in the db |
||
174 | if (\is_string($transform)) { |
||
175 | $assetTransforms = Craft::$app->getAssetTransforms(); |
||
176 | $transform = $assetTransforms->getTransformByHandle($transform); |
||
177 | } |
||
178 | // If the final format is an SVG, don't attempt to transform it |
||
179 | $finalFormat = empty($transform['format']) ? $asset->getExtension() : $transform['format']; |
||
180 | if ($finalFormat === 'svg') { |
||
181 | return null; |
||
182 | } |
||
183 | // Normalize the extension to lowercase, for some transform methods that require this |
||
184 | if (!empty($transform) && !empty($finalFormat)) { |
||
185 | $format = $transform['format'] ?? null; |
||
186 | $transform['format'] = $format === null ? null : strtolower($finalFormat); |
||
187 | } |
||
188 | // Generate an image transform url |
||
189 | $url = ImageOptimize::$plugin->transformMethod->getTransformUrl( |
||
190 | $asset, |
||
191 | $transform |
||
192 | ); |
||
193 | } |
||
194 | Craft::endProfile('handleGetAssetUrlEvent', __METHOD__); |
||
195 | |||
196 | return $url; |
||
197 | } |
||
198 | |||
199 | /** |
||
200 | * Handle responding to EVENT_GET_ASSET_THUMB_URL events |
||
201 | * |
||
202 | * @param GetAssetThumbUrlEvent $event |
||
203 | * |
||
204 | * @return null|string |
||
205 | */ |
||
206 | public function handleGetAssetThumbUrlEvent(GetAssetThumbUrlEvent $event) |
||
207 | { |
||
208 | Craft::beginProfile('handleGetAssetThumbUrlEvent', __METHOD__); |
||
209 | $url = $event->url; |
||
210 | if (!ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform) { |
||
211 | $asset = $event->asset; |
||
212 | if (ImageHelper::canManipulateAsImage($asset->getExtension())) { |
||
213 | $transform = new AssetTransform([ |
||
214 | 'width' => $event->width, |
||
215 | 'height' => $event->height, |
||
216 | 'interlace' => 'line', |
||
217 | ]); |
||
218 | /** @var ImageTransform $transformMethod */ |
||
219 | $transformMethod = ImageOptimize::$plugin->transformMethod; |
||
220 | // If the final format is an SVG, don't attempt to transform it |
||
221 | $finalFormat = empty($transform['format']) ? $asset->getExtension() : $transform['format']; |
||
222 | if ($finalFormat === 'svg') { |
||
223 | return null; |
||
224 | } |
||
225 | // Normalize the extension to lowercase, for some transform methods that require this |
||
226 | if ($transform !== null && !empty($finalFormat)) { |
||
227 | $transform['format'] = strtolower($finalFormat); |
||
228 | } |
||
229 | // Generate an image transform url |
||
230 | if ($transformMethod->hasProperty('generateTransformsBeforePageLoad')) { |
||
231 | $transformMethod->generateTransformsBeforePageLoad = $event->generate; |
||
232 | } |
||
233 | $url = $transformMethod->getTransformUrl($asset, $transform); |
||
234 | } |
||
235 | } |
||
236 | Craft::endProfile('handleGetAssetThumbUrlEvent', __METHOD__); |
||
237 | |||
238 | return $url; |
||
239 | } |
||
240 | |||
241 | /** |
||
242 | * Render the lazy load JavaScript shim |
||
243 | * |
||
244 | * @param array $scriptAttrs |
||
245 | * @param array $variables |
||
246 | * @return string |
||
247 | */ |
||
248 | public function renderLazyLoadJs($scriptAttrs = [], $variables = []) |
||
249 | { |
||
250 | $minifier = 'minify'; |
||
251 | if ($scriptAttrs === null) { |
||
252 | $minifier = 'jsMin'; |
||
253 | } |
||
254 | $vars = array_merge([ |
||
255 | 'scriptSrc' => 'https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.0/lazysizes.min.js', |
||
256 | ], |
||
257 | $variables, |
||
258 | ); |
||
259 | $content = PluginTemplateHelper::renderPluginTemplate( |
||
260 | 'frontend/lazyload-image-shim', |
||
261 | $vars, |
||
262 | $minifier |
||
263 | ); |
||
264 | $content = (string)$content; |
||
265 | if ($scriptAttrs !== null) { |
||
266 | $attrs = array_merge([ |
||
267 | ], |
||
268 | $scriptAttrs, |
||
269 | ); |
||
270 | $content = Html::tag('script', $content, $scriptAttrs); |
||
271 | } |
||
272 | |||
273 | return $content; |
||
274 | } |
||
275 | |||
276 | /** |
||
277 | * Handle responding to EVENT_GENERATE_TRANSFORM events |
||
278 | * |
||
279 | * @param GenerateTransformEvent $event |
||
280 | * |
||
281 | * @return null|string |
||
282 | */ |
||
283 | public function handleGenerateTransformEvent(GenerateTransformEvent $event) |
||
284 | { |
||
285 | Craft::beginProfile('handleGenerateTransformEvent', __METHOD__); |
||
286 | $tempPath = null; |
||
287 | |||
288 | // Only do this for local Craft transforms |
||
289 | if (ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform && $event->asset !== null) { |
||
290 | // Apply any filters to the image |
||
291 | if ($event->transformIndex->transform !== null) { |
||
292 | $this->applyFiltersToImage($event->transformIndex->transform, $event->asset, $event->image); |
||
293 | } |
||
294 | // Save the transformed image to a temp file |
||
295 | $tempPath = $this->saveTransformToTempFile( |
||
296 | $event->transformIndex, |
||
297 | $event->image |
||
298 | ); |
||
299 | $originalFileSize = @filesize($tempPath); |
||
300 | // Optimize the image |
||
301 | $this->optimizeImage( |
||
302 | $event->transformIndex, |
||
303 | $tempPath |
||
304 | ); |
||
305 | clearstatcache(true, $tempPath); |
||
306 | // Log the results of the image optimization |
||
307 | $optimizedFileSize = @filesize($tempPath); |
||
308 | $index = $event->transformIndex; |
||
309 | Craft::info( |
||
310 | pathinfo($index->filename, PATHINFO_FILENAME) |
||
311 | .'.' |
||
312 | .$index->detectedFormat |
||
313 | .' -> ' |
||
314 | .Craft::t('image-optimize', 'Original') |
||
315 | .': ' |
||
316 | .$this->humanFileSize($originalFileSize, 1) |
||
317 | .', ' |
||
318 | .Craft::t('image-optimize', 'Optimized') |
||
319 | .': ' |
||
320 | .$this->humanFileSize($optimizedFileSize, 1) |
||
321 | .' -> ' |
||
322 | .Craft::t('image-optimize', 'Savings') |
||
323 | .': ' |
||
324 | .number_format(abs(100 - (($optimizedFileSize * 100) / $originalFileSize)), 1) |
||
325 | .'%', |
||
326 | __METHOD__ |
||
327 | ); |
||
328 | // Create any image variants |
||
329 | $this->createImageVariants( |
||
330 | $event->transformIndex, |
||
331 | $event->asset, |
||
332 | $tempPath |
||
333 | ); |
||
334 | } |
||
335 | Craft::endProfile('handleGenerateTransformEvent', __METHOD__); |
||
336 | |||
337 | return $tempPath; |
||
338 | } |
||
339 | |||
340 | /** |
||
341 | * Handle cleaning up any variant creator images |
||
342 | * |
||
343 | * @param AssetTransformImageEvent $event |
||
344 | */ |
||
345 | public function handleAfterDeleteTransformsEvent(AssetTransformImageEvent $event) |
||
346 | { |
||
347 | $settings = ImageOptimize::$plugin->getSettings(); |
||
348 | // Only do this for local Craft transforms |
||
349 | if (ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform && $event->asset !== null) { |
||
350 | $this->cleanupImageVariants($event->asset, $event->transformIndex); |
||
351 | } |
||
352 | } |
||
353 | |||
354 | /** |
||
355 | * Save out the image to a temp file |
||
356 | * |
||
357 | * @param AssetTransformIndex $index |
||
358 | * @param Image $image |
||
359 | * |
||
360 | * @return string |
||
361 | */ |
||
362 | public function saveTransformToTempFile(AssetTransformIndex $index, Image $image): string |
||
363 | { |
||
364 | $tempFilename = uniqid(pathinfo($index->filename, PATHINFO_FILENAME), true).'.'.$index->detectedFormat; |
||
365 | $tempPath = Craft::$app->getPath()->getTempPath().DIRECTORY_SEPARATOR.$tempFilename; |
||
366 | try { |
||
367 | $image->saveAs($tempPath); |
||
368 | } catch (ImageException $e) { |
||
369 | Craft::error('Transformed image save failed: '.$e->getMessage(), __METHOD__); |
||
370 | } |
||
371 | Craft::info('Transformed image saved to: '.$tempPath, __METHOD__); |
||
372 | |||
373 | return $tempPath; |
||
374 | } |
||
375 | |||
376 | /** |
||
377 | * Run any image post-processing/optimization on the image file |
||
378 | * |
||
379 | * @param AssetTransformIndex $index |
||
380 | * @param string $tempPath |
||
381 | */ |
||
382 | public function optimizeImage(AssetTransformIndex $index, string $tempPath) |
||
383 | { |
||
384 | Craft::beginProfile('optimizeImage', __METHOD__); |
||
385 | $settings = ImageOptimize::$plugin->getSettings(); |
||
386 | // Get the active processors for the transform format |
||
387 | $activeImageProcessors = $settings->activeImageProcessors; |
||
388 | $fileFormat = $index->detectedFormat; |
||
389 | // Special-case for 'jpeg' |
||
390 | if ($fileFormat === 'jpeg') { |
||
391 | $fileFormat = 'jpg'; |
||
392 | } |
||
393 | if (!empty($activeImageProcessors[$fileFormat])) { |
||
394 | // Iterate through all of the processors for this format |
||
395 | $imageProcessors = $settings->imageProcessors; |
||
396 | foreach ($activeImageProcessors[$fileFormat] as $processor) { |
||
397 | if (!empty($processor) && !empty($imageProcessors[$processor])) { |
||
398 | $this->executeImageProcessor($imageProcessors[$processor], $tempPath); |
||
399 | } |
||
400 | } |
||
401 | } |
||
402 | Craft::endProfile('optimizeImage', __METHOD__); |
||
403 | } |
||
404 | |||
405 | /** |
||
406 | * Translate bytes into something human-readable |
||
407 | * |
||
408 | * @param $bytes |
||
409 | * @param int $decimals |
||
410 | * |
||
411 | * @return string |
||
412 | */ |
||
413 | public function humanFileSize($bytes, $decimals = 1): string |
||
414 | { |
||
415 | $oldSize = Craft::$app->formatter->sizeFormatBase; |
||
416 | Craft::$app->formatter->sizeFormatBase = 1000; |
||
417 | $result = Craft::$app->formatter->asShortSize($bytes, $decimals); |
||
418 | Craft::$app->formatter->sizeFormatBase = $oldSize; |
||
419 | |||
420 | return $result; |
||
421 | } |
||
422 | |||
423 | /** |
||
424 | * Create any image variants for the image file |
||
425 | * |
||
426 | * @param AssetTransformIndex $index |
||
427 | * @param Asset $asset |
||
428 | * @param string $tempPath |
||
429 | */ |
||
430 | public function createImageVariants(AssetTransformIndex $index, Asset $asset, string $tempPath) |
||
431 | { |
||
432 | Craft::beginProfile('createImageVariants', __METHOD__); |
||
433 | $settings = ImageOptimize::$plugin->getSettings(); |
||
434 | // Get the active image variant creators |
||
435 | $activeImageVariantCreators = $settings->activeImageVariantCreators; |
||
436 | $fileFormat = $index->detectedFormat ?? $index->format; |
||
437 | // Special-case for 'jpeg' |
||
438 | if ($fileFormat === 'jpeg') { |
||
439 | $fileFormat = 'jpg'; |
||
440 | } |
||
441 | if (!empty($activeImageVariantCreators[$fileFormat])) { |
||
442 | // Iterate through all of the image variant creators for this format |
||
443 | $imageVariantCreators = $settings->imageVariantCreators; |
||
444 | foreach ($activeImageVariantCreators[$fileFormat] as $variantCreator) { |
||
445 | if (!empty($variantCreator) && !empty($imageVariantCreators[$variantCreator])) { |
||
446 | // Create the image variant in a temporary folder |
||
447 | $generalConfig = Craft::$app->getConfig()->getGeneral(); |
||
448 | $quality = $index->transform->quality ?: $generalConfig->defaultImageQuality; |
||
449 | $outputPath = $this->executeVariantCreator( |
||
450 | $imageVariantCreators[$variantCreator], |
||
451 | $tempPath, |
||
452 | $quality |
||
453 | ); |
||
454 | |||
455 | if ($outputPath !== null) { |
||
456 | // Get info on the original and the created variant |
||
457 | $originalFileSize = @filesize($tempPath); |
||
458 | $variantFileSize = @filesize($outputPath); |
||
459 | |||
460 | Craft::info( |
||
461 | pathinfo($tempPath, PATHINFO_FILENAME) |
||
462 | .'.' |
||
463 | .pathinfo($tempPath, PATHINFO_EXTENSION) |
||
464 | .' -> ' |
||
465 | .pathinfo($outputPath, PATHINFO_FILENAME) |
||
466 | .'.' |
||
467 | .pathinfo($outputPath, PATHINFO_EXTENSION) |
||
468 | .' -> ' |
||
469 | .Craft::t('image-optimize', 'Original') |
||
470 | .': ' |
||
471 | .$this->humanFileSize($originalFileSize, 1) |
||
472 | .', ' |
||
473 | .Craft::t('image-optimize', 'Variant') |
||
474 | .': ' |
||
475 | .$this->humanFileSize($variantFileSize, 1) |
||
476 | .' -> ' |
||
477 | .Craft::t('image-optimize', 'Savings') |
||
478 | .': ' |
||
479 | .number_format(abs(100 - (($variantFileSize * 100) / $originalFileSize)), 1) |
||
480 | .'%', |
||
481 | __METHOD__ |
||
482 | ); |
||
483 | |||
484 | // Copy the image variant into place |
||
485 | $this->copyImageVariantToVolume( |
||
486 | $imageVariantCreators[$variantCreator], |
||
487 | $asset, |
||
488 | $index, |
||
489 | $outputPath |
||
490 | ); |
||
491 | } |
||
492 | } |
||
493 | } |
||
494 | } |
||
495 | Craft::endProfile('createImageVariants', __METHOD__); |
||
496 | } |
||
497 | |||
498 | /** |
||
499 | * Return an array of active image processors |
||
500 | * |
||
501 | * @return array |
||
502 | */ |
||
503 | public function getActiveImageProcessors(): array |
||
528 | } |
||
529 | |||
530 | /** |
||
531 | * Return an array of active image variant creators |
||
532 | * |
||
533 | * @return array |
||
534 | */ |
||
535 | public function getActiveVariantCreators(): array |
||
560 | } |
||
561 | |||
562 | // Protected Methods |
||
563 | // ========================================================================= |
||
564 | |||
565 | /** @noinspection PhpUnusedParameterInspection |
||
566 | * @param AssetTransform $transform |
||
567 | * @param Asset $asset |
||
568 | * @param Image $image |
||
569 | */ |
||
570 | |||
571 | protected function applyFiltersToImage(AssetTransform $transform, Asset $asset, Image $image) |
||
572 | { |
||
573 | $settings = ImageOptimize::$plugin->getSettings(); |
||
574 | // Only try to apply filters to Raster images |
||
575 | if ($image instanceof Raster) { |
||
576 | $imagineImage = $image->getImagineImage(); |
||
577 | if ($imagineImage !== null) { |
||
578 | // Handle auto-sharpening scaled down images |
||
579 | if ($settings->autoSharpenScaledImages) { |
||
580 | // See if the image has been scaled >= 50% |
||
581 | $widthScale = $asset->getWidth() / $image->getWidth(); |
||
582 | $heightScale = $asset->getHeight() / $image->getHeight(); |
||
583 | if (($widthScale >= 2.0) || ($heightScale >= 2.0)) { |
||
584 | $imagineImage->effects() |
||
585 | ->sharpen(); |
||
586 | Craft::debug( |
||
587 | Craft::t( |
||
588 | 'image-optimize', |
||
589 | 'Image transform >= 50%, sharpened the transformed image: {name}', |
||
590 | [ |
||
591 | 'name' => $asset->title, |
||
592 | ] |
||
593 | ), |
||
594 | __METHOD__ |
||
595 | ); |
||
596 | } |
||
597 | } |
||
598 | } |
||
599 | } |
||
600 | } |
||
601 | |||
602 | /** |
||
603 | * @param string $tempPath |
||
604 | * @param $thisProcessor |
||
605 | */ |
||
606 | protected function executeImageProcessor($thisProcessor, string $tempPath) |
||
607 | { |
||
608 | // Make sure the command exists |
||
609 | if (is_file($thisProcessor['commandPath'])) { |
||
610 | // Set any options for the command |
||
611 | $commandOptions = ''; |
||
612 | if (!empty($thisProcessor['commandOptions'])) { |
||
613 | $commandOptions = ' ' |
||
614 | .$thisProcessor['commandOptions'] |
||
615 | .' '; |
||
616 | } |
||
617 | // Redirect the command output if necessary for this processor |
||
618 | $outputFileFlag = ''; |
||
619 | if (!empty($thisProcessor['commandOutputFileFlag'])) { |
||
620 | $outputFileFlag = ' ' |
||
621 | .$thisProcessor['commandOutputFileFlag'] |
||
622 | .' ' |
||
623 | .escapeshellarg($tempPath) |
||
624 | .' '; |
||
625 | } |
||
626 | // Build the command to execute |
||
627 | $cmd = |
||
628 | $thisProcessor['commandPath'] |
||
629 | .$commandOptions |
||
630 | .$outputFileFlag |
||
631 | .escapeshellarg($tempPath); |
||
632 | // Execute the command |
||
633 | $shellOutput = $this->executeShellCommand($cmd); |
||
634 | Craft::info($cmd."\n".$shellOutput, __METHOD__); |
||
635 | } else { |
||
636 | Craft::error( |
||
637 | $thisProcessor['commandPath'] |
||
638 | .' ' |
||
639 | .Craft::t('image-optimize', 'does not exist'), |
||
640 | __METHOD__ |
||
641 | ); |
||
642 | } |
||
643 | } |
||
644 | |||
645 | /** |
||
646 | * Execute a shell command |
||
647 | * |
||
648 | * @param string $command |
||
649 | * |
||
650 | * @return string |
||
651 | */ |
||
652 | protected function executeShellCommand(string $command): string |
||
653 | { |
||
654 | // Create the shell command |
||
655 | $shellCommand = new ShellCommand(); |
||
656 | $shellCommand->setCommand($command); |
||
657 | |||
658 | // If we don't have proc_open, maybe we've got exec |
||
659 | if (!\function_exists('proc_open') && \function_exists('exec')) { |
||
660 | $shellCommand->useExec = true; |
||
661 | } |
||
662 | |||
663 | // Return the result of the command's output or error |
||
664 | if ($shellCommand->execute()) { |
||
665 | $result = $shellCommand->getOutput(); |
||
666 | } else { |
||
667 | $result = $shellCommand->getError(); |
||
668 | } |
||
669 | |||
670 | return $result; |
||
671 | } |
||
672 | |||
673 | /** |
||
674 | * @param $variantCreatorCommand |
||
675 | * @param string $tempPath |
||
676 | * @param int $imageQuality |
||
677 | * |
||
678 | * @return string|null the path to the created variant |
||
679 | */ |
||
680 | protected function executeVariantCreator($variantCreatorCommand, string $tempPath, int $imageQuality) |
||
681 | { |
||
682 | $outputPath = $tempPath; |
||
683 | // Make sure the command exists |
||
684 | if (is_file($variantCreatorCommand['commandPath'])) { |
||
685 | // Get the output file for this image variant |
||
686 | $outputPath .= '.'.$variantCreatorCommand['imageVariantExtension']; |
||
687 | // Set any options for the command |
||
688 | $commandOptions = ''; |
||
689 | if (!empty($variantCreatorCommand['commandOptions'])) { |
||
690 | $commandOptions = ' ' |
||
691 | .$variantCreatorCommand['commandOptions'] |
||
692 | .' '; |
||
693 | } |
||
694 | // Redirect the command output if necessary for this variantCreator |
||
695 | $outputFileFlag = ''; |
||
696 | if (!empty($variantCreatorCommand['commandOutputFileFlag'])) { |
||
697 | $outputFileFlag = ' ' |
||
698 | .$variantCreatorCommand['commandOutputFileFlag'] |
||
699 | .' ' |
||
700 | .escapeshellarg($outputPath) |
||
701 | .' '; |
||
702 | } |
||
703 | // Get the quality setting of this transform |
||
704 | $commandQualityFlag = ''; |
||
705 | if (!empty($variantCreatorCommand['commandQualityFlag'])) { |
||
706 | $commandQualityFlag = ' ' |
||
707 | .$variantCreatorCommand['commandQualityFlag'] |
||
708 | .' ' |
||
709 | .$imageQuality |
||
710 | .' '; |
||
711 | } |
||
712 | // Build the command to execute |
||
713 | $cmd = |
||
714 | $variantCreatorCommand['commandPath'] |
||
715 | .$commandOptions |
||
716 | .$commandQualityFlag |
||
717 | .$outputFileFlag |
||
718 | .escapeshellarg($tempPath); |
||
719 | // Execute the command |
||
720 | $shellOutput = $this->executeShellCommand($cmd); |
||
721 | Craft::info($cmd."\n".$shellOutput, __METHOD__); |
||
722 | } else { |
||
723 | Craft::error( |
||
724 | $variantCreatorCommand['commandPath'] |
||
725 | .' ' |
||
726 | .Craft::t('image-optimize', 'does not exist'), |
||
727 | __METHOD__ |
||
728 | ); |
||
729 | $outputPath = null; |
||
730 | } |
||
731 | |||
732 | return $outputPath; |
||
733 | } |
||
734 | |||
735 | /** |
||
736 | * @param Asset $asset |
||
737 | * @param AssetTransformIndex $transformIndex |
||
738 | */ |
||
739 | protected function cleanupImageVariants(Asset $asset, AssetTransformIndex $transformIndex) |
||
740 | { |
||
741 | $settings = ImageOptimize::$plugin->getSettings(); |
||
742 | $assetTransforms = Craft::$app->getAssetTransforms(); |
||
743 | // Get the active image variant creators |
||
744 | $activeImageVariantCreators = $settings->activeImageVariantCreators; |
||
745 | $fileFormat = $transformIndex->detectedFormat ?? $transformIndex->format; |
||
746 | if (!empty($activeImageVariantCreators[$fileFormat])) { |
||
747 | // Iterate through all of the image variant creators for this format |
||
748 | $imageVariantCreators = $settings->imageVariantCreators; |
||
749 | if (!empty($activeImageVariantCreators[$fileFormat])) { |
||
750 | foreach ($activeImageVariantCreators[$fileFormat] as $variantCreator) { |
||
751 | if (!empty($variantCreator) && !empty($imageVariantCreators[$variantCreator])) { |
||
752 | // Create the image variant in a temporary folder |
||
753 | $variantCreatorCommand = $imageVariantCreators[$variantCreator]; |
||
754 | try { |
||
755 | $volume = $asset->getVolume(); |
||
756 | } catch (InvalidConfigException $e) { |
||
757 | $volume = null; |
||
758 | Craft::error( |
||
759 | 'Asset volume error: '.$e->getMessage(), |
||
760 | __METHOD__ |
||
761 | ); |
||
762 | } |
||
763 | try { |
||
764 | $variantPath = $asset->getFolder()->path.$assetTransforms->getTransformSubpath( |
||
765 | $asset, |
||
766 | $transformIndex |
||
767 | ); |
||
768 | } catch (InvalidConfigException $e) { |
||
769 | $variantPath = ''; |
||
770 | Craft::error( |
||
771 | 'Asset folder does not exist: '.$e->getMessage(), |
||
772 | __METHOD__ |
||
773 | ); |
||
774 | } |
||
775 | $variantPath .= '.'.$variantCreatorCommand['imageVariantExtension']; |
||
776 | // Delete the variant file in case it is stale |
||
777 | try { |
||
778 | $volume->deleteFile($variantPath); |
||
779 | } catch (VolumeException $e) { |
||
780 | // We're fine with that. |
||
781 | } |
||
782 | Craft::info( |
||
783 | 'Deleted variant: '.$variantPath, |
||
784 | __METHOD__ |
||
785 | ); |
||
786 | } |
||
787 | } |
||
788 | } |
||
789 | } |
||
790 | } |
||
791 | |||
792 | /** |
||
793 | * @param $variantCreatorCommand |
||
794 | * @param Asset $asset |
||
795 | * @param AssetTransformIndex $index |
||
796 | * @param $outputPath |
||
797 | */ |
||
798 | protected function copyImageVariantToVolume( |
||
861 | ); |
||
862 | } |
||
863 | } |
||
864 | |||
865 | /** |
||
866 | * @param string $path |
||
867 | * @param string $extension |
||
868 | * |
||
869 | * @return string |
||
870 | */ |
||
871 | protected function swapPathExtension(string $path, string $extension): string |
||
881 | } |
||
882 | } |
||
883 |