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