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