Total Complexity | 89 |
Total Lines | 569 |
Duplicated Lines | 0 % |
Changes | 16 | ||
Bugs | 1 | Features | 0 |
Complex classes like Asset 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 Asset, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
23 | class Asset implements \ArrayAccess |
||
24 | { |
||
25 | /** @var Builder */ |
||
26 | protected $builder; |
||
27 | |||
28 | /** @var Config */ |
||
29 | protected $config; |
||
30 | |||
31 | /** @var array */ |
||
32 | protected $data = []; |
||
33 | |||
34 | /** @var bool */ |
||
35 | protected $fingerprinted = false; |
||
36 | |||
37 | /** @var bool */ |
||
38 | protected $compiled = false; |
||
39 | |||
40 | /** @var bool */ |
||
41 | protected $minified = false; |
||
42 | |||
43 | /** @var bool */ |
||
44 | protected $ignore_missing = false; |
||
45 | |||
46 | /** |
||
47 | * Creates an Asset from file(s) path. |
||
48 | * |
||
49 | * $options[ |
||
50 | * 'fingerprint' => true, |
||
51 | * 'minify' => true, |
||
52 | * 'filename' => '', |
||
53 | * 'ignore_missing' => false, |
||
54 | * ]; |
||
55 | * |
||
56 | * @param Builder $builder |
||
57 | * @param string|array $paths |
||
58 | * @param array|null $options |
||
59 | */ |
||
60 | public function __construct(Builder $builder, $paths, array $options = null) |
||
61 | { |
||
62 | $this->builder = $builder; |
||
63 | $this->config = $builder->getConfig(); |
||
64 | $paths = is_array($paths) ? $paths : [$paths]; |
||
65 | |||
66 | // handles options |
||
67 | $fingerprint = (bool) $this->config->get('assets.fingerprint.enabled'); |
||
68 | $minify = (bool) $this->config->get('assets.minify.enabled'); |
||
69 | $filename = ''; |
||
70 | $ignore_missing = false; |
||
71 | extract(is_array($options) ? $options : [], EXTR_IF_EXISTS); |
||
72 | $this->ignore_missing = $ignore_missing; |
||
73 | |||
74 | // fill data array with file(s) informations |
||
75 | $cache = new Cache($this->builder, 'assets'); |
||
76 | $cacheKey = sprintf('%s.ser', implode('_', $paths)); |
||
77 | if (!$cache->has($cacheKey)) { |
||
78 | $pathsCount = count($paths); |
||
79 | $this->data = [ |
||
80 | 'file' => '', |
||
81 | 'filename' => '', |
||
82 | 'path' => '', |
||
83 | 'ext' => '', |
||
84 | 'type' => '', |
||
85 | 'subtype' => '', |
||
86 | 'size' => 0, |
||
87 | 'source' => '', |
||
88 | 'content' => '', |
||
89 | ]; |
||
90 | $file = []; |
||
91 | for ($i = 0; $i < $pathsCount; $i++) { |
||
92 | // loads file(s) |
||
93 | $file[$i] = $this->loadFile($paths[$i], $ignore_missing); |
||
94 | // bundle: same type/ext only |
||
95 | if ($i > 0) { |
||
96 | if ($file[$i]['type'] != $file[$i - 1]['type']) { |
||
97 | throw new Exception(\sprintf('Asset bundle type error (%s != %s).', $file[$i]['type'], $file[$i - 1]['type'])); |
||
98 | } |
||
99 | if ($file[$i]['ext'] != $file[$i - 1]['ext']) { |
||
100 | throw new Exception(\sprintf('Asset bundle extension error (%s != %s).', $file[$i]['ext'], $file[$i - 1]['ext'])); |
||
101 | } |
||
102 | } |
||
103 | // missing allowed = empty path |
||
104 | if ($file[$i]['missing']) { |
||
105 | $this->data['path'] = ''; |
||
106 | |||
107 | continue; |
||
108 | } |
||
109 | // set data |
||
110 | if ($i == 0) { |
||
111 | $this->data['file'] = $file[$i]['filepath']; // should be an array of files in case of bundle? |
||
112 | $this->data['filename'] = $file[$i]['path']; |
||
113 | $this->data['path'] = $file[$i]['path']; |
||
114 | if (!empty($filename)) { |
||
115 | $this->data['path'] = '/'.ltrim($filename, '/'); |
||
116 | } |
||
117 | $this->data['ext'] = $file[$i]['ext']; |
||
118 | $this->data['type'] = $file[$i]['type']; |
||
119 | $this->data['subtype'] = $file[$i]['subtype']; |
||
120 | } |
||
121 | $this->data['size'] += $file[$i]['size']; |
||
122 | $this->data['source'] .= $file[$i]['content']; |
||
123 | $this->data['content'] .= $file[$i]['content']; |
||
124 | } |
||
125 | // bundle: define path |
||
126 | if ($pathsCount > 1) { |
||
127 | if (empty($filename)) { |
||
128 | switch ($this->data['ext']) { |
||
129 | case 'scss': |
||
130 | case 'css': |
||
131 | $this->data['path'] = '/styles.'.$file[0]['ext']; |
||
132 | break; |
||
133 | case 'js': |
||
134 | $this->data['path'] = '/scripts.'.$file[0]['ext']; |
||
135 | break; |
||
136 | default: |
||
137 | throw new Exception(\sprintf('Asset bundle supports "%s" files only.', 'scss, css and js')); |
||
138 | } |
||
139 | } |
||
140 | } |
||
141 | $cache->set($cacheKey, $this->data); |
||
142 | } |
||
143 | $this->data = $cache->get($cacheKey); |
||
144 | |||
145 | // fingerprinting |
||
146 | if ($fingerprint) { |
||
147 | $this->fingerprint(); |
||
148 | } |
||
149 | // compiling |
||
150 | if ((bool) $this->config->get('assets.compile.enabled')) { |
||
151 | $this->compile(); |
||
152 | } |
||
153 | // minifying |
||
154 | if ($minify) { |
||
155 | $this->minify(); |
||
156 | } |
||
157 | } |
||
158 | |||
159 | /** |
||
160 | * Returns path. |
||
161 | */ |
||
162 | public function __toString(): string |
||
163 | { |
||
164 | try { |
||
165 | $this->save(); |
||
166 | } catch (Exception $e) { |
||
167 | $this->builder->getLogger()->error($e->getMessage()); |
||
168 | } |
||
169 | |||
170 | return $this->data['path']; |
||
171 | } |
||
172 | |||
173 | /** |
||
174 | * Fingerprints a file. |
||
175 | */ |
||
176 | public function fingerprint(): self |
||
177 | { |
||
178 | if ($this->fingerprinted) { |
||
179 | return $this; |
||
180 | } |
||
181 | |||
182 | $fingerprint = hash('md5', $this->data['source']); |
||
183 | $this->data['path'] = preg_replace( |
||
184 | '/\.'.$this->data['ext'].'$/m', |
||
185 | ".$fingerprint.".$this->data['ext'], |
||
186 | $this->data['path'] |
||
187 | ); |
||
188 | |||
189 | $this->fingerprinted = true; |
||
190 | |||
191 | return $this; |
||
192 | } |
||
193 | |||
194 | /** |
||
195 | * Compiles a SCSS. |
||
196 | */ |
||
197 | public function compile(): self |
||
263 | } |
||
264 | |||
265 | /** |
||
266 | * Minifying a CSS or a JS. |
||
267 | */ |
||
268 | public function minify(): self |
||
318 | } |
||
319 | |||
320 | /** |
||
321 | * Resizes an image. |
||
322 | */ |
||
323 | public function resize(int $size): self |
||
324 | { |
||
325 | $cache = new Cache($this->builder, 'assets'); |
||
326 | $cacheKey = $cache->createKeyFromAsset($this, $size); |
||
327 | if (!$cache->has($cacheKey)) { |
||
328 | if ($this->data['type'] !== 'image') { |
||
329 | throw new Exception(sprintf('Not able to resize "%s"', $this->data['path'])); |
||
330 | } |
||
331 | if (!extension_loaded('gd')) { |
||
332 | throw new Exception('GD extension is required to use images resize.'); |
||
333 | } |
||
334 | |||
335 | try { |
||
336 | $img = ImageManager::make($this->data['source']); |
||
337 | $img->resize($size, null, function (\Intervention\Image\Constraint $constraint) { |
||
338 | $constraint->aspectRatio(); |
||
339 | $constraint->upsize(); |
||
340 | }); |
||
341 | } catch (\Exception $e) { |
||
342 | throw new Exception(sprintf('Not able to resize image "%s": ', $this->data['path'], $e->getMessage())); |
||
343 | } |
||
344 | $this->data['path'] = '/'.Util::joinPath((string) $this->config->get('assets.target'), 'thumbnails', (string) $size, $this->data['path']); |
||
345 | |||
346 | try { |
||
347 | $this->data['content'] = (string) $img->encode($this->data['ext'], $this->config->get('assets.images.quality')); |
||
348 | } catch (\Exception $e) { |
||
349 | throw new Exception(sprintf('Not able to encode image "%s": ', $this->data['path'], $e->getMessage())); |
||
350 | } |
||
351 | |||
352 | $cache->set($cacheKey, $this->data); |
||
353 | } |
||
354 | $this->data = $cache->get($cacheKey); |
||
355 | |||
356 | return $this; |
||
357 | } |
||
358 | |||
359 | /** |
||
360 | * Returns the data URL of an image. |
||
361 | */ |
||
362 | public function dataurl(): string |
||
363 | { |
||
364 | if ($this->data['type'] !== 'image') { |
||
365 | throw new Exception(sprintf('Can\'t get data URL of "%s"', $this->data['path'])); |
||
366 | } |
||
367 | |||
368 | return (string) ImageManager::make($this->data['content'])->encode('data-url', $this->config->get('assets.images.quality')); |
||
369 | } |
||
370 | |||
371 | /** |
||
372 | * Implements \ArrayAccess. |
||
373 | */ |
||
374 | public function offsetSet($offset, $value) |
||
375 | { |
||
376 | if (!is_null($offset)) { |
||
377 | $this->data[$offset] = $value; |
||
378 | } |
||
379 | } |
||
380 | |||
381 | /** |
||
382 | * Implements \ArrayAccess. |
||
383 | */ |
||
384 | public function offsetExists($offset) |
||
385 | { |
||
386 | return isset($this->data[$offset]); |
||
387 | } |
||
388 | |||
389 | /** |
||
390 | * Implements \ArrayAccess. |
||
391 | */ |
||
392 | public function offsetUnset($offset) |
||
393 | { |
||
394 | unset($this->data[$offset]); |
||
395 | } |
||
396 | |||
397 | /** |
||
398 | * Implements \ArrayAccess. |
||
399 | */ |
||
400 | public function offsetGet($offset) |
||
401 | { |
||
402 | return isset($this->data[$offset]) ? $this->data[$offset] : null; |
||
403 | } |
||
404 | |||
405 | /** |
||
406 | * Hashing content of an asset with the specified algo, sha384 by default. |
||
407 | * Used for SRI (Subresource Integrity). |
||
408 | * |
||
409 | * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity |
||
410 | */ |
||
411 | public function getIntegrity(string $algo = 'sha384'): string |
||
412 | { |
||
413 | return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true))); |
||
414 | } |
||
415 | |||
416 | /** |
||
417 | * Returns the width of an image. |
||
418 | * |
||
419 | * @return false|int |
||
420 | */ |
||
421 | public function getWidth() |
||
422 | { |
||
423 | if (false === $size = $this->getImageSize()) { |
||
424 | return false; |
||
425 | } |
||
426 | |||
427 | return $size[0]; |
||
428 | } |
||
429 | |||
430 | /** |
||
431 | * Returns the height of an image. |
||
432 | * |
||
433 | * @return false|int |
||
434 | */ |
||
435 | public function getHeight() |
||
436 | { |
||
437 | if (false === $size = $this->getImageSize()) { |
||
438 | return false; |
||
439 | } |
||
440 | |||
441 | return $size[1]; |
||
442 | } |
||
443 | |||
444 | /** |
||
445 | * Returns MP3 file infos. |
||
446 | * |
||
447 | * @see https://github.com/wapmorgan/Mp3Info |
||
448 | */ |
||
449 | public function getAudio(): Mp3Info |
||
450 | { |
||
451 | return new Mp3Info($this->data['file']); |
||
452 | } |
||
453 | |||
454 | /** |
||
455 | * Saves file. |
||
456 | * Note: a file from `static/` with the same name will NOT be overridden. |
||
457 | * |
||
458 | * @throws Exception |
||
459 | */ |
||
460 | public function save(): void |
||
461 | { |
||
462 | $filepath = Util::joinFile($this->config->getOutputPath(), $this->data['path']); |
||
463 | if (!$this->builder->getBuildOptions()['dry-run'] |
||
464 | && !Util\File::getFS()->exists($filepath) |
||
465 | ) { |
||
466 | try { |
||
467 | Util\File::getFS()->dumpFile($filepath, $this->data['content']); |
||
468 | $this->builder->getLogger()->debug(sprintf('Save asset "%s"', $this->data['path'])); |
||
469 | } catch (\Symfony\Component\Filesystem\Exception\IOException $e) { |
||
470 | if (!$this->ignore_missing) { |
||
471 | throw new Exception(\sprintf('Can\'t save asset "%s"', $this->data['path'])); |
||
472 | } |
||
473 | } |
||
474 | } |
||
475 | } |
||
476 | |||
477 | /** |
||
478 | * Load file data. |
||
479 | */ |
||
480 | private function loadFile(string $path, bool $ignore_missing = false): array |
||
523 | } |
||
524 | |||
525 | /** |
||
526 | * Try to find the file: |
||
527 | * 1. remote (if $path is a valid URL) |
||
528 | * 2. in static/ |
||
529 | * 3. in themes/<theme>/static/ |
||
530 | * Returns local file path or false if file don't exists. |
||
531 | * |
||
532 | * @return string|false |
||
533 | */ |
||
534 | private function findFile(string $path) |
||
535 | { |
||
536 | // in case of remote file: save it and returns cached file path |
||
537 | if (Util\Url::isUrl($path)) { |
||
538 | $url = $path; |
||
539 | $relativePath = Page::slugify(sprintf('%s%s-%s', parse_url($url, PHP_URL_HOST), parse_url($url, PHP_URL_PATH), parse_url($url, PHP_URL_QUERY))); |
||
540 | $filePath = Util::joinFile($this->config->getCacheAssetsPath(), $relativePath); |
||
541 | if (!file_exists($filePath)) { |
||
542 | if (!Util\Url::isRemoteFileExists($url)) { |
||
543 | return false; |
||
544 | } |
||
545 | if (false === $content = Util\File::fileGetContents($url, true)) { |
||
546 | return false; |
||
547 | } |
||
548 | if (strlen($content) <= 1) { |
||
549 | throw new Exception(sprintf('Asset at "%s" is empty.', $url)); |
||
550 | } |
||
551 | Util\File::getFS()->dumpFile($filePath, $content); |
||
552 | } |
||
553 | |||
554 | return $filePath; |
||
555 | } |
||
556 | |||
557 | // checks in static/ |
||
558 | $filePath = Util::joinFile($this->config->getStaticPath(), $path); |
||
559 | if (Util\File::getFS()->exists($filePath)) { |
||
560 | return $filePath; |
||
561 | } |
||
562 | |||
563 | // checks in each themes/<theme>/static/ |
||
564 | foreach ($this->config->getTheme() as $theme) { |
||
565 | $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path); |
||
566 | if (Util\File::getFS()->exists($filePath)) { |
||
567 | return $filePath; |
||
568 | } |
||
569 | } |
||
570 | |||
571 | return false; |
||
572 | } |
||
573 | |||
574 | /** |
||
575 | * Returns image size informations. |
||
576 | * |
||
577 | * @see https://www.php.net/manual/function.getimagesize.php |
||
578 | * |
||
579 | * @return false|array |
||
580 | */ |
||
581 | private function getImageSize() |
||
592 | } |
||
593 | } |
||
594 |