Total Complexity | 65 |
Total Lines | 496 |
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 | 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() |
||
372 | } |
||
373 | |||
374 | /** |
||
375 | * @inheritdoc |
||
376 | */ |
||
377 | public function getInputHtml($value, ElementInterface $element = null): string |
||
378 | { |
||
379 | if ($element !== null && $element instanceof Asset && $this->handle !== null) { |
||
380 | /** @var Asset $element */ |
||
381 | // Register our asset bundle |
||
382 | try { |
||
383 | Craft::$app->getView()->registerAssetBundle(ImageOptimizeAsset::class); |
||
384 | } catch (InvalidConfigException $e) { |
||
385 | Craft::error($e->getMessage(), __METHOD__); |
||
386 | } |
||
387 | |||
388 | // Get our id and namespace |
||
389 | if (ImageOptimize::$craft35) { |
||
390 | $id = Html::id($this->handle); |
||
391 | } else { |
||
392 | $id = Craft::$app->getView()->formatInputId($this->handle); |
||
393 | } |
||
394 | $nameSpaceId = Craft::$app->getView()->namespaceInputId($id); |
||
395 | |||
396 | // Variables to pass down to our field JavaScript to let it namespace properly |
||
397 | $jsonVars = [ |
||
398 | 'id' => $id, |
||
399 | 'name' => $this->handle, |
||
400 | 'namespace' => $nameSpaceId, |
||
401 | 'prefix' => Craft::$app->getView()->namespaceInputId(''), |
||
402 | ]; |
||
403 | $jsonVars = Json::encode($jsonVars); |
||
404 | $view = Craft::$app->getView(); |
||
405 | $view->registerJs( |
||
406 | "$('#{$nameSpaceId}-field').ImageOptimizeOptimizedImages(" . |
||
407 | $jsonVars . |
||
408 | ");" |
||
409 | ); |
||
410 | |||
411 | $settings = ImageOptimize::$plugin->getSettings(); |
||
412 | $createVariants = ImageOptimize::$plugin->optimizedImages->shouldCreateVariants($this, $element); |
||
413 | |||
414 | // Render the input template |
||
415 | try { |
||
416 | return Craft::$app->getView()->renderTemplate( |
||
417 | 'image-optimize/_components/fields/OptimizedImages_input', |
||
418 | [ |
||
419 | 'name' => $this->handle, |
||
420 | 'value' => $value, |
||
421 | 'variants' => $this->variants, |
||
422 | 'field' => $this, |
||
423 | 'settings' => $settings, |
||
424 | 'elementId' => $element->id, |
||
425 | 'format' => $element->getExtension(), |
||
426 | 'id' => $id, |
||
427 | 'nameSpaceId' => $nameSpaceId, |
||
428 | 'createVariants' => $createVariants, |
||
429 | ] |
||
430 | ); |
||
431 | } catch (LoaderError $e) { |
||
432 | Craft::error($e->getMessage(), __METHOD__); |
||
433 | } catch (\yii\base\Exception $e) { |
||
434 | Craft::error($e->getMessage(), __METHOD__); |
||
435 | } |
||
436 | } |
||
437 | |||
438 | // Render an error template, since the field only works when attached to an Asset |
||
439 | try { |
||
440 | return Craft::$app->getView()->renderTemplate( |
||
441 | 'image-optimize/_components/fields/OptimizedImages_error', |
||
442 | [ |
||
443 | ] |
||
444 | ); |
||
445 | } catch (LoaderError $e) { |
||
446 | Craft::error($e->getMessage(), __METHOD__); |
||
447 | } catch (\yii\base\Exception $e) { |
||
448 | Craft::error($e->getMessage(), __METHOD__); |
||
449 | } |
||
450 | |||
451 | return ''; |
||
452 | } |
||
453 | |||
454 | // Protected Methods |
||
455 | // ========================================================================= |
||
456 | |||
457 | /** |
||
458 | * Returns an array of asset volumes and their sub-folders |
||
459 | * |
||
460 | * @param string|null $fieldHandle |
||
461 | * |
||
462 | * @return array |
||
463 | * @throws InvalidConfigException |
||
464 | */ |
||
465 | protected function getFieldVolumeInfo($fieldHandle): array |
||
466 | { |
||
467 | $result = []; |
||
468 | if ($fieldHandle !== null) { |
||
469 | $volumes = Craft::$app->getVolumes()->getAllVolumes(); |
||
470 | $assets = Craft::$app->getAssets(); |
||
471 | foreach ($volumes as $volume) { |
||
472 | if (is_subclass_of($volume, Volume::class)) { |
||
473 | /** @var Volume $volume */ |
||
474 | if ($this->volumeHasField($volume, $fieldHandle)) { |
||
475 | $tree = $assets->getFolderTreeByVolumeIds([$volume->id]); |
||
476 | $result[] = [ |
||
477 | 'name' => $volume->name, |
||
478 | 'handle' => $volume->handle, |
||
479 | 'subfolders' => $this->assembleSourceList($tree), |
||
480 | ]; |
||
481 | } |
||
482 | } |
||
483 | } |
||
484 | } |
||
485 | // If there are too many sub-folders in an Asset volume, don't display them, return an empty array |
||
486 | if (count($result) > self::MAX_VOLUME_SUBFOLDERS) { |
||
487 | $result = []; |
||
488 | } |
||
489 | |||
490 | return $result; |
||
491 | } |
||
492 | |||
493 | /** |
||
494 | * See if the passed $volume has an OptimizedImagesField with the handle $fieldHandle |
||
495 | * |
||
496 | * @param Volume $volume |
||
497 | * |
||
498 | * @param string $fieldHandle |
||
499 | * |
||
500 | * @return bool |
||
501 | * @throws InvalidConfigException |
||
502 | */ |
||
503 | protected function volumeHasField(Volume $volume, string $fieldHandle): bool |
||
519 | } |
||
520 | |||
521 | /** |
||
522 | * Transforms an asset folder tree into a source list. |
||
523 | * |
||
524 | * @param array $folders |
||
525 | * @param bool $includeNestedFolders |
||
526 | * |
||
527 | * @return array |
||
528 | */ |
||
529 | protected function assembleSourceList(array $folders, bool $includeNestedFolders = true): array |
||
543 |