Total Complexity | 57 |
Total Lines | 475 |
Duplicated Lines | 0 % |
Changes | 13 | ||
Bugs | 3 | 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 |
||
45 | class OptimizedImages extends Field |
||
46 | { |
||
47 | // Constants |
||
48 | // ========================================================================= |
||
49 | |||
50 | public const DEFAULT_ASPECT_RATIOS = [ |
||
51 | ['x' => 16, 'y' => 9], |
||
52 | ]; |
||
53 | public const DEFAULT_IMAGE_VARIANTS = [ |
||
54 | [ |
||
55 | 'width' => 1200, |
||
56 | 'useAspectRatio' => true, |
||
57 | 'aspectRatioX' => 16.0, |
||
58 | 'aspectRatioY' => 9.0, |
||
59 | 'retinaSizes' => ['1'], |
||
60 | 'quality' => 82, |
||
61 | 'format' => 'jpg', |
||
62 | ], |
||
63 | ]; |
||
64 | |||
65 | public const MAX_VOLUME_SUBFOLDERS = 30; |
||
66 | |||
67 | // Public Properties |
||
68 | // ========================================================================= |
||
69 | |||
70 | /** |
||
71 | * @var array |
||
72 | */ |
||
73 | public array $fieldVolumeSettings = []; |
||
74 | |||
75 | /** |
||
76 | * @var array |
||
77 | */ |
||
78 | public array $ignoreFilesOfType = []; |
||
79 | |||
80 | /** |
||
81 | * @var bool |
||
82 | */ |
||
83 | public bool $displayOptimizedImageVariants = true; |
||
84 | |||
85 | /** |
||
86 | * @var bool |
||
87 | */ |
||
88 | public bool $displayDominantColorPalette = true; |
||
89 | |||
90 | /** |
||
91 | * @var bool |
||
92 | */ |
||
93 | public bool $displayLazyLoadPlaceholderImages = true; |
||
94 | |||
95 | /** |
||
96 | * @var array |
||
97 | */ |
||
98 | public array $variants = []; |
||
99 | |||
100 | // Private Properties |
||
101 | // ========================================================================= |
||
102 | |||
103 | /** |
||
104 | * @var array |
||
105 | */ |
||
106 | private array $aspectRatios = []; |
||
107 | |||
108 | // Static Methods |
||
109 | // ========================================================================= |
||
110 | |||
111 | /** |
||
112 | * @inheritdoc |
||
113 | */ |
||
114 | public function __construct(array $config = []) |
||
115 | { |
||
116 | // Unset any deprecated properties |
||
117 | if (!empty($config)) { |
||
118 | unset($config['transformMethod'], $config['imgixDomain']); |
||
119 | } |
||
120 | parent::__construct($config); |
||
121 | } |
||
122 | |||
123 | // Public Methods |
||
124 | // ========================================================================= |
||
125 | |||
126 | /** |
||
127 | * @inheritdoc |
||
128 | */ |
||
129 | public static function displayName(): string |
||
130 | { |
||
131 | return 'OptimizedImages'; |
||
132 | } |
||
133 | |||
134 | /** |
||
135 | * @inheritdoc |
||
136 | */ |
||
137 | public function init(): void |
||
138 | { |
||
139 | parent::init(); |
||
140 | |||
141 | // Handle cases where the plugin has been uninstalled |
||
142 | if (ImageOptimize::$plugin !== null) { |
||
143 | $settings = ImageOptimize::$plugin->getSettings(); |
||
144 | if ($settings) { |
||
145 | if (empty($this->variants)) { |
||
146 | $this->variants = $settings->defaultVariants; |
||
147 | } |
||
148 | $this->aspectRatios = $settings->defaultAspectRatios; |
||
149 | } |
||
150 | } |
||
151 | // If the user has deleted all default aspect ratios, provide a fallback |
||
152 | if (empty($this->aspectRatios)) { |
||
153 | $this->aspectRatios = self::DEFAULT_ASPECT_RATIOS; |
||
154 | } |
||
155 | // If the user has deleted all default variants, provide a fallback |
||
156 | if (empty($this->variants)) { |
||
157 | $this->variants = self::DEFAULT_IMAGE_VARIANTS; |
||
158 | } |
||
159 | } |
||
160 | |||
161 | /** |
||
162 | * @inheritdoc |
||
163 | */ |
||
164 | public function rules(): array |
||
165 | { |
||
166 | $rules = parent::rules(); |
||
167 | return array_merge($rules, [ |
||
168 | [ |
||
169 | [ |
||
170 | 'displayOptimizedImageVariants', |
||
171 | 'displayDominantColorPalette', |
||
172 | 'displayLazyLoadPlaceholderImages', |
||
173 | ], |
||
174 | 'boolean', |
||
175 | ], |
||
176 | [ |
||
177 | [ |
||
178 | 'ignoreFilesOfType', |
||
179 | 'variants', |
||
180 | ], |
||
181 | ArrayValidator::class |
||
182 | ], |
||
183 | ]); |
||
184 | } |
||
185 | |||
186 | /** |
||
187 | * @inheritdoc |
||
188 | * @since 1.6.2 |
||
189 | */ |
||
190 | public function getContentGqlType(): Type|array |
||
198 | ]; |
||
199 | } |
||
200 | |||
201 | /** |
||
202 | * @inheritdoc |
||
203 | * @since 1.7.0 |
||
204 | */ |
||
205 | public function useFieldset(): bool |
||
208 | } |
||
209 | |||
210 | /** |
||
211 | * @inheritdoc |
||
212 | */ |
||
213 | public function afterElementSave(ElementInterface $element, bool $isNew): void |
||
214 | { |
||
215 | parent::afterElementSave($element, $isNew); |
||
216 | // Update our OptimizedImages Field data now that the Asset has been saved |
||
217 | // If this element is propagating, we don't need to redo the image saving for each site |
||
218 | if ($element instanceof Asset && $element->id !== null && !$element->propagating) { |
||
219 | // If the scenario is Asset::SCENARIO_FILEOPS or Asset::SCENARIO_MOVE (if using Craft > v3.7.1) treat it as a new asset |
||
220 | $scenario = $element->getScenario(); |
||
221 | $request = Craft::$app->getRequest(); |
||
222 | if ($isNew || $scenario === Asset::SCENARIO_FILEOPS || $scenario === Asset::SCENARIO_MOVE) { |
||
223 | /** |
||
224 | * If this is a newly uploaded/created Asset, we can save the variants |
||
225 | * via a queue job to prevent it from blocking |
||
226 | */ |
||
227 | ImageOptimize::$plugin->optimizedImages->resaveAsset($element->id); |
||
228 | } else if (!$request->isConsoleRequest && $request->getPathInfo() === 'assets/save-image') { |
||
229 | /** |
||
230 | * If it's not a newly uploaded/created Asset, check to see if the image |
||
231 | * itself is being updated (via the ImageEditor). If so, update the |
||
232 | * variants immediately so the AssetSelectorHud displays the new images |
||
233 | */ |
||
234 | try { |
||
235 | ImageOptimize::$plugin->optimizedImages->updateOptimizedImageFieldData($this, $element); |
||
236 | } catch (Exception $e) { |
||
237 | Craft::error($e->getMessage(), __METHOD__); |
||
238 | } |
||
239 | } else { |
||
240 | ImageOptimize::$plugin->optimizedImages->resaveAsset($element->id); |
||
241 | } |
||
242 | } |
||
243 | } |
||
244 | |||
245 | /** |
||
246 | * @inheritdoc |
||
247 | */ |
||
248 | public function normalizeValue($value, ElementInterface $asset = null): mixed |
||
249 | { |
||
250 | // If we're passed in a string, assume it's JSON-encoded, and decode it |
||
251 | if (is_string($value) && !empty($value)) { |
||
252 | $value = Json::decodeIfJson($value); |
||
253 | } |
||
254 | // If we're passed in an array, make a model from it |
||
255 | if (is_array($value)) { |
||
256 | // Create a new OptimizedImage model and populate it |
||
257 | $model = new OptimizedImage($value); |
||
258 | } elseif ($value instanceof OptimizedImage) { |
||
259 | $model = $value; |
||
260 | } else { |
||
261 | // Just create a new empty model |
||
262 | $model = new OptimizedImage([]); |
||
263 | } |
||
264 | |||
265 | return $model; |
||
266 | } |
||
267 | |||
268 | /** |
||
269 | * @inheritdoc |
||
270 | */ |
||
271 | public function getContentColumnType(): string |
||
272 | { |
||
273 | return Schema::TYPE_TEXT; |
||
274 | } |
||
275 | |||
276 | /** |
||
277 | * @inheritdoc |
||
278 | */ |
||
279 | public function getSettingsHtml(): null|string |
||
280 | { |
||
281 | $namespace = Craft::$app->getView()->getNamespace(); |
||
282 | if (str_contains($namespace, Matrix::class) || str_contains($namespace, SuperTableField::class)) { |
||
283 | // Render an error template, since the field only works when attached to an Asset |
||
284 | try { |
||
285 | return Craft::$app->getView()->renderTemplate( |
||
286 | 'image-optimize/_components/fields/OptimizedImages_error', |
||
287 | [ |
||
288 | ] |
||
289 | ); |
||
290 | } catch (Exception $e) { |
||
291 | Craft::error($e->getMessage(), __METHOD__); |
||
292 | } |
||
293 | } |
||
294 | // Register our asset bundle |
||
295 | try { |
||
296 | Craft::$app->getView()->registerAssetBundle(ImageOptimizeAsset::class); |
||
297 | } catch (InvalidConfigException $e) { |
||
298 | Craft::error($e->getMessage(), __METHOD__); |
||
299 | } |
||
300 | |||
301 | try { |
||
302 | $reflect = new ReflectionClass($this); |
||
303 | $thisId = $reflect->getShortName(); |
||
304 | } catch (ReflectionException $e) { |
||
305 | Craft::error($e->getMessage(), __METHOD__); |
||
306 | $thisId = 0; |
||
307 | } |
||
308 | // Get our id and namespace |
||
309 | $id = Html::id($thisId); |
||
310 | $namespacedId = Craft::$app->getView()->namespaceInputId($id); |
||
311 | $namespacePrefix = Craft::$app->getView()->namespaceInputName($thisId); |
||
312 | $sizesWrapperId = Craft::$app->getView()->namespaceInputId('sizes-wrapper'); |
||
313 | $view = Craft::$app->getView(); |
||
314 | $view->registerJs( |
||
315 | 'document.addEventListener("vite-script-loaded", function (e) {' . |
||
316 | 'if (e.detail.path === "../src/web/assets/src/js/OptimizedImagesField.js") {' . |
||
317 | 'new Craft.OptimizedImagesInput(' . |
||
318 | '"' . $namespacedId . '", ' . |
||
319 | '"' . $namespacePrefix . '",' . |
||
320 | '"' . $sizesWrapperId . '"' . |
||
321 | ');' . |
||
322 | '}' . |
||
323 | '});' |
||
324 | ); |
||
325 | |||
326 | // Prep our aspect ratios |
||
327 | $aspectRatios = []; |
||
328 | $index = 1; |
||
329 | foreach ($this->aspectRatios as $aspectRatio) { |
||
330 | if ($index % 6 === 0) { |
||
331 | $aspectRatio['break'] = true; |
||
332 | } |
||
333 | $aspectRatios[] = $aspectRatio; |
||
334 | $index++; |
||
335 | } |
||
336 | $aspectRatio = ['x' => 2, 'y' => 2, 'custom' => true]; |
||
337 | $aspectRatios[] = $aspectRatio; |
||
338 | // Get only the user-editable settings |
||
339 | $settings = ImageOptimize::$plugin->getSettings(); |
||
340 | |||
341 | // Render the settings template |
||
342 | try { |
||
343 | return Craft::$app->getView()->renderTemplate( |
||
344 | 'image-optimize/_components/fields/OptimizedImages_settings', |
||
345 | [ |
||
346 | 'field' => $this, |
||
347 | 'settings' => $settings, |
||
348 | 'aspectRatios' => $aspectRatios, |
||
349 | 'id' => $id, |
||
350 | 'name' => $this->handle, |
||
351 | 'namespace' => $namespacedId, |
||
352 | 'fieldVolumes' => $this->getFieldVolumeInfo($this->handle), |
||
353 | ] |
||
354 | ); |
||
355 | } catch (Exception $e) { |
||
356 | Craft::error($e->getMessage(), __METHOD__); |
||
357 | } |
||
358 | |||
359 | return ''; |
||
360 | } |
||
361 | |||
362 | /** |
||
363 | * @inheritdoc |
||
364 | */ |
||
365 | public function getInputHtml($value, ElementInterface $element = null): string |
||
366 | { |
||
367 | if ($element instanceof Asset && $this->handle !== null) { |
||
368 | /** @var Asset $element */ |
||
369 | // Register our asset bundle |
||
370 | try { |
||
371 | Craft::$app->getView()->registerAssetBundle(ImageOptimizeAsset::class); |
||
372 | } catch (InvalidConfigException $e) { |
||
373 | Craft::error($e->getMessage(), __METHOD__); |
||
374 | } |
||
375 | |||
376 | // Get our id and namespace |
||
377 | $id = Html::id($this->handle); |
||
378 | $nameSpaceId = Craft::$app->getView()->namespaceInputId($id); |
||
379 | |||
380 | // Variables to pass down to our field JavaScript to let it namespace properly |
||
381 | $jsonVars = [ |
||
382 | 'id' => $id, |
||
383 | 'name' => $this->handle, |
||
384 | 'namespace' => $nameSpaceId, |
||
385 | 'prefix' => Craft::$app->getView()->namespaceInputId(''), |
||
386 | ]; |
||
387 | $jsonVars = Json::encode($jsonVars); |
||
388 | $view = Craft::$app->getView(); |
||
389 | $view->registerJs( |
||
390 | 'document.addEventListener("vite-script-loaded", function (e) {' . |
||
391 | 'if (e.detail.path === "../src/web/assets/src/js/OptimizedImagesField.js") {' . |
||
392 | "$('#{$nameSpaceId}-field').ImageOptimizeOptimizedImages(" . |
||
393 | $jsonVars . |
||
394 | ");" . |
||
395 | '}' . |
||
396 | '});' |
||
397 | ); |
||
398 | |||
399 | $settings = ImageOptimize::$plugin->getSettings(); |
||
400 | $createVariants = ImageOptimize::$plugin->optimizedImages->shouldCreateVariants($this, $element); |
||
401 | |||
402 | // Render the input template |
||
403 | try { |
||
404 | return Craft::$app->getView()->renderTemplate( |
||
405 | 'image-optimize/_components/fields/OptimizedImages_input', |
||
406 | [ |
||
407 | 'name' => $this->handle, |
||
408 | 'value' => $value, |
||
409 | 'variants' => $this->variants, |
||
410 | 'field' => $this, |
||
411 | 'settings' => $settings, |
||
412 | 'elementId' => $element->id, |
||
413 | 'format' => $element->getExtension(), |
||
414 | 'id' => $id, |
||
415 | 'nameSpaceId' => $nameSpaceId, |
||
416 | 'createVariants' => $createVariants, |
||
417 | ] |
||
418 | ); |
||
419 | } catch (Exception $e) { |
||
420 | Craft::error($e->getMessage(), __METHOD__); |
||
421 | } |
||
422 | } |
||
423 | |||
424 | // Render an error template, since the field only works when attached to an Asset |
||
425 | try { |
||
426 | return Craft::$app->getView()->renderTemplate( |
||
427 | 'image-optimize/_components/fields/OptimizedImages_error', |
||
428 | [ |
||
429 | ] |
||
430 | ); |
||
431 | } catch (Exception $e) { |
||
432 | Craft::error($e->getMessage(), __METHOD__); |
||
433 | } |
||
434 | |||
435 | return ''; |
||
436 | } |
||
437 | |||
438 | // Protected Methods |
||
439 | // ========================================================================= |
||
440 | |||
441 | /** |
||
442 | * Returns an array of asset volumes and their sub-folders |
||
443 | * |
||
444 | * @param string|null $fieldHandle |
||
445 | * |
||
446 | * @return array |
||
447 | * @throws InvalidConfigException |
||
448 | */ |
||
449 | protected function getFieldVolumeInfo(?string $fieldHandle): array |
||
450 | { |
||
451 | $result = []; |
||
452 | if ($fieldHandle !== null) { |
||
453 | $volumes = Craft::$app->getVolumes()->getAllVolumes(); |
||
454 | $assets = Craft::$app->getAssets(); |
||
455 | foreach ($volumes as $volume) { |
||
456 | if (($volume instanceof Volume) && $this->volumeHasField($volume, $fieldHandle)) { |
||
457 | $tree = $assets->getFolderTreeByVolumeIds([$volume->id]); |
||
458 | $result[] = [ |
||
459 | 'name' => $volume->name, |
||
460 | 'handle' => $volume->handle, |
||
461 | 'subfolders' => $this->assembleSourceList($tree), |
||
462 | ]; |
||
463 | } |
||
464 | } |
||
465 | } |
||
466 | // If there are too many sub-folders in an Asset volume, don't display them, return an empty array |
||
467 | if (count($result) > self::MAX_VOLUME_SUBFOLDERS) { |
||
468 | $result = []; |
||
469 | } |
||
470 | |||
471 | return $result; |
||
472 | } |
||
473 | |||
474 | /** |
||
475 | * See if the passed $volume has an OptimizedImagesField with the handle $fieldHandle |
||
476 | * |
||
477 | * @param Volume $volume |
||
478 | * @param string $fieldHandle |
||
479 | * |
||
480 | * @return bool |
||
481 | */ |
||
482 | protected function volumeHasField(Volume $volume, string $fieldHandle): bool |
||
498 | } |
||
499 | |||
500 | /** |
||
501 | * Transforms an asset folder tree into a source list. |
||
502 | * |
||
503 | * @param array $folders |
||
504 | * @param bool $includeNestedFolders |
||
505 | * |
||
506 | * @return array |
||
507 | */ |
||
508 | protected function assembleSourceList(array $folders, bool $includeNestedFolders = true): array |
||
520 | } |
||
521 | } |
||
522 |