Total Complexity | 65 |
Total Lines | 504 |
Duplicated Lines | 0 % |
Changes | 14 | ||
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 | const DEFAULT_ASPECT_RATIOS = [ |
||
51 | ['x' => 16, 'y' => 9], |
||
52 | ]; |
||
53 | 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 | const MAX_VOLUME_SUBFOLDERS = 30; |
||
66 | |||
67 | // Public Properties |
||
68 | // ========================================================================= |
||
69 | |||
70 | /** |
||
71 | * @var array |
||
72 | */ |
||
73 | public $fieldVolumeSettings = []; |
||
74 | |||
75 | /** |
||
76 | * @var array |
||
77 | */ |
||
78 | public $ignoreFilesOfType = []; |
||
79 | |||
80 | /** |
||
81 | * @var bool |
||
82 | */ |
||
83 | public $displayOptimizedImageVariants = true; |
||
84 | |||
85 | /** |
||
86 | * @var bool |
||
87 | */ |
||
88 | public $displayDominantColorPalette = true; |
||
89 | |||
90 | /** |
||
91 | * @var bool |
||
92 | */ |
||
93 | public $displayLazyLoadPlaceholderImages = true; |
||
94 | |||
95 | /** |
||
96 | * @var array |
||
97 | */ |
||
98 | public $variants = []; |
||
99 | |||
100 | // Private Properties |
||
101 | // ========================================================================= |
||
102 | |||
103 | /** |
||
104 | * @var array |
||
105 | */ |
||
106 | private $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() |
||
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() |
||
165 | { |
||
166 | $rules = parent::rules(); |
||
167 | $rules = 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 | return $rules; |
||
186 | } |
||
187 | |||
188 | /** |
||
189 | * @inheritdoc |
||
190 | * @since 1.6.2 |
||
191 | */ |
||
192 | public function getContentGqlType() |
||
193 | { |
||
194 | $typeArray = OptimizedImagesGenerator::generateTypes($this); |
||
195 | |||
196 | return [ |
||
197 | 'name' => $this->handle, |
||
198 | 'description' => 'Optimized Images field', |
||
199 | 'type' => array_shift($typeArray), |
||
200 | ]; |
||
201 | } |
||
202 | |||
203 | /** |
||
204 | * @inheritdoc |
||
205 | * @since 1.7.0 |
||
206 | */ |
||
207 | public function useFieldset(): bool |
||
210 | } |
||
211 | |||
212 | /** |
||
213 | * @inheritdoc |
||
214 | */ |
||
215 | public function afterElementSave(ElementInterface $element, bool $isNew) |
||
216 | { |
||
217 | parent::afterElementSave($element, $isNew); |
||
218 | // Update our OptimizedImages Field data now that the Asset has been saved |
||
219 | // If this element is propagating, we don't need to redo the image saving for each site |
||
220 | if ($element instanceof Asset && $element->id !== null && !$element->propagating) { |
||
221 | // If the scenario is Asset::SCENARIO_FILEOPS or Asset::SCENARIO_MOVE (if using Craft > v3.7.1) treat it as a new asset |
||
222 | $scenario = $element->getScenario(); |
||
223 | $request = Craft::$app->getRequest(); |
||
224 | $supportsMoveScenario = version_compare( |
||
225 | Craft::$app->getVersion(), |
||
226 | '3.7.1', |
||
227 | '>=' |
||
228 | ) === true; |
||
229 | |||
230 | if ($isNew || $scenario === Asset::SCENARIO_FILEOPS || ($supportsMoveScenario && $scenario === Asset::SCENARIO_MOVE)) { |
||
231 | /** |
||
232 | * If this is a newly uploaded/created Asset, we can save the variants |
||
233 | * via a queue job to prevent it from blocking |
||
234 | */ |
||
235 | ImageOptimize::$plugin->optimizedImages->resaveAsset($element->id); |
||
236 | } else if (!$request->isConsoleRequest && $request->getPathInfo() === 'actions/assets/save-image') { |
||
237 | /** |
||
238 | * If it's not a newly uploaded/created Asset, check to see if the image |
||
239 | * itself is being updated (via the ImageEditor). If so, update the |
||
240 | * variants immediately so the AssetSelectorHud displays the new images |
||
241 | */ |
||
242 | try { |
||
243 | ImageOptimize::$plugin->optimizedImages->updateOptimizedImageFieldData($this, $element); |
||
244 | } catch (Exception $e) { |
||
245 | Craft::error($e->getMessage(), __METHOD__); |
||
246 | } |
||
247 | } else { |
||
248 | ImageOptimize::$plugin->optimizedImages->resaveAsset($element->id); |
||
249 | } |
||
250 | } |
||
251 | } |
||
252 | |||
253 | /** |
||
254 | * @inheritdoc |
||
255 | */ |
||
256 | public function normalizeValue($value, ElementInterface $asset = null) |
||
257 | { |
||
258 | // If we're passed in a string, assume it's JSON-encoded, and decode it |
||
259 | if (is_string($value) && !empty($value)) { |
||
260 | $value = Json::decodeIfJson($value); |
||
261 | } |
||
262 | // If we're passed in an array, make a model from it |
||
263 | if (is_array($value)) { |
||
264 | // Create a new OptimizedImage model and populate it |
||
265 | $model = new OptimizedImage($value); |
||
266 | } elseif ($value instanceof OptimizedImage) { |
||
267 | $model = $value; |
||
268 | } else { |
||
269 | // Just create a new empty model |
||
270 | $model = new OptimizedImage(null); |
||
271 | } |
||
272 | |||
273 | return $model; |
||
274 | } |
||
275 | |||
276 | /** |
||
277 | * @inheritdoc |
||
278 | */ |
||
279 | public function getContentColumnType(): string |
||
282 | } |
||
283 | |||
284 | /** |
||
285 | * @inheritdoc |
||
286 | */ |
||
287 | public function getSettingsHtml() |
||
288 | { |
||
289 | $namespace = Craft::$app->getView()->getNamespace(); |
||
290 | if (strpos($namespace, Matrix::class) !== false || strpos($namespace, SuperTableField::class) !== false) { |
||
291 | // Render an error template, since the field only works when attached to an Asset |
||
292 | try { |
||
293 | return Craft::$app->getView()->renderTemplate( |
||
294 | 'image-optimize/_components/fields/OptimizedImages_error', |
||
295 | [ |
||
296 | ] |
||
297 | ); |
||
298 | } catch (LoaderError $e) { |
||
299 | Craft::error($e->getMessage(), __METHOD__); |
||
300 | } catch (\yii\base\Exception $e) { |
||
301 | Craft::error($e->getMessage(), __METHOD__); |
||
302 | } |
||
303 | } |
||
304 | // Register our asset bundle |
||
305 | try { |
||
306 | Craft::$app->getView()->registerAssetBundle(ImageOptimizeAsset::class); |
||
307 | } catch (InvalidConfigException $e) { |
||
308 | Craft::error($e->getMessage(), __METHOD__); |
||
309 | } |
||
310 | |||
311 | try { |
||
312 | $reflect = new ReflectionClass($this); |
||
313 | $thisId = $reflect->getShortName(); |
||
314 | } catch (ReflectionException $e) { |
||
315 | Craft::error($e->getMessage(), __METHOD__); |
||
316 | $thisId = 0; |
||
317 | } |
||
318 | // Get our id and namespace |
||
319 | if (ImageOptimize::$craft35) { |
||
320 | $id = Html::id($thisId); |
||
321 | } else { |
||
322 | $id = Craft::$app->getView()->formatInputId($thisId); |
||
323 | } |
||
324 | $namespacedId = Craft::$app->getView()->namespaceInputId($id); |
||
325 | $namespacePrefix = Craft::$app->getView()->namespaceInputName($thisId); |
||
326 | $sizesWrapperId = Craft::$app->getView()->namespaceInputId('sizes-wrapper'); |
||
327 | $view = Craft::$app->getView(); |
||
328 | $view->registerJs( |
||
329 | 'document.addEventListener("vite-script-loaded", function (e) {' . |
||
330 | 'if (e.detail.path === "../src/web/assets/src/js/OptimizedImagesField.js") {' . |
||
331 | 'new Craft.OptimizedImagesInput(' . |
||
332 | '"' . $namespacedId . '", ' . |
||
333 | '"' . $namespacePrefix . '",' . |
||
334 | '"' . $sizesWrapperId . '"' . |
||
335 | ');' . |
||
336 | '}' . |
||
337 | '});' |
||
338 | ); |
||
339 | |||
340 | // Prep our aspect ratios |
||
341 | $aspectRatios = []; |
||
342 | $index = 1; |
||
343 | foreach ($this->aspectRatios as $aspectRatio) { |
||
344 | if ($index % 6 === 0) { |
||
345 | $aspectRatio['break'] = true; |
||
346 | } |
||
347 | $aspectRatios[] = $aspectRatio; |
||
348 | $index++; |
||
349 | } |
||
350 | $aspectRatio = ['x' => 2, 'y' => 2, 'custom' => true]; |
||
351 | $aspectRatios[] = $aspectRatio; |
||
352 | // Get only the user-editable settings |
||
353 | $settings = ImageOptimize::$plugin->getSettings(); |
||
354 | |||
355 | // Render the settings template |
||
356 | try { |
||
357 | return Craft::$app->getView()->renderTemplate( |
||
358 | 'image-optimize/_components/fields/OptimizedImages_settings', |
||
359 | [ |
||
360 | 'field' => $this, |
||
361 | 'settings' => $settings, |
||
362 | 'aspectRatios' => $aspectRatios, |
||
363 | 'id' => $id, |
||
364 | 'name' => $this->handle, |
||
365 | 'namespace' => $namespacedId, |
||
366 | 'fieldVolumes' => $this->getFieldVolumeInfo($this->handle), |
||
367 | ] |
||
368 | ); |
||
369 | } catch (LoaderError $e) { |
||
370 | Craft::error($e->getMessage(), __METHOD__); |
||
371 | } catch (\yii\base\Exception $e) { |
||
372 | Craft::error($e->getMessage(), __METHOD__); |
||
373 | } |
||
374 | |||
375 | return ''; |
||
376 | } |
||
377 | |||
378 | /** |
||
379 | * @inheritdoc |
||
380 | */ |
||
381 | public function getInputHtml($value, ElementInterface $element = null): string |
||
382 | { |
||
383 | if ($element !== null && $element instanceof Asset && $this->handle !== null) { |
||
384 | /** @var Asset $element */ |
||
385 | // Register our asset bundle |
||
386 | try { |
||
387 | Craft::$app->getView()->registerAssetBundle(ImageOptimizeAsset::class); |
||
388 | } catch (InvalidConfigException $e) { |
||
389 | Craft::error($e->getMessage(), __METHOD__); |
||
390 | } |
||
391 | |||
392 | // Get our id and namespace |
||
393 | if (ImageOptimize::$craft35) { |
||
394 | $id = Html::id($this->handle); |
||
395 | } else { |
||
396 | $id = Craft::$app->getView()->formatInputId($this->handle); |
||
397 | } |
||
398 | $nameSpaceId = Craft::$app->getView()->namespaceInputId($id); |
||
399 | |||
400 | // Variables to pass down to our field JavaScript to let it namespace properly |
||
401 | $jsonVars = [ |
||
402 | 'id' => $id, |
||
403 | 'name' => $this->handle, |
||
404 | 'namespace' => $nameSpaceId, |
||
405 | 'prefix' => Craft::$app->getView()->namespaceInputId(''), |
||
406 | ]; |
||
407 | $jsonVars = Json::encode($jsonVars); |
||
408 | $view = Craft::$app->getView(); |
||
409 | $view->registerJs( |
||
410 | 'document.addEventListener("vite-script-loaded", function (e) {' . |
||
411 | 'if (e.detail.path === "../src/web/assets/src/js/OptimizedImagesField.js") {' . |
||
412 | "$('#{$nameSpaceId}-field').ImageOptimizeOptimizedImages(" . |
||
413 | $jsonVars . |
||
414 | ");" . |
||
415 | '}' . |
||
416 | '});' |
||
417 | ); |
||
418 | |||
419 | $settings = ImageOptimize::$plugin->getSettings(); |
||
420 | $createVariants = ImageOptimize::$plugin->optimizedImages->shouldCreateVariants($this, $element); |
||
421 | |||
422 | // Render the input template |
||
423 | try { |
||
424 | return Craft::$app->getView()->renderTemplate( |
||
425 | 'image-optimize/_components/fields/OptimizedImages_input', |
||
426 | [ |
||
427 | 'name' => $this->handle, |
||
428 | 'value' => $value, |
||
429 | 'variants' => $this->variants, |
||
430 | 'field' => $this, |
||
431 | 'settings' => $settings, |
||
432 | 'elementId' => $element->id, |
||
433 | 'format' => $element->getExtension(), |
||
434 | 'id' => $id, |
||
435 | 'nameSpaceId' => $nameSpaceId, |
||
436 | 'createVariants' => $createVariants, |
||
437 | ] |
||
438 | ); |
||
439 | } catch (LoaderError $e) { |
||
440 | Craft::error($e->getMessage(), __METHOD__); |
||
441 | } catch (\yii\base\Exception $e) { |
||
442 | Craft::error($e->getMessage(), __METHOD__); |
||
443 | } |
||
444 | } |
||
445 | |||
446 | // Render an error template, since the field only works when attached to an Asset |
||
447 | try { |
||
448 | return Craft::$app->getView()->renderTemplate( |
||
449 | 'image-optimize/_components/fields/OptimizedImages_error', |
||
450 | [ |
||
451 | ] |
||
452 | ); |
||
453 | } catch (LoaderError $e) { |
||
454 | Craft::error($e->getMessage(), __METHOD__); |
||
455 | } catch (\yii\base\Exception $e) { |
||
456 | Craft::error($e->getMessage(), __METHOD__); |
||
457 | } |
||
458 | |||
459 | return ''; |
||
460 | } |
||
461 | |||
462 | // Protected Methods |
||
463 | // ========================================================================= |
||
464 | |||
465 | /** |
||
466 | * Returns an array of asset volumes and their sub-folders |
||
467 | * |
||
468 | * @param string|null $fieldHandle |
||
469 | * |
||
470 | * @return array |
||
471 | * @throws InvalidConfigException |
||
472 | */ |
||
473 | protected function getFieldVolumeInfo($fieldHandle): array |
||
474 | { |
||
475 | $result = []; |
||
476 | if ($fieldHandle !== null) { |
||
477 | $volumes = Craft::$app->getVolumes()->getAllVolumes(); |
||
478 | $assets = Craft::$app->getAssets(); |
||
479 | foreach ($volumes as $volume) { |
||
480 | if (is_subclass_of($volume, Volume::class)) { |
||
481 | /** @var Volume $volume */ |
||
482 | if ($this->volumeHasField($volume, $fieldHandle)) { |
||
483 | $tree = $assets->getFolderTreeByVolumeIds([$volume->id]); |
||
484 | $result[] = [ |
||
485 | 'name' => $volume->name, |
||
486 | 'handle' => $volume->handle, |
||
487 | 'subfolders' => $this->assembleSourceList($tree), |
||
488 | ]; |
||
489 | } |
||
490 | } |
||
491 | } |
||
492 | } |
||
493 | // If there are too many sub-folders in an Asset volume, don't display them, return an empty array |
||
494 | if (count($result) > self::MAX_VOLUME_SUBFOLDERS) { |
||
495 | $result = []; |
||
496 | } |
||
497 | |||
498 | return $result; |
||
499 | } |
||
500 | |||
501 | /** |
||
502 | * See if the passed $volume has an OptimizedImagesField with the handle $fieldHandle |
||
503 | * |
||
504 | * @param Volume $volume |
||
505 | * |
||
506 | * @param string $fieldHandle |
||
507 | * |
||
508 | * @return bool |
||
509 | * @throws InvalidConfigException |
||
510 | */ |
||
511 | protected function volumeHasField(Volume $volume, string $fieldHandle): bool |
||
527 | } |
||
528 | |||
529 | /** |
||
530 | * Transforms an asset folder tree into a source list. |
||
531 | * |
||
532 | * @param array $folders |
||
533 | * @param bool $includeNestedFolders |
||
534 | * |
||
535 | * @return array |
||
536 | */ |
||
537 | protected function assembleSourceList(array $folders, bool $includeNestedFolders = true): array |
||
549 | } |
||
550 | } |
||
551 |