Total Complexity | 59 |
Total Lines | 431 |
Duplicated Lines | 0 % |
Changes | 14 | ||
Bugs | 0 | Features | 0 |
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 |
||
38 | class OptimizedImages extends Component |
||
39 | { |
||
40 | // Constants |
||
41 | // ========================================================================= |
||
42 | |||
43 | // Public Properties |
||
44 | // ========================================================================= |
||
45 | |||
46 | // Public Methods |
||
47 | // ========================================================================= |
||
48 | |||
49 | /** |
||
50 | * @param Asset $asset |
||
51 | * @param array $variants |
||
52 | * |
||
53 | * @return OptimizedImage|null |
||
54 | */ |
||
55 | public function createOptimizedImages(Asset $asset, array $variants = []) |
||
56 | { |
||
57 | Craft::beginProfile('createOptimizedImages', __METHOD__); |
||
58 | if (empty($variants)) { |
||
59 | $settings = ImageOptimize::$plugin->getSettings(); |
||
60 | if ($settings) { |
||
61 | $variants = $settings->defaultVariants; |
||
62 | } |
||
63 | } |
||
64 | |||
65 | $model = new OptimizedImage(); |
||
66 | $this->populateOptimizedImageModel($asset, $variants, $model); |
||
67 | Craft::endProfile('createOptimizedImages', __METHOD__); |
||
68 | |||
69 | return $model; |
||
70 | } |
||
71 | |||
72 | /** |
||
73 | * @param Asset $asset |
||
74 | * @param array $variants |
||
75 | * @param OptimizedImage $model |
||
76 | */ |
||
77 | public function populateOptimizedImageModel(Asset $asset, $variants, OptimizedImage $model) |
||
78 | { |
||
79 | Craft::beginProfile('populateOptimizedImageModel', __METHOD__); |
||
80 | $settings = ImageOptimize::$plugin->getSettings(); |
||
81 | // Empty our the optimized image URLs |
||
82 | $model->optimizedImageUrls = []; |
||
83 | $model->optimizedWebPImageUrls = []; |
||
84 | $model->variantSourceWidths = []; |
||
85 | $model->placeholderWidth = 0; |
||
86 | $model->placeholderHeight = 0; |
||
87 | |||
88 | foreach ($variants as $variant) { |
||
89 | $retinaSizes = ['1']; |
||
90 | if (!empty($variant['retinaSizes'])) { |
||
91 | $retinaSizes = $variant['retinaSizes']; |
||
92 | } |
||
93 | foreach ($retinaSizes as $retinaSize) { |
||
94 | $finalFormat = empty($variant['format']) ? $asset->getExtension() : $variant['format']; |
||
95 | // Only try the transform if it's possible |
||
96 | if (Image::canManipulateAsImage($finalFormat) |
||
97 | && Image::canManipulateAsImage($asset->getExtension()) |
||
98 | && $asset->height > 0) { |
||
99 | // Create the transform based on the variant |
||
100 | list($transform, $aspectRatio) = $this->getTransformFromVariant($asset, $variant, $retinaSize); |
||
101 | // Only create the image variant if it is not upscaled, or they are okay with it being up-scaled |
||
102 | if (($asset->width >= $transform->width && $asset->height >= $transform->height) |
||
103 | || $settings->allowUpScaledImageVariants |
||
104 | ) { |
||
105 | $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio); |
||
106 | } |
||
107 | } else { |
||
108 | Craft::error( |
||
109 | 'Could not create transform for: '.$asset->title |
||
110 | .' - Final format: '.$finalFormat |
||
111 | .' - Element extension: '.$asset->getExtension() |
||
112 | .' - canManipulateAsImage: '.Image::canManipulateAsImage($asset->getExtension()), |
||
113 | __METHOD__ |
||
114 | ); |
||
115 | } |
||
116 | } |
||
117 | } |
||
118 | |||
119 | // If no image variants were created, populate it with the image itself |
||
120 | if (empty($model->optimizedImageUrls)) { |
||
121 | $finalFormat = $asset->getExtension(); |
||
122 | if (Image::canManipulateAsImage($finalFormat) |
||
123 | && Image::canManipulateAsImage($finalFormat) |
||
124 | && $asset->height > 0) { |
||
125 | $variant = [ |
||
126 | 'width' => $asset->width, |
||
127 | 'useAspectRatio' => false, |
||
128 | 'aspectRatioX' => $asset->width, |
||
129 | 'aspectRatioY' => $asset->height, |
||
130 | 'retinaSizes' => ['1'], |
||
131 | 'quality' => 0, |
||
132 | ]; |
||
133 | list($transform, $aspectRatio) = $this->getTransformFromVariant($asset, $variant, 1); |
||
134 | $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio); |
||
135 | } else { |
||
136 | Craft::error( |
||
137 | 'Could not create transform for: '.$asset->title |
||
138 | .' - Final format: '.$finalFormat |
||
139 | .' - Element extension: '.$asset->getExtension() |
||
140 | .' - canManipulateAsImage: '.Image::canManipulateAsImage($asset->getExtension()), |
||
141 | __METHOD__ |
||
142 | ); |
||
143 | } |
||
144 | } |
||
145 | Craft::endProfile('populateOptimizedImageModel', __METHOD__); |
||
146 | } |
||
147 | |||
148 | // Protected Methods |
||
149 | // ========================================================================= |
||
150 | |||
151 | /** |
||
152 | * @param Field $field |
||
153 | * @param ElementInterface $asset |
||
154 | * |
||
155 | * @throws \yii\db\Exception |
||
156 | * @throws InvalidConfigException |
||
157 | */ |
||
158 | public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset) |
||
159 | { |
||
160 | /** @var Asset $asset */ |
||
161 | if ($asset instanceof Asset && $field instanceof OptimizedImagesField) { |
||
162 | $createVariants = true; |
||
163 | Craft::info(print_r($field->fieldVolumeSettings, true), __METHOD__); |
||
164 | // See if we're ignoring files in this dir |
||
165 | if (!empty($field->fieldVolumeSettings)) { |
||
166 | foreach ($field->fieldVolumeSettings as $volumeHandle => $subfolders) { |
||
167 | if ($asset->getVolume()->handle === $volumeHandle) { |
||
168 | if (is_string($subfolders) && $subfolders === '*') { |
||
169 | $createVariants = true; |
||
170 | Craft::info("Matched '*' wildcard ", __METHOD__); |
||
171 | } else { |
||
172 | $createVariants = false; |
||
173 | if (is_array($subfolders)) { |
||
174 | foreach ($subfolders as $subfolder) { |
||
175 | __METHOD__); |
||
176 | if ($asset->getFolder()->uid === $subfolder) { |
||
177 | Craft::info('Matched subfolder uid: '.print_r($subfolder, true), __METHOD__); |
||
178 | $createVariants = true; |
||
179 | } |
||
180 | } |
||
181 | } |
||
182 | } |
||
183 | } |
||
184 | } |
||
185 | } |
||
186 | // See if we should ignore this type of file |
||
187 | $sourceType = $asset->getMimeType(); |
||
188 | if (!empty($field->ignoreFilesOfType) && $sourceType !== null) { |
||
189 | if (\in_array($sourceType, array_values($field->ignoreFilesOfType), false)) { |
||
190 | $createVariants = false; |
||
191 | } |
||
192 | } |
||
193 | Craft::info(print_r($sourceType, true), 'image-optimize'); |
||
194 | // Create a new OptimizedImage model and populate it |
||
195 | $model = new OptimizedImage(); |
||
196 | // Empty our the optimized image URLs |
||
197 | $model->optimizedImageUrls = []; |
||
198 | $model->optimizedWebPImageUrls = []; |
||
199 | $model->variantSourceWidths = []; |
||
200 | $model->placeholderWidth = 0; |
||
201 | $model->placeholderHeight = 0; |
||
202 | if ($asset !== null && $createVariants) { |
||
203 | $this->populateOptimizedImageModel( |
||
204 | $asset, |
||
205 | $field->variants, |
||
206 | $model |
||
207 | ); |
||
208 | } |
||
209 | // Save our field data directly into the content table |
||
210 | if ($field->handle !== null) { |
||
211 | $asset->setFieldValue($field->handle, $field->serializeValue($model)); |
||
212 | $table = $asset->getContentTable(); |
||
213 | $column = $asset->getFieldColumnPrefix().$field->handle; |
||
214 | $data = Json::encode($field->serializeValue($asset->getFieldValue($field->handle), $asset)); |
||
215 | Craft::$app->db->createCommand() |
||
216 | ->update($table, [ |
||
217 | $column => $data, |
||
218 | ], [ |
||
219 | 'elementId' => $asset->getId(), |
||
220 | ], [], false) |
||
221 | ->execute(); |
||
222 | } |
||
223 | } |
||
224 | } |
||
225 | |||
226 | /** |
||
227 | * Re-save all of the assets in all of the volumes |
||
228 | * |
||
229 | * @throws \yii\base\InvalidConfigException |
||
230 | */ |
||
231 | public function resaveAllVolumesAssets() |
||
232 | { |
||
233 | $volumes = Craft::$app->getVolumes()->getAllVolumes(); |
||
234 | foreach ($volumes as $volume) { |
||
235 | if (is_subclass_of($volume, Volume::class)) { |
||
236 | /** @var Volume $volume */ |
||
237 | $this->resaveVolumeAssets($volume); |
||
238 | } |
||
239 | } |
||
240 | } |
||
241 | |||
242 | /** |
||
243 | * Re-save all of the Asset elements in the Volume $volume that have an |
||
244 | * OptimizedImages field in the FieldLayout |
||
245 | * |
||
246 | * @param Volume $volume |
||
247 | * |
||
248 | * @throws \yii\base\InvalidConfigException |
||
249 | */ |
||
250 | public function resaveVolumeAssets(Volume $volume) |
||
251 | { |
||
252 | $needToReSave = false; |
||
253 | /** @var FieldLayout $fieldLayout */ |
||
254 | $fieldLayout = $volume->getFieldLayout(); |
||
255 | // Loop through the fields in the layout to see if there is an OptimizedImages field |
||
256 | if ($fieldLayout) { |
||
257 | $fields = $fieldLayout->getFields(); |
||
258 | foreach ($fields as $field) { |
||
259 | if ($field instanceof OptimizedImagesField) { |
||
260 | $needToReSave = true; |
||
261 | } |
||
262 | } |
||
263 | } |
||
264 | if ($needToReSave) { |
||
265 | try { |
||
266 | $siteId = Craft::$app->getSites()->getPrimarySite()->id; |
||
267 | } catch (SiteNotFoundException $e) { |
||
268 | $siteId = 0; |
||
269 | Craft::error( |
||
270 | 'Failed to get primary site: '.$e->getMessage(), |
||
271 | __METHOD__ |
||
272 | ); |
||
273 | } |
||
274 | |||
275 | $queue = Craft::$app->getQueue(); |
||
276 | $jobId = $queue->push(new ResaveOptimizedImages([ |
||
277 | 'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]), |
||
278 | 'criteria' => [ |
||
279 | 'siteId' => $siteId, |
||
280 | 'volumeId' => $volume->id, |
||
281 | 'status' => null, |
||
282 | 'enabledForSite' => false, |
||
283 | ], |
||
284 | ])); |
||
285 | Craft::debug( |
||
286 | Craft::t( |
||
287 | 'image-optimize', |
||
288 | 'Started resaveVolumeAssets queue job id: {jobId}', |
||
289 | [ |
||
290 | 'jobId' => $jobId, |
||
291 | ] |
||
292 | ), |
||
293 | __METHOD__ |
||
294 | ); |
||
295 | } |
||
296 | } |
||
297 | |||
298 | /** |
||
299 | * Re-save an individual asset |
||
300 | * |
||
301 | * @param int $id |
||
302 | */ |
||
303 | public function resaveAsset(int $id) |
||
304 | { |
||
305 | $queue = Craft::$app->getQueue(); |
||
306 | $jobId = $queue->push(new ResaveOptimizedImages([ |
||
307 | 'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]), |
||
308 | 'criteria' => [ |
||
309 | 'id' => $id, |
||
310 | 'status' => null, |
||
311 | 'enabledForSite' => false, |
||
312 | ], |
||
313 | ])); |
||
314 | Craft::debug( |
||
315 | Craft::t( |
||
316 | 'image-optimize', |
||
317 | 'Started resaveAsset queue job id: {jobId} Element id: {elementId}', |
||
318 | [ |
||
319 | 'elementId' => $id, |
||
320 | 'jobId' => $jobId, |
||
321 | ] |
||
322 | ), |
||
323 | __METHOD__ |
||
324 | ); |
||
325 | } |
||
326 | |||
327 | /** |
||
328 | * Create an optimized SVG data uri |
||
329 | * See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris |
||
330 | * |
||
331 | * @param string $uri |
||
332 | * |
||
333 | * @return string |
||
334 | */ |
||
335 | public function encodeOptimizedSVGDataUri(string $uri): string |
||
336 | { |
||
337 | // First, uri encode everything |
||
338 | $uri = rawurlencode($uri); |
||
339 | $replacements = [ |
||
340 | // remove newlines |
||
341 | '/%0A/' => '', |
||
342 | // put spaces back in |
||
343 | '/%20/' => ' ', |
||
344 | // put equals signs back in |
||
345 | '/%3D/' => '=', |
||
346 | // put colons back in |
||
347 | '/%3A/' => ':', |
||
348 | // put slashes back in |
||
349 | '/%2F/' => '/', |
||
350 | // replace quotes with apostrophes (may break certain SVGs) |
||
351 | '/%22/' => "'", |
||
352 | ]; |
||
353 | foreach ($replacements as $pattern => $replacement) { |
||
354 | $uri = preg_replace($pattern, $replacement, $uri); |
||
355 | } |
||
356 | |||
357 | return $uri; |
||
358 | } |
||
359 | |||
360 | /** |
||
361 | * @param Asset $element |
||
362 | * @param OptimizedImage $model |
||
363 | * @param $aspectRatio |
||
364 | */ |
||
365 | protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio) |
||
366 | { |
||
367 | Craft::beginProfile('generatePlaceholders', __METHOD__); |
||
368 | $settings = ImageOptimize::$plugin->getSettings(); |
||
369 | if ($settings->generatePlaceholders && ImageOptimize::$generatePlaceholders) { |
||
370 | $placeholder = ImageOptimize::$plugin->placeholder; |
||
371 | if ($element->focalPoint) { |
||
372 | $position = $element->getFocalPoint(); |
||
373 | } else { |
||
374 | $position = 'center-center'; |
||
375 | } |
||
376 | $tempPath = $placeholder->createTempPlaceholderImage($element, $aspectRatio, $position); |
||
377 | if (!empty($tempPath)) { |
||
378 | // Generate our placeholder image |
||
379 | $model->placeholder = $placeholder->generatePlaceholderImage($tempPath, $aspectRatio, $position); |
||
380 | // Generate the color palette for the image |
||
381 | if ($settings->createColorPalette) { |
||
382 | $model->colorPalette = $placeholder->generateColorPalette($tempPath); |
||
383 | $model->lightness = $placeholder->calculateLightness($model->colorPalette); |
||
384 | } |
||
385 | // Generate the Potrace SVG |
||
386 | if ($settings->createPlaceholderSilhouettes) { |
||
387 | $model->placeholderSvg = $placeholder->generatePlaceholderSvg($tempPath); |
||
388 | } |
||
389 | // Get rid of our placeholder image |
||
390 | @unlink($tempPath); |
||
391 | } |
||
392 | } |
||
393 | Craft::endProfile('generatePlaceholders', __METHOD__); |
||
394 | } |
||
395 | |||
396 | /** |
||
397 | * @param Asset $asset |
||
398 | * @param $variant |
||
399 | * @param $retinaSize |
||
400 | * |
||
401 | * @return array |
||
402 | */ |
||
403 | protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array |
||
404 | { |
||
405 | $settings = ImageOptimize::$plugin->getSettings(); |
||
406 | $transform = new AssetTransform(); |
||
407 | $transform->format = $variant['format'] ?? null; |
||
408 | // Handle animate .gif images by never changing the format |
||
409 | $images = Craft::$app->getImages(); |
||
410 | if ($asset->extension === 'gif' && !$images->getIsGd()) { |
||
411 | $imageSource = $asset->getTransformSource(); |
||
412 | try { |
||
413 | if (ImageHelper::getIsAnimatedGif($imageSource)) { |
||
414 | $transform->format = null; |
||
415 | } |
||
416 | } catch (ImageException $e) { |
||
417 | Craft::error($e->getMessage(), __METHOD__); |
||
418 | } catch (InvalidConfigException $e) { |
||
419 | Craft::error($e->getMessage(), __METHOD__); |
||
420 | } |
||
421 | } |
||
422 | $useAspectRatio = $variant['useAspectRatio'] ?? true; |
||
423 | if ($useAspectRatio) { |
||
424 | $aspectRatio = $variant['aspectRatioX'] / $variant['aspectRatioY']; |
||
425 | } else { |
||
426 | $aspectRatio = $asset->width / $asset->height; |
||
427 | } |
||
428 | $width = $variant['width'] * $retinaSize; |
||
429 | $transform->width = $width; |
||
430 | $transform->height = (int)($width / $aspectRatio); |
||
431 | // Image quality |
||
432 | $quality = $variant['quality'] ?? null; |
||
433 | if ($settings->lowerQualityRetinaImageVariants && $retinaSize != '1') { |
||
434 | $quality = (int)($quality * (1.5 / (int)$retinaSize)); |
||
435 | } |
||
436 | $transform->quality = $quality; |
||
437 | // Interlaced (progressive JPEGs or interlaced PNGs) |
||
438 | if (property_exists($transform, 'interlace')) { |
||
439 | $transform->interlace = 'line'; |
||
440 | } |
||
441 | |||
442 | return [$transform, $aspectRatio]; |
||
443 | } |
||
444 | |||
445 | /** |
||
446 | * @param Asset $asset |
||
447 | * @param OptimizedImage $model |
||
448 | * @param $transform |
||
449 | * @param $variant |
||
450 | * @param $aspectRatio |
||
451 | */ |
||
452 | protected function addVariantImageToModel(Asset $asset, OptimizedImage $model, $transform, $variant, $aspectRatio) |
||
453 | { |
||
454 | Craft::beginProfile('addVariantImageToModel', __METHOD__); |
||
455 | // Generate an image transform url |
||
456 | $url = ImageOptimize::$plugin->transformMethod->getTransformUrl( |
||
457 | $asset, |
||
458 | $transform |
||
459 | ); |
||
460 | Craft::info( |
||
461 | 'URL created: '.print_r($url, true), |
||
462 | __METHOD__ |
||
463 | ); |
||
464 | // Update the model |
||
465 | if (!empty($url)) { |
||
466 | $model->variantSourceWidths[] = $variant['width']; |
||
467 | $model->variantHeights[$transform->width] = $asset->getHeight($transform); |
||
468 | // Store & prefetch image at the image URL |
||
469 | //ImageOptimize::$plugin->transformMethod->prefetchRemoteFile($url); |
||
496 |