Total Complexity | 84 |
Total Lines | 554 |
Duplicated Lines | 0 % |
Changes | 16 | ||
Bugs | 8 | Features | 2 |
Complex classes like OptimizedImages 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 OptimizedImages, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
47 | class OptimizedImages extends Component |
||
48 | { |
||
49 | // Constants |
||
50 | // ========================================================================= |
||
51 | |||
52 | // Public Properties |
||
53 | // ========================================================================= |
||
54 | |||
55 | // Public Methods |
||
56 | // ========================================================================= |
||
57 | |||
58 | /** |
||
59 | * @param Asset $asset |
||
60 | * @param array $variants |
||
61 | * |
||
62 | * @return OptimizedImage |
||
63 | * @throws InvalidConfigException |
||
64 | */ |
||
65 | public function createOptimizedImages(Asset $asset, array $variants = []): OptimizedImage |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * @param Asset $asset |
||
85 | * @param array $variants |
||
86 | * @param OptimizedImage $model |
||
87 | * @param bool $force |
||
88 | * @throws InvalidConfigException |
||
89 | */ |
||
90 | public function populateOptimizedImageModel(Asset $asset, array $variants, OptimizedImage $model, bool $force = false): void |
||
91 | { |
||
92 | Craft::beginProfile('populateOptimizedImageModel', __METHOD__); |
||
93 | /** @var Settings $settings */ |
||
94 | $settings = ImageOptimize::$plugin->getSettings(); |
||
95 | // Empty our the optimized image URLs |
||
96 | $model->optimizedImageUrls = []; |
||
97 | $model->optimizedWebPImageUrls = []; |
||
98 | $model->variantSourceWidths = []; |
||
99 | $model->placeholderWidth = 0; |
||
100 | $model->placeholderHeight = 0; |
||
101 | $model->stickyErrors = []; |
||
102 | |||
103 | foreach ($variants as $variant) { |
||
104 | $retinaSizes = ['1']; |
||
105 | if (!empty($variant['retinaSizes'])) { |
||
106 | $retinaSizes = $variant['retinaSizes']; |
||
107 | } |
||
108 | foreach ($retinaSizes as $retinaSize) { |
||
109 | $finalFormat = empty($variant['format']) ? $asset->getExtension() : $variant['format']; |
||
110 | $variantFormat = $finalFormat; |
||
111 | if (!ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform) { |
||
112 | $variantFormat = empty($variant['format']) ? null : $variant['format']; |
||
113 | } |
||
114 | $variant['format'] = $variantFormat; |
||
115 | // Only try the transform if it's possible |
||
116 | if ((int)$asset->height > 0 |
||
117 | && Image::canManipulateAsImage($finalFormat) |
||
118 | && Image::canManipulateAsImage($asset->getExtension()) |
||
119 | ) { |
||
120 | // Create the transform based on the variant |
||
121 | /** @var AssetTransform $transform */ |
||
122 | [$transform, $aspectRatio] = $this->getTransformFromVariant($asset, $variant, $retinaSize); |
||
123 | // If they want to $force it, set `fileExists` = 0 in the transform index, then delete the transformed image |
||
124 | if ($force) { |
||
125 | $transformer = Craft::createObject(ImageTransformer::class); |
||
126 | |||
127 | try { |
||
128 | $index = $transformer->getTransformIndex($asset, $transform); |
||
129 | $index->fileExists = false; |
||
130 | $transformer->storeTransformIndexData($index); |
||
131 | try { |
||
132 | $transformer->deleteImageTransformFile($asset, $index); |
||
133 | } catch (Throwable $exception) { |
||
134 | } |
||
135 | } catch (Throwable $e) { |
||
136 | $msg = 'Failed to update transform: ' . $e->getMessage(); |
||
137 | Craft::error($msg, __METHOD__); |
||
138 | if (Craft::$app instanceof ConsoleApplication) { |
||
139 | echo $msg . PHP_EOL; |
||
140 | } |
||
141 | // Add the error message to the stickyErrors for the model |
||
142 | $model->stickyErrors[] = $msg; |
||
143 | } |
||
144 | } |
||
145 | // Only create the image variant if it is not upscaled, or they are okay with it being up-scaled |
||
146 | if (($asset->width >= $transform->width && $asset->height >= $transform->height) |
||
147 | || $settings->allowUpScaledImageVariants |
||
148 | ) { |
||
149 | $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio); |
||
150 | } |
||
151 | } else { |
||
152 | $canManipulate = Image::canManipulateAsImage($asset->getExtension()); |
||
153 | $msg = 'Could not create transform for: ' . $asset->title |
||
154 | . ' - Final format: ' . $finalFormat |
||
155 | . ' - Element extension: ' . $asset->getExtension() |
||
156 | . ' - canManipulateAsImage: ' . $canManipulate; |
||
157 | Craft::error( |
||
158 | $msg, |
||
159 | __METHOD__ |
||
160 | ); |
||
161 | if (Craft::$app instanceof ConsoleApplication) { |
||
162 | echo $msg . PHP_EOL; |
||
163 | } |
||
164 | if ($canManipulate) { |
||
165 | // Add the error message to the stickyErrors for the model |
||
166 | $model->stickyErrors[] = $msg; |
||
167 | } |
||
168 | } |
||
169 | } |
||
170 | } |
||
171 | |||
172 | // If no image variants were created, populate it with the image itself |
||
173 | if (empty($model->optimizedImageUrls)) { |
||
174 | $finalFormat = $asset->getExtension(); |
||
175 | if ((int)$asset->height > 0 |
||
176 | && Image::canManipulateAsImage($finalFormat) |
||
177 | ) { |
||
178 | $variant = [ |
||
179 | 'width' => $asset->width, |
||
180 | 'useAspectRatio' => false, |
||
181 | 'aspectRatioX' => $asset->width, |
||
182 | 'aspectRatioY' => $asset->height, |
||
183 | 'retinaSizes' => ['1'], |
||
184 | 'quality' => 0, |
||
185 | 'format' => $finalFormat, |
||
186 | ]; |
||
187 | [$transform, $aspectRatio] = $this->getTransformFromVariant($asset, $variant, 1); |
||
188 | $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio); |
||
189 | } else { |
||
190 | $canManipulate = Image::canManipulateAsImage($asset->getExtension()); |
||
191 | $msg = 'Could not create transform for: ' . $asset->title |
||
192 | . ' - Final format: ' . $finalFormat |
||
193 | . ' - Element extension: ' . $asset->getExtension() |
||
194 | . ' - canManipulateAsImage: ' . $canManipulate; |
||
195 | Craft::error( |
||
196 | $msg, |
||
197 | __METHOD__ |
||
198 | ); |
||
199 | if ($canManipulate) { |
||
200 | // Add the error message to the stickyErrors for the model |
||
201 | $model->stickyErrors[] = $msg; |
||
202 | } |
||
203 | } |
||
204 | } |
||
205 | Craft::endProfile('populateOptimizedImageModel', __METHOD__); |
||
206 | } |
||
207 | |||
208 | /** |
||
209 | * Should variants be created for the given OptimizedImages field and the Asset? |
||
210 | * |
||
211 | * @param $field |
||
212 | * @param $asset |
||
213 | * @return bool |
||
214 | */ |
||
215 | public function shouldCreateVariants($field, $asset): bool |
||
258 | } |
||
259 | |||
260 | /** |
||
261 | * @param Field $field |
||
262 | * @param ElementInterface $asset |
||
263 | * @param bool $force |
||
264 | * |
||
265 | * @throws Exception |
||
266 | * @throws InvalidConfigException |
||
267 | * @throws InvalidFieldException |
||
268 | */ |
||
269 | public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset, bool $force = false): void |
||
270 | { |
||
271 | /** @var Asset $asset */ |
||
272 | if ($asset instanceof Asset && $field instanceof OptimizedImagesField) { |
||
273 | $createVariants = $this->shouldCreateVariants($field, $asset); |
||
274 | // Create a new OptimizedImage model and populate it |
||
275 | $model = new OptimizedImage(); |
||
276 | // Empty our the optimized image URLs |
||
277 | $model->optimizedImageUrls = []; |
||
278 | $model->optimizedWebPImageUrls = []; |
||
279 | $model->variantSourceWidths = []; |
||
280 | $model->placeholderWidth = 0; |
||
281 | $model->placeholderHeight = 0; |
||
282 | if ($createVariants) { |
||
283 | $this->populateOptimizedImageModel( |
||
284 | $asset, |
||
285 | $field->variants, |
||
286 | $model, |
||
287 | $force |
||
288 | ); |
||
289 | } |
||
290 | // Save the changed data directly into the elements_sites.content table |
||
291 | if ($field->handle !== null) { |
||
292 | $asset->setFieldValue($field->handle, $field->serializeValue($model, $asset)); |
||
293 | $fieldLayout = $asset->getFieldLayout(); |
||
294 | $siteSettingsRecords = Element_SiteSettingsRecord::findAll([ |
||
295 | 'elementId' => $asset->id, |
||
296 | ]); |
||
297 | // Update it for all of the sites |
||
298 | foreach ($siteSettingsRecords as $siteSettingsRecord) { |
||
299 | // Set the field values |
||
300 | if ($fieldLayout) { |
||
301 | $content = Json::decodeIfJson($siteSettingsRecord->content); |
||
302 | if (!is_array($content)) { |
||
303 | $content = []; |
||
304 | } |
||
305 | $content[$field->layoutElement->uid] = $field->serializeValue($asset->getFieldValue($field->handle), $asset); |
||
306 | $siteSettingsRecord->content = $content; |
||
307 | // Save the site settings record |
||
308 | if (!$siteSettingsRecord->save(false)) { |
||
309 | Craft::error('Couldn’t save elements’ site settings record.', __METHOD__); |
||
310 | } |
||
311 | } |
||
312 | } |
||
313 | } |
||
314 | } |
||
315 | } |
||
316 | |||
317 | /** |
||
318 | * Re-save all the assets in all the volumes |
||
319 | * |
||
320 | * @param ?int $fieldId only for this specific id |
||
321 | * @param bool $force Should image variants be forced to be recreated? |
||
322 | * |
||
323 | * @throws InvalidConfigException |
||
324 | */ |
||
325 | public function resaveAllVolumesAssets(?int $fieldId = null, bool $force = false): void |
||
326 | { |
||
327 | $volumes = Craft::$app->getVolumes()->getAllVolumes(); |
||
328 | foreach ($volumes as $volume) { |
||
329 | $this->resaveVolumeAssets($volume, $fieldId, $force); |
||
330 | } |
||
331 | } |
||
332 | |||
333 | /** |
||
334 | * Re-save all the Asset elements in the Volume $volume that have an |
||
335 | * OptimizedImages field in the FieldLayout |
||
336 | * |
||
337 | * @param Volume $volume for this volume |
||
338 | * @param ?int $fieldId only for this specific id |
||
339 | * @param bool $force Should image variants be forced to be recreated? |
||
340 | */ |
||
341 | public function resaveVolumeAssets(Volume $volume, ?int $fieldId = null, bool $force = false): void |
||
342 | { |
||
343 | $needToReSave = false; |
||
344 | /** @var ?FieldLayout $fieldLayout */ |
||
345 | $fieldLayout = $volume->getFieldLayout(); |
||
346 | // Loop through the fields in the layout to see if there is an OptimizedImages field |
||
347 | if ($fieldLayout) { |
||
348 | $fields = $fieldLayout->getCustomFields(); |
||
349 | foreach ($fields as $field) { |
||
350 | if ($field instanceof OptimizedImagesField) { |
||
351 | $needToReSave = true; |
||
352 | } |
||
353 | } |
||
354 | } |
||
355 | if ($needToReSave) { |
||
356 | try { |
||
357 | $siteId = Craft::$app->getSites()->getPrimarySite()->id; |
||
358 | } catch (SiteNotFoundException $e) { |
||
359 | $siteId = 0; |
||
360 | Craft::error( |
||
361 | 'Failed to get primary site: ' . $e->getMessage(), |
||
362 | __METHOD__ |
||
363 | ); |
||
364 | } |
||
365 | |||
366 | $queue = Craft::$app->getQueue(); |
||
367 | $jobId = $queue->push(new ResaveOptimizedImages([ |
||
368 | 'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]), |
||
369 | 'criteria' => [ |
||
370 | 'siteId' => $siteId, |
||
371 | 'volumeId' => $volume->id, |
||
372 | 'status' => null, |
||
373 | ], |
||
374 | 'fieldId' => $fieldId, |
||
375 | 'force' => $force, |
||
376 | ])); |
||
377 | Craft::debug( |
||
378 | Craft::t( |
||
379 | 'image-optimize', |
||
380 | 'Started resaveVolumeAssets queue job id: {jobId}', |
||
381 | [ |
||
382 | 'jobId' => $jobId, |
||
383 | ] |
||
384 | ), |
||
385 | __METHOD__ |
||
386 | ); |
||
387 | } |
||
388 | } |
||
389 | |||
390 | /** |
||
391 | * Re-save an individual asset |
||
392 | * |
||
393 | * @param int $id |
||
394 | * @param bool $force Should image variants be forced to be recreated? |
||
395 | */ |
||
396 | public function resaveAsset(int $id, bool $force = false): void |
||
397 | { |
||
398 | $queue = Craft::$app->getQueue(); |
||
399 | $jobId = $queue->push(new ResaveOptimizedImages([ |
||
400 | 'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]), |
||
401 | 'criteria' => [ |
||
402 | 'id' => $id, |
||
403 | 'status' => null, |
||
404 | ], |
||
405 | 'force' => $force, |
||
406 | ])); |
||
407 | Craft::debug( |
||
408 | Craft::t( |
||
409 | 'image-optimize', |
||
410 | 'Started resaveAsset queue job id: {jobId} Element id: {elementId}', |
||
411 | [ |
||
412 | 'elementId' => $id, |
||
413 | 'jobId' => $jobId, |
||
414 | ] |
||
415 | ), |
||
416 | __METHOD__ |
||
417 | ); |
||
418 | } |
||
419 | |||
420 | /** |
||
421 | * Create an optimized SVG data uri |
||
422 | * See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris |
||
423 | * |
||
424 | * @param string $uri |
||
425 | * |
||
426 | * @return string |
||
427 | */ |
||
428 | public function encodeOptimizedSVGDataUri(string $uri): string |
||
429 | { |
||
430 | // First, uri encode everything |
||
431 | $uri = rawurlencode($uri); |
||
432 | $replacements = [ |
||
433 | // remove newlines |
||
434 | '/%0A/' => '', |
||
435 | // put equals signs back in |
||
436 | '/%3D/' => '=', |
||
437 | // put colons back in |
||
438 | '/%3A/' => ':', |
||
439 | // put slashes back in |
||
440 | '/%2F/' => '/', |
||
441 | // replace quotes with apostrophes (may break certain SVGs) |
||
442 | '/%22/' => "'", |
||
443 | ]; |
||
444 | foreach ($replacements as $pattern => $replacement) { |
||
445 | $uri = preg_replace($pattern, $replacement, $uri); |
||
446 | } |
||
447 | |||
448 | return $uri; |
||
449 | } |
||
450 | |||
451 | // Protected Methods |
||
452 | // ========================================================================= |
||
453 | |||
454 | /** |
||
455 | * @param Asset $element |
||
456 | * @param OptimizedImage $model |
||
457 | * @param $aspectRatio |
||
458 | */ |
||
459 | protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio): void |
||
493 | } |
||
494 | |||
495 | /** |
||
496 | * @param Asset $asset |
||
497 | * @param $variant |
||
498 | * @param $retinaSize |
||
499 | * |
||
500 | * @return array |
||
501 | * @throws FsObjectNotFoundException |
||
502 | */ |
||
503 | protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array |
||
545 | } |
||
546 | |||
547 | /** |
||
548 | * @param Asset $asset |
||
549 | * @param OptimizedImage $model |
||
550 | * @param $transform |
||
551 | * @param $variant |
||
552 | * @param $aspectRatio |
||
553 | */ |
||
554 | protected function addVariantImageToModel(Asset $asset, OptimizedImage $model, $transform, $variant, $aspectRatio): void |
||
603 |