| Total Complexity | 72 |
| Total Lines | 475 |
| Duplicated Lines | 0 % |
| Changes | 18 | ||
| 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 = []) |
||
| 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) |
||
| 146 | } |
||
| 147 | |||
| 148 | /** |
||
| 149 | * Should variants be created for the given OptimizedImages field and the Asset? |
||
| 150 | * |
||
| 151 | * @param $field |
||
| 152 | * @param $asset |
||
| 153 | * @return bool |
||
| 154 | */ |
||
| 155 | public function shouldCreateVariants($field, $asset): bool |
||
| 156 | { |
||
| 157 | $createVariants = true; |
||
| 158 | Craft::info(print_r($field->fieldVolumeSettings, true), __METHOD__); |
||
| 159 | // See if we're ignoring files in this dir |
||
| 160 | if (!empty($field->fieldVolumeSettings)) { |
||
| 161 | foreach ($field->fieldVolumeSettings as $volumeHandle => $subfolders) { |
||
| 162 | if ($asset->getVolume()->handle === $volumeHandle) { |
||
| 163 | if (is_string($subfolders) && $subfolders === '*') { |
||
| 164 | $createVariants = true; |
||
| 165 | Craft::info("Matched '*' wildcard ", __METHOD__); |
||
| 166 | } else { |
||
| 167 | $createVariants = false; |
||
| 168 | if (is_array($subfolders)) { |
||
| 169 | foreach ($subfolders as $subfolder) { |
||
| 170 | $folder = $asset->getFolder(); |
||
| 171 | while ($folder !== null && !$createVariants) { |
||
| 172 | if ($folder->uid === $subfolder) { |
||
| 173 | Craft::info('Matched subfolder uid: ' . print_r($subfolder, true), __METHOD__); |
||
| 174 | $createVariants = true; |
||
| 175 | } else { |
||
| 176 | $folder = $folder->getParent(); |
||
| 177 | } |
||
| 178 | } |
||
| 179 | } |
||
| 180 | } |
||
| 181 | } |
||
| 182 | } |
||
| 183 | } |
||
| 184 | } |
||
| 185 | // See if we should ignore this type of file |
||
| 186 | $sourceType = $asset->getMimeType(); |
||
| 187 | if (!empty($field->ignoreFilesOfType) && $sourceType !== null) { |
||
| 188 | if (\in_array($sourceType, array_values($field->ignoreFilesOfType), false)) { |
||
| 189 | $createVariants = false; |
||
| 190 | } |
||
| 191 | } |
||
| 192 | return $createVariants; |
||
| 193 | } |
||
| 194 | |||
| 195 | /** |
||
| 196 | * @param Field $field |
||
| 197 | * @param ElementInterface $asset |
||
| 198 | * |
||
| 199 | * @throws \yii\db\Exception |
||
| 200 | * @throws InvalidConfigException |
||
| 201 | */ |
||
| 202 | public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset) |
||
| 203 | { |
||
| 204 | /** @var Asset $asset */ |
||
| 205 | if ($asset instanceof Asset && $field instanceof OptimizedImagesField) { |
||
| 206 | $createVariants = $this->shouldCreateVariants($field, $asset); |
||
| 207 | // Create a new OptimizedImage model and populate it |
||
| 208 | $model = new OptimizedImage(); |
||
| 209 | // Empty our the optimized image URLs |
||
| 210 | $model->optimizedImageUrls = []; |
||
| 211 | $model->optimizedWebPImageUrls = []; |
||
| 212 | $model->variantSourceWidths = []; |
||
| 213 | $model->placeholderWidth = 0; |
||
| 214 | $model->placeholderHeight = 0; |
||
| 215 | if ($asset !== null && $createVariants) { |
||
| 216 | $this->populateOptimizedImageModel( |
||
| 217 | $asset, |
||
| 218 | $field->variants, |
||
| 219 | $model |
||
| 220 | ); |
||
| 221 | } |
||
| 222 | // Save our field data directly into the content table |
||
| 223 | if ($field->handle !== null) { |
||
| 224 | $asset->setFieldValue($field->handle, $field->serializeValue($model)); |
||
| 225 | $table = $asset->getContentTable(); |
||
| 226 | $column = $asset->getFieldColumnPrefix().$field->handle; |
||
| 227 | $data = Json::encode($field->serializeValue($asset->getFieldValue($field->handle), $asset)); |
||
| 228 | Craft::$app->db->createCommand() |
||
| 229 | ->update($table, [ |
||
| 230 | $column => $data, |
||
| 231 | ], [ |
||
| 232 | 'elementId' => $asset->getId(), |
||
| 233 | ], [], false) |
||
| 234 | ->execute(); |
||
| 235 | } |
||
| 236 | } |
||
| 237 | } |
||
| 238 | |||
| 239 | /** |
||
| 240 | * Re-save all of the assets in all of the volumes |
||
| 241 | * |
||
| 242 | * @throws \yii\base\InvalidConfigException |
||
| 243 | */ |
||
| 244 | public function resaveAllVolumesAssets() |
||
| 245 | { |
||
| 246 | $volumes = Craft::$app->getVolumes()->getAllVolumes(); |
||
| 247 | foreach ($volumes as $volume) { |
||
| 248 | if (is_subclass_of($volume, Volume::class)) { |
||
| 249 | /** @var Volume $volume */ |
||
| 250 | $this->resaveVolumeAssets($volume); |
||
| 251 | } |
||
| 252 | } |
||
| 253 | } |
||
| 254 | |||
| 255 | /** |
||
| 256 | * Re-save all of the Asset elements in the Volume $volume that have an |
||
| 257 | * OptimizedImages field in the FieldLayout |
||
| 258 | * |
||
| 259 | * @param Volume $volume |
||
| 260 | * |
||
| 261 | * @throws \yii\base\InvalidConfigException |
||
| 262 | */ |
||
| 263 | public function resaveVolumeAssets(Volume $volume) |
||
| 264 | { |
||
| 265 | $needToReSave = false; |
||
| 266 | /** @var FieldLayout $fieldLayout */ |
||
| 267 | $fieldLayout = $volume->getFieldLayout(); |
||
| 268 | // Loop through the fields in the layout to see if there is an OptimizedImages field |
||
| 269 | if ($fieldLayout) { |
||
| 270 | $fields = $fieldLayout->getFields(); |
||
| 271 | foreach ($fields as $field) { |
||
| 272 | if ($field instanceof OptimizedImagesField) { |
||
| 273 | $needToReSave = true; |
||
| 274 | } |
||
| 275 | } |
||
| 276 | } |
||
| 277 | if ($needToReSave) { |
||
| 278 | try { |
||
| 279 | $siteId = Craft::$app->getSites()->getPrimarySite()->id; |
||
| 280 | } catch (SiteNotFoundException $e) { |
||
| 281 | $siteId = 0; |
||
| 282 | Craft::error( |
||
| 283 | 'Failed to get primary site: '.$e->getMessage(), |
||
| 284 | __METHOD__ |
||
| 285 | ); |
||
| 286 | } |
||
| 287 | |||
| 288 | $queue = Craft::$app->getQueue(); |
||
| 289 | $jobId = $queue->push(new ResaveOptimizedImages([ |
||
| 290 | 'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]), |
||
| 291 | 'criteria' => [ |
||
| 292 | 'siteId' => $siteId, |
||
| 293 | 'volumeId' => $volume->id, |
||
| 294 | 'status' => null, |
||
| 295 | 'enabledForSite' => false, |
||
| 296 | ], |
||
| 297 | ])); |
||
| 298 | Craft::debug( |
||
| 299 | Craft::t( |
||
| 300 | 'image-optimize', |
||
| 301 | 'Started resaveVolumeAssets queue job id: {jobId}', |
||
| 302 | [ |
||
| 303 | 'jobId' => $jobId, |
||
| 304 | ] |
||
| 305 | ), |
||
| 306 | __METHOD__ |
||
| 307 | ); |
||
| 308 | } |
||
| 309 | } |
||
| 310 | |||
| 311 | /** |
||
| 312 | * Re-save an individual asset |
||
| 313 | * |
||
| 314 | * @param int $id |
||
| 315 | */ |
||
| 316 | public function resaveAsset(int $id) |
||
| 317 | { |
||
| 318 | $queue = Craft::$app->getQueue(); |
||
| 319 | $jobId = $queue->push(new ResaveOptimizedImages([ |
||
| 320 | 'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]), |
||
| 321 | 'criteria' => [ |
||
| 322 | 'id' => $id, |
||
| 323 | 'status' => null, |
||
| 324 | 'enabledForSite' => false, |
||
| 325 | ], |
||
| 326 | ])); |
||
| 327 | Craft::debug( |
||
| 328 | Craft::t( |
||
| 329 | 'image-optimize', |
||
| 330 | 'Started resaveAsset queue job id: {jobId} Element id: {elementId}', |
||
| 331 | [ |
||
| 332 | 'elementId' => $id, |
||
| 333 | 'jobId' => $jobId, |
||
| 334 | ] |
||
| 335 | ), |
||
| 336 | __METHOD__ |
||
| 337 | ); |
||
| 338 | } |
||
| 339 | |||
| 340 | /** |
||
| 341 | * Create an optimized SVG data uri |
||
| 342 | * See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris |
||
| 343 | * |
||
| 344 | * @param string $uri |
||
| 345 | * |
||
| 346 | * @return string |
||
| 347 | */ |
||
| 348 | public function encodeOptimizedSVGDataUri(string $uri): string |
||
| 349 | { |
||
| 350 | // First, uri encode everything |
||
| 351 | $uri = rawurlencode($uri); |
||
| 352 | $replacements = [ |
||
| 353 | // remove newlines |
||
| 354 | '/%0A/' => '', |
||
| 355 | // put spaces back in |
||
| 356 | '/%20/' => ' ', |
||
| 357 | // put equals signs back in |
||
| 358 | '/%3D/' => '=', |
||
| 359 | // put colons back in |
||
| 360 | '/%3A/' => ':', |
||
| 361 | // put slashes back in |
||
| 362 | '/%2F/' => '/', |
||
| 363 | // replace quotes with apostrophes (may break certain SVGs) |
||
| 364 | '/%22/' => "'", |
||
| 365 | ]; |
||
| 366 | foreach ($replacements as $pattern => $replacement) { |
||
| 367 | $uri = preg_replace($pattern, $replacement, $uri); |
||
| 368 | } |
||
| 369 | |||
| 370 | return $uri; |
||
| 371 | } |
||
| 372 | |||
| 373 | // Protected Methods |
||
| 374 | // ========================================================================= |
||
| 375 | |||
| 376 | /** |
||
| 377 | * @param Asset $element |
||
| 378 | * @param OptimizedImage $model |
||
| 379 | * @param $aspectRatio |
||
| 380 | */ |
||
| 381 | protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio) |
||
| 410 | } |
||
| 411 | |||
| 412 | /** |
||
| 413 | * @param Asset $asset |
||
| 414 | * @param $variant |
||
| 415 | * @param $retinaSize |
||
| 416 | * |
||
| 417 | * @return array |
||
| 418 | */ |
||
| 419 | protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array |
||
| 462 | } |
||
| 463 | |||
| 464 | /** |
||
| 465 | * @param Asset $asset |
||
| 466 | * @param OptimizedImage $model |
||
| 467 | * @param $transform |
||
| 468 | * @param $variant |
||
| 469 | * @param $aspectRatio |
||
| 470 | */ |
||
| 471 | protected function addVariantImageToModel(Asset $asset, OptimizedImage $model, $transform, $variant, $aspectRatio) |
||
| 515 |