| Total Complexity | 59 |
| Total Lines | 431 |
| Duplicated Lines | 0 % |
| Changes | 14 | ||
| 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 |
||
| 38 | class OptimizedImages extends Component |
||
| 39 | { |
||
| 40 | // Constants |
||
| 41 | // ========================================================================= |
||
| 42 | |||
| 43 | // Public Properties |
||
| 44 | // ========================================================================= |
||
| 45 | |||
| 46 | // Public Methods |
||
| 47 | // ========================================================================= |
||
| 48 | |||
| 49 | /** |
||
| 50 | * @param Asset $asset |
||
| 51 | * @param array $variants |
||
| 52 | * |
||
| 53 | * @return OptimizedImage|null |
||
| 54 | */ |
||
| 55 | public function createOptimizedImages(Asset $asset, array $variants = []) |
||
| 56 | { |
||
| 57 | Craft::beginProfile('createOptimizedImages', __METHOD__); |
||
| 58 | if (empty($variants)) { |
||
| 59 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 60 | if ($settings) { |
||
| 61 | $variants = $settings->defaultVariants; |
||
| 62 | } |
||
| 63 | } |
||
| 64 | |||
| 65 | $model = new OptimizedImage(); |
||
| 66 | $this->populateOptimizedImageModel($asset, $variants, $model); |
||
| 67 | Craft::endProfile('createOptimizedImages', __METHOD__); |
||
| 68 | |||
| 69 | return $model; |
||
| 70 | } |
||
| 71 | |||
| 72 | /** |
||
| 73 | * @param Asset $asset |
||
| 74 | * @param array $variants |
||
| 75 | * @param OptimizedImage $model |
||
| 76 | */ |
||
| 77 | public function populateOptimizedImageModel(Asset $asset, $variants, OptimizedImage $model) |
||
| 78 | { |
||
| 79 | Craft::beginProfile('populateOptimizedImageModel', __METHOD__); |
||
| 80 | $settings = ImageOptimize::$plugin->getSettings(); |
||
| 81 | // Empty our the optimized image URLs |
||
| 82 | $model->optimizedImageUrls = []; |
||
| 83 | $model->optimizedWebPImageUrls = []; |
||
| 84 | $model->variantSourceWidths = []; |
||
| 85 | $model->placeholderWidth = 0; |
||
| 86 | $model->placeholderHeight = 0; |
||
| 87 | |||
| 88 | foreach ($variants as $variant) { |
||
| 89 | $retinaSizes = ['1']; |
||
| 90 | if (!empty($variant['retinaSizes'])) { |
||
| 91 | $retinaSizes = $variant['retinaSizes']; |
||
| 92 | } |
||
| 93 | foreach ($retinaSizes as $retinaSize) { |
||
| 94 | $finalFormat = empty($variant['format']) ? $asset->getExtension() : $variant['format']; |
||
| 95 | // Only try the transform if it's possible |
||
| 96 | if (Image::canManipulateAsImage($finalFormat) |
||
| 97 | && Image::canManipulateAsImage($asset->getExtension()) |
||
| 98 | && $asset->height > 0) { |
||
| 99 | // Create the transform based on the variant |
||
| 100 | list($transform, $aspectRatio) = $this->getTransformFromVariant($asset, $variant, $retinaSize); |
||
| 101 | // Only create the image variant if it is not upscaled, or they are okay with it being up-scaled |
||
| 102 | if (($asset->width >= $transform->width && $asset->height >= $transform->height) |
||
| 103 | || $settings->allowUpScaledImageVariants |
||
| 104 | ) { |
||
| 105 | $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio); |
||
| 106 | } |
||
| 107 | } else { |
||
| 108 | Craft::error( |
||
| 109 | 'Could not create transform for: '.$asset->title |
||
| 110 | .' - Final format: '.$finalFormat |
||
| 111 | .' - Element extension: '.$asset->getExtension() |
||
| 112 | .' - canManipulateAsImage: '.Image::canManipulateAsImage($asset->getExtension()), |
||
| 113 | __METHOD__ |
||
| 114 | ); |
||
| 115 | } |
||
| 116 | } |
||
| 117 | } |
||
| 118 | |||
| 119 | // If no image variants were created, populate it with the image itself |
||
| 120 | if (empty($model->optimizedImageUrls)) { |
||
| 121 | $finalFormat = $asset->getExtension(); |
||
| 122 | if (Image::canManipulateAsImage($finalFormat) |
||
| 123 | && Image::canManipulateAsImage($finalFormat) |
||
| 124 | && $asset->height > 0) { |
||
| 125 | $variant = [ |
||
| 126 | 'width' => $asset->width, |
||
| 127 | 'useAspectRatio' => false, |
||
| 128 | 'aspectRatioX' => $asset->width, |
||
| 129 | 'aspectRatioY' => $asset->height, |
||
| 130 | 'retinaSizes' => ['1'], |
||
| 131 | 'quality' => 0, |
||
| 132 | ]; |
||
| 133 | list($transform, $aspectRatio) = $this->getTransformFromVariant($asset, $variant, 1); |
||
| 134 | $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio); |
||
| 135 | } else { |
||
| 136 | Craft::error( |
||
| 137 | 'Could not create transform for: '.$asset->title |
||
| 138 | .' - Final format: '.$finalFormat |
||
| 139 | .' - Element extension: '.$asset->getExtension() |
||
| 140 | .' - canManipulateAsImage: '.Image::canManipulateAsImage($asset->getExtension()), |
||
| 141 | __METHOD__ |
||
| 142 | ); |
||
| 143 | } |
||
| 144 | } |
||
| 145 | Craft::endProfile('populateOptimizedImageModel', __METHOD__); |
||
| 146 | } |
||
| 147 | |||
| 148 | // Protected Methods |
||
| 149 | // ========================================================================= |
||
| 150 | |||
| 151 | /** |
||
| 152 | * @param Field $field |
||
| 153 | * @param ElementInterface $asset |
||
| 154 | * |
||
| 155 | * @throws \yii\db\Exception |
||
| 156 | */ |
||
| 157 | public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset) |
||
| 158 | { |
||
| 159 | /** @var Asset $asset */ |
||
| 160 | if ($asset instanceof Asset && $field instanceof OptimizedImagesField) { |
||
| 161 | $createVariants = true; |
||
| 162 | $sourceType = $asset->getMimeType(); |
||
| 163 | if (!empty($field->ignoreFilesOfType) && $sourceType !== null) { |
||
| 164 | if (\in_array($sourceType, array_values($field->ignoreFilesOfType), false)) { |
||
| 165 | $createVariants = false; |
||
| 166 | } |
||
| 167 | } |
||
| 168 | Craft::info(print_r($sourceType, true), 'image-optimize'); |
||
| 169 | // Create a new OptimizedImage model and populate it |
||
| 170 | $model = new OptimizedImage(); |
||
| 171 | // Empty our the optimized image URLs |
||
| 172 | $model->optimizedImageUrls = []; |
||
| 173 | $model->optimizedWebPImageUrls = []; |
||
| 174 | $model->variantSourceWidths = []; |
||
| 175 | $model->placeholderWidth = 0; |
||
| 176 | $model->placeholderHeight = 0; |
||
| 177 | if ($asset !== null && $createVariants) { |
||
| 178 | $this->populateOptimizedImageModel( |
||
| 179 | $asset, |
||
| 180 | $field->variants, |
||
| 181 | $model |
||
| 182 | ); |
||
| 183 | } |
||
| 184 | // Save our field data directly into the content table |
||
| 185 | if ($field->handle !== null) { |
||
| 186 | $asset->setFieldValue($field->handle, $field->serializeValue($model)); |
||
| 187 | $table = $asset->getContentTable(); |
||
| 188 | $column = $asset->getFieldColumnPrefix().$field->handle; |
||
| 189 | $data = Json::encode($field->serializeValue($asset->getFieldValue($field->handle), $asset)); |
||
| 190 | Craft::$app->db->createCommand() |
||
| 191 | ->update($table, [ |
||
| 192 | $column => $data, |
||
| 193 | ], [ |
||
| 194 | 'elementId' => $asset->getId(), |
||
| 195 | ], [], false) |
||
| 196 | ->execute(); |
||
| 197 | } |
||
| 198 | } |
||
| 199 | } |
||
| 200 | |||
| 201 | /** |
||
| 202 | * Re-save all of the assets in all of the volumes |
||
| 203 | * |
||
| 204 | * @throws \yii\base\InvalidConfigException |
||
| 205 | */ |
||
| 206 | public function resaveAllVolumesAssets() |
||
| 207 | { |
||
| 208 | $volumes = Craft::$app->getVolumes()->getAllVolumes(); |
||
| 209 | foreach ($volumes as $volume) { |
||
| 210 | if (is_subclass_of($volume, Volume::class)) { |
||
| 211 | /** @var Volume $volume */ |
||
| 212 | $this->resaveVolumeAssets($volume); |
||
| 213 | } |
||
| 214 | } |
||
| 215 | } |
||
| 216 | |||
| 217 | /** |
||
| 218 | * Re-save all of the Asset elements in the Volume $volume that have an |
||
| 219 | * OptimizedImages field in the FieldLayout |
||
| 220 | * |
||
| 221 | * @param Volume $volume |
||
| 222 | * |
||
| 223 | * @throws \yii\base\InvalidConfigException |
||
| 224 | */ |
||
| 225 | public function resaveVolumeAssets(Volume $volume) |
||
| 226 | { |
||
| 227 | $needToReSave = false; |
||
| 228 | /** @var FieldLayout $fieldLayout */ |
||
| 229 | $fieldLayout = $volume->getFieldLayout(); |
||
| 230 | // Loop through the fields in the layout to see if there is an OptimizedImages field |
||
| 231 | if ($fieldLayout) { |
||
| 232 | $fields = $fieldLayout->getFields(); |
||
| 233 | foreach ($fields as $field) { |
||
| 234 | if ($field instanceof OptimizedImagesField) { |
||
| 235 | $needToReSave = true; |
||
| 236 | } |
||
| 237 | } |
||
| 238 | } |
||
| 239 | if ($needToReSave) { |
||
| 240 | try { |
||
| 241 | $siteId = Craft::$app->getSites()->getPrimarySite()->id; |
||
| 242 | } catch (SiteNotFoundException $e) { |
||
| 243 | $siteId = 0; |
||
| 244 | Craft::error( |
||
| 245 | 'Failed to get primary site: '.$e->getMessage(), |
||
| 246 | __METHOD__ |
||
| 247 | ); |
||
| 248 | } |
||
| 249 | |||
| 250 | $queue = Craft::$app->getQueue(); |
||
| 251 | $jobId = $queue->push(new ResaveOptimizedImages([ |
||
| 252 | 'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]), |
||
| 253 | 'criteria' => [ |
||
| 254 | 'siteId' => $siteId, |
||
| 255 | 'volumeId' => $volume->id, |
||
| 256 | 'status' => null, |
||
| 257 | 'enabledForSite' => false, |
||
| 258 | ], |
||
| 259 | ])); |
||
| 260 | Craft::debug( |
||
| 261 | Craft::t( |
||
| 262 | 'image-optimize', |
||
| 263 | 'Started resaveVolumeAssets queue job id: {jobId}', |
||
| 264 | [ |
||
| 265 | 'jobId' => $jobId, |
||
| 266 | ] |
||
| 267 | ), |
||
| 268 | __METHOD__ |
||
| 269 | ); |
||
| 270 | } |
||
| 271 | } |
||
| 272 | |||
| 273 | /** |
||
| 274 | * Re-save an individual asset |
||
| 275 | * |
||
| 276 | * @param int $id |
||
| 277 | */ |
||
| 278 | public function resaveAsset(int $id) |
||
| 279 | { |
||
| 280 | $queue = Craft::$app->getQueue(); |
||
| 281 | $jobId = $queue->push(new ResaveOptimizedImages([ |
||
| 282 | 'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]), |
||
| 283 | 'criteria' => [ |
||
| 284 | 'id' => $id, |
||
| 285 | 'status' => null, |
||
| 286 | 'enabledForSite' => false, |
||
| 287 | ], |
||
| 288 | ])); |
||
| 289 | Craft::debug( |
||
| 290 | Craft::t( |
||
| 291 | 'image-optimize', |
||
| 292 | 'Started resaveAsset queue job id: {jobId} Element id: {elementId}', |
||
| 293 | [ |
||
| 294 | 'elementId' => $id, |
||
| 295 | 'jobId' => $jobId, |
||
| 296 | ] |
||
| 297 | ), |
||
| 298 | __METHOD__ |
||
| 299 | ); |
||
| 300 | } |
||
| 301 | |||
| 302 | /** |
||
| 303 | * Create an optimized SVG data uri |
||
| 304 | * See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris |
||
| 305 | * |
||
| 306 | * @param string $uri |
||
| 307 | * |
||
| 308 | * @return string |
||
| 309 | */ |
||
| 310 | public function encodeOptimizedSVGDataUri(string $uri): string |
||
| 311 | { |
||
| 312 | // First, uri encode everything |
||
| 313 | $uri = rawurlencode($uri); |
||
| 314 | $replacements = [ |
||
| 315 | // remove newlines |
||
| 316 | '/%0A/' => '', |
||
| 317 | // put spaces back in |
||
| 318 | '/%20/' => ' ', |
||
| 319 | // put equals signs back in |
||
| 320 | '/%3D/' => '=', |
||
| 321 | // put colons back in |
||
| 322 | '/%3A/' => ':', |
||
| 323 | // put slashes back in |
||
| 324 | '/%2F/' => '/', |
||
| 325 | // replace quotes with apostrophes (may break certain SVGs) |
||
| 326 | '/%22/' => "'", |
||
| 327 | ]; |
||
| 328 | foreach ($replacements as $pattern => $replacement) { |
||
| 329 | $uri = preg_replace($pattern, $replacement, $uri); |
||
| 330 | } |
||
| 331 | |||
| 332 | return $uri; |
||
| 333 | } |
||
| 334 | |||
| 335 | /** |
||
| 336 | * @param Asset $element |
||
| 337 | * @param OptimizedImage $model |
||
| 338 | * @param $aspectRatio |
||
| 339 | */ |
||
| 340 | protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio) |
||
| 369 | } |
||
| 370 | |||
| 371 | /** |
||
| 372 | * @param Asset $asset |
||
| 373 | * @param $variant |
||
| 374 | * @param $retinaSize |
||
| 375 | * |
||
| 376 | * @return array |
||
| 377 | */ |
||
| 378 | protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array |
||
| 418 | } |
||
| 419 | |||
| 420 | /** |
||
| 421 | * @param Asset $asset |
||
| 422 | * @param OptimizedImage $model |
||
| 423 | * @param $transform |
||
| 424 | * @param $variant |
||
| 425 | * @param $aspectRatio |
||
| 426 | */ |
||
| 427 | protected function addVariantImageToModel(Asset $asset, OptimizedImage $model, $transform, $variant, $aspectRatio) |
||
| 471 |