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