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