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