| Total Complexity | 159 |
| Total Lines | 1004 |
| Duplicated Lines | 0 % |
| Changes | 3 | ||
| 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 |
||
| 38 | class Asset implements \ArrayAccess |
||
| 39 | { |
||
| 40 | public const IMAGE_THUMB = 'thumbnails'; |
||
| 41 | |||
| 42 | /** @var Builder */ |
||
| 43 | protected $builder; |
||
| 44 | |||
| 45 | /** @var Config */ |
||
| 46 | protected $config; |
||
| 47 | |||
| 48 | /** @var array */ |
||
| 49 | protected $data = []; |
||
| 50 | |||
| 51 | /** @var array Cache tags */ |
||
| 52 | protected $cacheTags = []; |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Creates an Asset from a file path, an array of files path or an URL. |
||
| 56 | * Options: |
||
| 57 | * [ |
||
| 58 | * 'filename' => <string>, |
||
| 59 | * 'leading_slash' => <bool> |
||
| 60 | * 'ignore_missing' => <bool>, |
||
| 61 | * 'fingerprint' => <bool>, |
||
| 62 | * 'minify' => <bool>, |
||
| 63 | * 'optimize' => <bool>, |
||
| 64 | * 'fallback' => <string>, |
||
| 65 | * 'useragent' => <string>, |
||
| 66 | * ] |
||
| 67 | * |
||
| 68 | * @param Builder $builder |
||
| 69 | * @param string|array $paths |
||
| 70 | * @param array|null $options |
||
| 71 | * |
||
| 72 | * @throws RuntimeException |
||
| 73 | */ |
||
| 74 | public function __construct(Builder $builder, string|array $paths, array|null $options = null) |
||
| 248 | } |
||
| 249 | |||
| 250 | /** |
||
| 251 | * Returns path. |
||
| 252 | */ |
||
| 253 | public function __toString(): string |
||
| 254 | { |
||
| 255 | $this->save(); |
||
| 256 | |||
| 257 | if ($this->isImageInCdn()) { |
||
| 258 | return $this->buildImageCdnUrl(); |
||
| 259 | } |
||
| 260 | |||
| 261 | if ($this->builder->getConfig()->isEnabled('canonicalurl')) { |
||
| 262 | return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]); |
||
| 263 | } |
||
| 264 | |||
| 265 | return $this->data['path']; |
||
| 266 | } |
||
| 267 | |||
| 268 | /** |
||
| 269 | * Implements \ArrayAccess. |
||
| 270 | */ |
||
| 271 | #[\ReturnTypeWillChange] |
||
| 272 | public function offsetSet($offset, $value): void |
||
| 273 | { |
||
| 274 | if (!\is_null($offset)) { |
||
| 275 | $this->data[$offset] = $value; |
||
| 276 | } |
||
| 277 | } |
||
| 278 | |||
| 279 | /** |
||
| 280 | * Implements \ArrayAccess. |
||
| 281 | */ |
||
| 282 | #[\ReturnTypeWillChange] |
||
| 283 | public function offsetExists($offset): bool |
||
| 284 | { |
||
| 285 | return isset($this->data[$offset]); |
||
| 286 | } |
||
| 287 | |||
| 288 | /** |
||
| 289 | * Implements \ArrayAccess. |
||
| 290 | */ |
||
| 291 | #[\ReturnTypeWillChange] |
||
| 292 | public function offsetUnset($offset): void |
||
| 293 | { |
||
| 294 | unset($this->data[$offset]); |
||
| 295 | } |
||
| 296 | |||
| 297 | /** |
||
| 298 | * Implements \ArrayAccess. |
||
| 299 | */ |
||
| 300 | #[\ReturnTypeWillChange] |
||
| 301 | public function offsetGet($offset) |
||
| 302 | { |
||
| 303 | return isset($this->data[$offset]) ? $this->data[$offset] : null; |
||
| 304 | } |
||
| 305 | |||
| 306 | /** |
||
| 307 | * Adds asset path to the list of assets to save. |
||
| 308 | * |
||
| 309 | * @throws RuntimeException |
||
| 310 | */ |
||
| 311 | public function save(): void |
||
| 323 | } |
||
| 324 | |||
| 325 | /** |
||
| 326 | * Add hash to the file name + cache. |
||
| 327 | */ |
||
| 328 | public function fingerprint(): self |
||
| 340 | } |
||
| 341 | |||
| 342 | /** |
||
| 343 | * Compiles a SCSS + cache. |
||
| 344 | * |
||
| 345 | * @throws RuntimeException |
||
| 346 | */ |
||
| 347 | public function compile(): self |
||
| 348 | { |
||
| 349 | $this->cacheTags['compile'] = true; |
||
| 350 | $cache = new Cache($this->builder, 'assets'); |
||
| 351 | $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags); |
||
| 352 | if (!$cache->has($cacheKey)) { |
||
| 353 | $this->doCompile(); |
||
| 354 | $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl')); |
||
| 355 | } |
||
| 356 | $this->data = $cache->get($cacheKey); |
||
| 357 | |||
| 358 | return $this; |
||
| 359 | } |
||
| 360 | |||
| 361 | /** |
||
| 362 | * Minifying a CSS or a JS. |
||
| 363 | */ |
||
| 364 | public function minify(): self |
||
| 365 | { |
||
| 366 | $this->cacheTags['minify'] = true; |
||
| 367 | $cache = new Cache($this->builder, 'assets'); |
||
| 368 | $cacheKey = $cache->createKeyFromAsset($this, $this->cacheTags); |
||
| 369 | if (!$cache->has($cacheKey)) { |
||
| 370 | $this->doMinify(); |
||
| 371 | $cache->set($cacheKey, $this->data, $this->config->get('cache.assets.ttl')); |
||
| 372 | } |
||
| 373 | $this->data = $cache->get($cacheKey); |
||
| 374 | |||
| 375 | return $this; |
||
| 376 | } |
||
| 377 | |||
| 378 | /** |
||
| 379 | * Returns the Data URL (encoded in Base64). |
||
| 380 | * |
||
| 381 | * @throws RuntimeException |
||
| 382 | */ |
||
| 383 | public function dataurl(): string |
||
| 390 | } |
||
| 391 | |||
| 392 | /** |
||
| 393 | * Hashing content of an asset with the specified algo, sha384 by default. |
||
| 394 | * Used for SRI (Subresource Integrity). |
||
| 395 | * |
||
| 396 | * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity |
||
| 397 | */ |
||
| 398 | public function integrity(string $algo = 'sha384'): string |
||
| 401 | } |
||
| 402 | |||
| 403 | /** |
||
| 404 | * Resizes an image to the given width or/and height. |
||
| 405 | * |
||
| 406 | * - If only the width is specified, the height is calculated to preserve the aspect ratio |
||
| 407 | * - If only the height is specified, the width is calculated to preserve the aspect ratio |
||
| 408 | * - If both width and height are specified, the image is resized to fit within the given dimensions, image is cropped and centered if necessary |
||
| 409 | * - If rmAnimation is true, any animation in the image (e.g., GIF) will be removed. |
||
| 410 | * |
||
| 411 | * @throws RuntimeException |
||
| 412 | */ |
||
| 413 | public function resize(?int $width = null, ?int $height = null, bool $rmAnimation = false): self |
||
| 414 | { |
||
| 415 | $this->checkImage(); |
||
| 416 | |||
| 417 | // if no width and no height, return the original image |
||
| 418 | if ($width === null && $height === null) { |
||
| 419 | return $this; |
||
| 420 | } |
||
| 421 | |||
| 422 | // if the image width or height is already smaller, return it |
||
| 423 | if ($width !== null && $this->data['width'] <= $width && $height === null) { |
||
| 424 | return $this; |
||
| 425 | } |
||
| 426 | if ($height !== null && $this->data['height'] <= $height && $width === null) { |
||
| 427 | return $this; |
||
| 428 | } |
||
| 429 | |||
| 430 | $assetResized = clone $this; |
||
| 431 | $assetResized->data['width'] = $width ?? $this->data['width']; |
||
| 432 | $assetResized->data['height'] = $height ?? $this->data['height']; |
||
| 433 | |||
| 434 | if ($this->isImageInCdn()) { |
||
| 435 | if ($width === null) { |
||
| 436 | $assetResized->data['width'] = round($this->data['width'] / ($this->data['height'] / $height)); |
||
| 437 | } |
||
| 438 | if ($height === null) { |
||
| 439 | $assetResized->data['height'] = round($this->data['height'] / ($this->data['width'] / $width)); |
||
| 440 | } |
||
| 441 | |||
| 442 | return $assetResized; // returns asset with the new dimensions only: CDN do the rest of the job |
||
| 443 | } |
||
| 444 | |||
| 445 | $quality = (int) $this->config->get('assets.images.quality'); |
||
| 446 | |||
| 447 | $cache = new Cache($this->builder, 'assets'); |
||
| 448 | $assetResized->cacheTags['quality'] = $quality; |
||
| 449 | $assetResized->cacheTags['width'] = $width; |
||
| 450 | $assetResized->cacheTags['height'] = $height; |
||
| 451 | $cacheKey = $cache->createKeyFromAsset($assetResized, $assetResized->cacheTags); |
||
| 452 | if (!$cache->has($cacheKey)) { |
||
| 453 | $assetResized->data['content'] = Image::resize($assetResized, $width, $height, $quality, $rmAnimation); |
||
| 454 | $assetResized->data['path'] = '/' . Util::joinPath( |
||
| 455 | (string) $this->config->get('assets.target'), |
||
| 456 | self::IMAGE_THUMB, |
||
| 457 | (string) $width . 'x' . (string) $height, |
||
| 458 | $assetResized->data['path'] |
||
| 459 | ); |
||
| 460 | $assetResized->data['path'] = $this->deduplicateThumbPath($assetResized->data['path']); |
||
| 461 | $assetResized->data['width'] = $assetResized->getWidth(); |
||
| 462 | $assetResized->data['height'] = $assetResized->getHeight(); |
||
| 463 | $assetResized->data['size'] = \strlen($assetResized->data['content']); |
||
| 464 | |||
| 465 | $cache->set($cacheKey, $assetResized->data, $this->config->get('cache.assets.ttl')); |
||
| 466 | $this->builder->getLogger()->debug(\sprintf('Asset resized: "%s" (%sx%s)', $assetResized->data['path'], $width, $height)); |
||
| 467 | } |
||
| 468 | $assetResized->data = $cache->get($cacheKey); |
||
| 469 | |||
| 470 | return $assetResized; |
||
| 471 | } |
||
| 472 | |||
| 473 | /** |
||
| 474 | * Creates a maskable image (with a padding = 20%). |
||
| 475 | * |
||
| 476 | * @throws RuntimeException |
||
| 477 | */ |
||
| 478 | public function maskable(?int $padding = null): self |
||
| 479 | { |
||
| 480 | $this->checkImage(); |
||
| 481 | |||
| 482 | if ($padding === null) { |
||
| 483 | $padding = 20; // default padding |
||
| 484 | } |
||
| 485 | |||
| 486 | $assetMaskable = clone $this; |
||
| 487 | |||
| 488 | $quality = (int) $this->config->get('assets.images.quality'); |
||
| 489 | |||
| 490 | $cache = new Cache($this->builder, 'assets'); |
||
| 491 | $assetMaskable->cacheTags['maskable'] = true; |
||
| 492 | $cacheKey = $cache->createKeyFromAsset($assetMaskable, $assetMaskable->cacheTags); |
||
| 493 | if (!$cache->has($cacheKey)) { |
||
| 494 | $assetMaskable->data['content'] = Image::maskable($assetMaskable, $quality, $padding); |
||
| 495 | $assetMaskable->data['path'] = '/' . Util::joinPath( |
||
| 496 | (string) $this->config->get('assets.target'), |
||
| 497 | 'maskable', |
||
| 498 | $assetMaskable->data['path'] |
||
| 499 | ); |
||
| 500 | $assetMaskable->data['size'] = \strlen($assetMaskable->data['content']); |
||
| 501 | |||
| 502 | $cache->set($cacheKey, $assetMaskable->data, $this->config->get('cache.assets.ttl')); |
||
| 503 | $this->builder->getLogger()->debug(\sprintf('Asset maskabled: "%s"', $assetMaskable->data['path'])); |
||
| 504 | } |
||
| 505 | $assetMaskable->data = $cache->get($cacheKey); |
||
| 506 | |||
| 507 | return $assetMaskable; |
||
| 508 | } |
||
| 509 | |||
| 510 | /** |
||
| 511 | * Converts an image asset to $format format. |
||
| 512 | * |
||
| 513 | * @throws RuntimeException |
||
| 514 | */ |
||
| 515 | public function convert(string $format, ?int $quality = null): self |
||
| 516 | { |
||
| 517 | if ($this->data['type'] != 'image') { |
||
| 518 | throw new RuntimeException(\sprintf('Unable to convert "%s" (%s) to %s: not an image.', $this->data['path'], $this->data['type'], $format)); |
||
| 519 | } |
||
| 520 | |||
| 521 | if ($quality === null) { |
||
| 522 | $quality = (int) $this->config->get('assets.images.quality'); |
||
| 523 | } |
||
| 524 | |||
| 525 | $asset = clone $this; |
||
| 526 | $asset['ext'] = $format; |
||
| 527 | $asset->data['subtype'] = "image/$format"; |
||
| 528 | |||
| 529 | if ($this->isImageInCdn()) { |
||
| 530 | return $asset; // returns the asset with the new extension only: CDN do the rest of the job |
||
| 531 | } |
||
| 532 | |||
| 533 | $cache = new Cache($this->builder, 'assets'); |
||
| 534 | $this->cacheTags['quality'] = $quality; |
||
| 535 | if ($this->data['width']) { |
||
| 536 | $this->cacheTags['width'] = $this->data['width']; |
||
| 537 | } |
||
| 538 | $cacheKey = $cache->createKeyFromAsset($asset, $this->cacheTags); |
||
| 539 | if (!$cache->has($cacheKey)) { |
||
| 540 | $asset->data['content'] = Image::convert($asset, $format, $quality); |
||
| 541 | $asset->data['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']); |
||
| 542 | $asset->data['size'] = \strlen($asset->data['content']); |
||
| 543 | $cache->set($cacheKey, $asset->data, $this->config->get('cache.assets.ttl')); |
||
| 544 | $this->builder->getLogger()->debug(\sprintf('Asset converted: "%s" (%s -> %s)', $asset->data['path'], $this->data['ext'], $format)); |
||
| 545 | } |
||
| 546 | $asset->data = $cache->get($cacheKey); |
||
| 547 | |||
| 548 | return $asset; |
||
| 549 | } |
||
| 550 | |||
| 551 | /** |
||
| 552 | * Converts an image asset to WebP format. |
||
| 553 | * |
||
| 554 | * @throws RuntimeException |
||
| 555 | */ |
||
| 556 | public function webp(?int $quality = null): self |
||
| 557 | { |
||
| 558 | return $this->convert('webp', $quality); |
||
| 559 | } |
||
| 560 | |||
| 561 | /** |
||
| 562 | * Converts an image asset to AVIF format. |
||
| 563 | * |
||
| 564 | * @throws RuntimeException |
||
| 565 | */ |
||
| 566 | public function avif(?int $quality = null): self |
||
| 567 | { |
||
| 568 | return $this->convert('avif', $quality); |
||
| 569 | } |
||
| 570 | |||
| 571 | /** |
||
| 572 | * Is the asset an image and is it in CDN? |
||
| 573 | */ |
||
| 574 | public function isImageInCdn(): bool |
||
| 575 | { |
||
| 576 | if ( |
||
| 577 | $this->data['type'] == 'image' |
||
| 578 | && $this->config->isEnabled('assets.images.cdn') |
||
| 579 | && $this->data['ext'] != 'ico' |
||
| 580 | && (Image::isSVG($this) && $this->config->isEnabled('assets.images.cdn.svg')) |
||
| 581 | ) { |
||
| 582 | return true; |
||
| 583 | } |
||
| 584 | // handle remote image? |
||
| 585 | if ($this->data['url'] !== null && $this->config->isEnabled('assets.images.cdn.remote')) { |
||
| 586 | return true; |
||
| 587 | } |
||
| 588 | |||
| 589 | return false; |
||
| 590 | } |
||
| 591 | |||
| 592 | /** |
||
| 593 | * Returns the width of an image/SVG or a video. |
||
| 594 | * |
||
| 595 | * @throws RuntimeException |
||
| 596 | */ |
||
| 597 | public function getWidth(): ?int |
||
| 598 | { |
||
| 599 | switch ($this->data['type']) { |
||
| 600 | case 'image': |
||
| 601 | if (Image::isSVG($this) && false !== $svg = Image::getSvgAttributes($this)) { |
||
| 602 | return (int) $svg->width; |
||
| 603 | } |
||
| 604 | if (false === $size = $this->getImageSize()) { |
||
| 605 | throw new RuntimeException(\sprintf('Unable to get width of "%s".', $this->data['path'])); |
||
| 606 | } |
||
| 607 | |||
| 608 | return $size[0]; |
||
| 609 | case 'video': |
||
| 610 | return $this->getVideo()['width']; |
||
| 611 | } |
||
| 612 | |||
| 613 | return null; |
||
| 614 | } |
||
| 615 | |||
| 616 | /** |
||
| 617 | * Returns the height of an image/SVG or a video. |
||
| 618 | * |
||
| 619 | * @throws RuntimeException |
||
| 620 | */ |
||
| 621 | public function getHeight(): ?int |
||
| 638 | } |
||
| 639 | |||
| 640 | /** |
||
| 641 | * Returns audio file infos: |
||
| 642 | * - duration (in seconds.microseconds) |
||
| 643 | * - bitrate (in bps) |
||
| 644 | * - channel ('stereo', 'dual_mono', 'joint_stereo' or 'mono') |
||
| 645 | * |
||
| 646 | * @see https://github.com/wapmorgan/Mp3Info |
||
| 647 | */ |
||
| 648 | public function getAudio(): array |
||
| 649 | { |
||
| 650 | $audio = new Mp3Info($this->data['file']); |
||
| 651 | |||
| 652 | return [ |
||
| 653 | 'duration' => $audio->duration, |
||
| 654 | 'bitrate' => $audio->bitRate, |
||
| 655 | 'channel' => $audio->channel, |
||
| 656 | ]; |
||
| 657 | } |
||
| 658 | |||
| 659 | /** |
||
| 660 | * Returns video file infos: |
||
| 661 | * - duration (in seconds) |
||
| 662 | * - width (in pixels) |
||
| 663 | * - height (in pixels) |
||
| 664 | * |
||
| 665 | * @see https://github.com/JamesHeinrich/getID3 |
||
| 666 | */ |
||
| 667 | public function getVideo(): array |
||
| 668 | { |
||
| 669 | if ($this->data['type'] !== 'video') { |
||
| 670 | throw new RuntimeException(\sprintf('Unable to get video infos of "%s".', $this->data['path'])); |
||
| 671 | } |
||
| 672 | |||
| 673 | $video = (new \getID3())->analyze($this->data['file']); |
||
| 674 | |||
| 675 | return [ |
||
| 676 | 'duration' => $video['playtime_seconds'], |
||
| 677 | 'width' => $video['video']['resolution_x'], |
||
| 678 | 'height' => $video['video']['resolution_y'], |
||
| 679 | ]; |
||
| 680 | } |
||
| 681 | |||
| 682 | /** |
||
| 683 | * Builds a relative path from a URL. |
||
| 684 | * Used for remote files. |
||
| 685 | */ |
||
| 686 | public static function buildPathFromUrl(string $url): string |
||
| 687 | { |
||
| 688 | $host = parse_url($url, PHP_URL_HOST); |
||
| 689 | $path = parse_url($url, PHP_URL_PATH); |
||
| 690 | $query = parse_url($url, PHP_URL_QUERY); |
||
| 691 | $ext = pathinfo(parse_url($url, PHP_URL_PATH), \PATHINFO_EXTENSION); |
||
| 692 | |||
| 693 | // Google Fonts hack |
||
| 694 | if (Util\Str::endsWith($path, '/css') || Util\Str::endsWith($path, '/css2')) { |
||
| 695 | $ext = 'css'; |
||
| 696 | } |
||
| 697 | |||
| 698 | return Page::slugify(\sprintf('%s%s%s%s', $host, self::sanitize($path), $query ? "-$query" : '', $query && $ext ? ".$ext" : '')); |
||
| 699 | } |
||
| 700 | |||
| 701 | /** |
||
| 702 | * Replaces some characters by '_'. |
||
| 703 | */ |
||
| 704 | public static function sanitize(string $string): string |
||
| 705 | { |
||
| 706 | return str_replace(['<', '>', ':', '"', '\\', '|', '?', '*'], '_', $string); |
||
| 707 | } |
||
| 708 | |||
| 709 | /** |
||
| 710 | * Add hash to the file name. |
||
| 711 | */ |
||
| 712 | protected function doFingerprint(): self |
||
| 723 | } |
||
| 724 | |||
| 725 | /** |
||
| 726 | * Compiles a SCSS. |
||
| 727 | * |
||
| 728 | * @throws RuntimeException |
||
| 729 | */ |
||
| 730 | protected function doCompile(): self |
||
| 731 | { |
||
| 732 | // abort if not a SCSS file |
||
| 733 | if ($this->data['ext'] != 'scss') { |
||
| 734 | return $this; |
||
| 735 | } |
||
| 736 | $scssPhp = new Compiler(); |
||
| 737 | // import paths |
||
| 738 | $importDir = []; |
||
| 739 | $importDir[] = Util::joinPath($this->config->getStaticPath()); |
||
| 740 | $importDir[] = Util::joinPath($this->config->getAssetsPath()); |
||
| 741 | $scssDir = (array) $this->config->get('assets.compile.import'); |
||
| 742 | $themes = $this->config->getTheme() ?? []; |
||
| 743 | foreach ($scssDir as $dir) { |
||
| 744 | $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir); |
||
| 745 | $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir); |
||
| 746 | $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir); |
||
| 747 | foreach ($themes as $theme) { |
||
| 748 | $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir")); |
||
| 749 | $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir")); |
||
| 750 | } |
||
| 751 | } |
||
| 752 | $scssPhp->setQuietDeps(true); |
||
| 753 | $scssPhp->setImportPaths(array_unique($importDir)); |
||
| 754 | // adds source map |
||
| 755 | if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) { |
||
| 756 | $importDir = []; |
||
| 757 | $assetDir = (string) $this->config->get('assets.dir'); |
||
| 758 | $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR); |
||
| 759 | $fileRelPath = substr($this->data['file'], $assetDirPos + 8); |
||
| 760 | $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath); |
||
| 761 | $importDir[] = \dirname($filePath); |
||
| 762 | foreach ($scssDir as $dir) { |
||
| 763 | $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir); |
||
| 764 | } |
||
| 765 | $scssPhp->setImportPaths(array_unique($importDir)); |
||
| 766 | $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE); |
||
| 767 | $scssPhp->setSourceMapOptions([ |
||
| 768 | 'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()), |
||
| 769 | 'sourceRoot' => '/', |
||
| 770 | ]); |
||
| 771 | } |
||
| 772 | // defines output style |
||
| 773 | $outputStyles = ['expanded', 'compressed']; |
||
| 774 | $outputStyle = strtolower((string) $this->config->get('assets.compile.style')); |
||
| 775 | if (!\in_array($outputStyle, $outputStyles)) { |
||
| 776 | throw new ConfigException(\sprintf('"%s" value must be "%s".', 'assets.compile.style', implode('" or "', $outputStyles))); |
||
| 777 | } |
||
| 778 | $scssPhp->setOutputStyle($outputStyle == 'compressed' ? OutputStyle::COMPRESSED : OutputStyle::EXPANDED); |
||
| 779 | // set variables |
||
| 780 | $variables = $this->config->get('assets.compile.variables'); |
||
| 781 | if (!empty($variables)) { |
||
| 782 | $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables); |
||
| 783 | $scssPhp->replaceVariables($variables); |
||
| 784 | } |
||
| 785 | // debug |
||
| 786 | if ($this->builder->isDebug()) { |
||
| 787 | $scssPhp->setQuietDeps(false); |
||
| 788 | $this->builder->getLogger()->debug(\sprintf("SCSS compiler imported paths:\n%s", Util\Str::arrayToList(array_unique($importDir)))); |
||
| 789 | } |
||
| 790 | // update data |
||
| 791 | $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']); |
||
| 792 | $this->data['ext'] = 'css'; |
||
| 793 | $this->data['type'] = 'text'; |
||
| 794 | $this->data['subtype'] = 'text/css'; |
||
| 795 | $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss(); |
||
| 796 | $this->data['size'] = \strlen($this->data['content']); |
||
| 797 | |||
| 798 | $this->builder->getLogger()->debug(\sprintf('Asset compiled: "%s"', $this->data['path'])); |
||
| 799 | |||
| 800 | return $this; |
||
| 801 | } |
||
| 802 | |||
| 803 | /** |
||
| 804 | * Minifying a CSS or a JS + cache. |
||
| 805 | * |
||
| 806 | * @throws RuntimeException |
||
| 807 | */ |
||
| 808 | protected function doMinify(): self |
||
| 809 | { |
||
| 810 | // compile SCSS files |
||
| 811 | if ($this->data['ext'] == 'scss') { |
||
| 812 | $this->doCompile(); |
||
| 813 | } |
||
| 814 | // abort if already minified |
||
| 815 | if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') { |
||
| 816 | return $this; |
||
| 817 | } |
||
| 818 | // abord if not a CSS or JS file |
||
| 819 | if (!\in_array($this->data['ext'], ['css', 'js'])) { |
||
| 820 | return $this; |
||
| 821 | } |
||
| 822 | // in debug mode: disable minify to preserve inline source map |
||
| 823 | if ($this->builder->isDebug() && $this->config->isEnabled('assets.compile.sourcemap')) { |
||
| 824 | return $this; |
||
| 825 | } |
||
| 826 | switch ($this->data['ext']) { |
||
| 827 | case 'css': |
||
| 828 | $minifier = new Minify\CSS($this->data['content']); |
||
| 829 | break; |
||
| 830 | case 'js': |
||
| 831 | $minifier = new Minify\JS($this->data['content']); |
||
| 832 | break; |
||
| 833 | default: |
||
| 834 | throw new RuntimeException(\sprintf('Unable to minify "%s".', $this->data['path'])); |
||
| 835 | } |
||
| 836 | $this->data['content'] = $minifier->minify(); |
||
| 837 | $this->data['size'] = \strlen($this->data['content']); |
||
| 838 | |||
| 839 | $this->builder->getLogger()->debug(\sprintf('Asset minified: "%s"', $this->data['path'])); |
||
| 840 | |||
| 841 | return $this; |
||
| 842 | } |
||
| 843 | |||
| 844 | /** |
||
| 845 | * Returns local file path and updated path, or throw an exception. |
||
| 846 | * If $fallback path is set, it will be used if the remote file is not found. |
||
| 847 | * |
||
| 848 | * Try to locate the file in: |
||
| 849 | * (1. remote file) |
||
| 850 | * 1. assets |
||
| 851 | * 2. themes/<theme>/assets |
||
| 852 | * 3. static |
||
| 853 | * 4. themes/<theme>/static |
||
| 854 | * |
||
| 855 | * @throws RuntimeException |
||
| 856 | */ |
||
| 857 | private function locateFile(string $path, ?string $fallback = null, ?string $userAgent = null): array |
||
| 858 | { |
||
| 859 | // remote file |
||
| 860 | if (Util\File::isRemote($path)) { |
||
| 861 | try { |
||
| 862 | $url = $path; |
||
| 863 | $path = self::buildPathFromUrl($url); |
||
| 864 | $cache = new Cache($this->builder, 'assets/remote'); |
||
| 865 | if (!$cache->has($path)) { |
||
| 866 | $content = $this->getRemoteFileContent($url, $userAgent); |
||
| 867 | $cache->set($path, [ |
||
| 868 | 'content' => $content, |
||
| 869 | 'path' => $path, |
||
| 870 | ], $this->config->get('cache.assets.remote.ttl')); |
||
| 871 | } |
||
| 872 | return [ |
||
| 873 | 'file' => $cache->getContentFilePathname($path), |
||
| 874 | 'path' => $path, |
||
| 875 | ]; |
||
| 876 | } catch (RuntimeException $e) { |
||
| 877 | if (empty($fallback)) { |
||
| 878 | throw new RuntimeException($e->getMessage()); |
||
| 879 | } |
||
| 880 | $path = $fallback; |
||
| 881 | } |
||
| 882 | } |
||
| 883 | |||
| 884 | // checks in assets/ |
||
| 885 | $file = Util::joinFile($this->config->getAssetsPath(), $path); |
||
| 886 | if (Util\File::getFS()->exists($file)) { |
||
| 887 | return [ |
||
| 888 | 'file' => $file, |
||
| 889 | 'path' => $path, |
||
| 890 | ]; |
||
| 891 | } |
||
| 892 | |||
| 893 | // checks in each themes/<theme>/assets/ |
||
| 894 | foreach ($this->config->getTheme() ?? [] as $theme) { |
||
| 895 | $file = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path); |
||
| 896 | if (Util\File::getFS()->exists($file)) { |
||
| 897 | return [ |
||
| 898 | 'file' => $file, |
||
| 899 | 'path' => $path, |
||
| 900 | ]; |
||
| 901 | } |
||
| 902 | } |
||
| 903 | |||
| 904 | // checks in static/ |
||
| 905 | $file = Util::joinFile($this->config->getStaticPath(), $path); |
||
| 906 | if (Util\File::getFS()->exists($file)) { |
||
| 907 | return [ |
||
| 908 | 'file' => $file, |
||
| 909 | 'path' => $path, |
||
| 910 | ]; |
||
| 911 | } |
||
| 912 | |||
| 913 | // checks in each themes/<theme>/static/ |
||
| 914 | foreach ($this->config->getTheme() ?? [] as $theme) { |
||
| 915 | $file = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path); |
||
| 916 | if (Util\File::getFS()->exists($file)) { |
||
| 917 | return [ |
||
| 918 | 'file' => $file, |
||
| 919 | 'path' => $path, |
||
| 920 | ]; |
||
| 921 | } |
||
| 922 | } |
||
| 923 | |||
| 924 | throw new RuntimeException(\sprintf('Unable to locate file "%s".', $path)); |
||
| 925 | } |
||
| 926 | |||
| 927 | /** |
||
| 928 | * Try to get remote file content. |
||
| 929 | * Returns file content or throw an exception. |
||
| 930 | * |
||
| 931 | * @throws RuntimeException |
||
| 932 | */ |
||
| 933 | private function getRemoteFileContent(string $path, ?string $userAgent = null): string |
||
| 946 | } |
||
| 947 | |||
| 948 | /** |
||
| 949 | * Optimizing $filepath image. |
||
| 950 | * Returns the new file size. |
||
| 951 | */ |
||
| 952 | private function optimizeImage(string $filepath, string $path, int $quality): int |
||
| 953 | { |
||
| 954 | $message = \sprintf('Asset not optimized: "%s"', $path); |
||
| 955 | $sizeBefore = filesize($filepath); |
||
| 956 | Optimizer::create($quality)->optimize($filepath); |
||
| 957 | $sizeAfter = filesize($filepath); |
||
| 958 | if ($sizeAfter < $sizeBefore) { |
||
| 959 | $message = \sprintf('Asset optimized: "%s" (%s Ko -> %s Ko)', $path, ceil($sizeBefore / 1000), ceil($sizeAfter / 1000)); |
||
| 960 | } |
||
| 961 | $this->builder->getLogger()->debug($message); |
||
| 962 | |||
| 963 | return $sizeAfter; |
||
| 964 | } |
||
| 965 | |||
| 966 | /** |
||
| 967 | * Returns image size informations. |
||
| 968 | * |
||
| 969 | * @see https://www.php.net/manual/function.getimagesize.php |
||
| 970 | * |
||
| 971 | * @throws RuntimeException |
||
| 972 | */ |
||
| 973 | private function getImageSize(): array|false |
||
| 988 | } |
||
| 989 | |||
| 990 | /** |
||
| 991 | * Builds CDN image URL. |
||
| 992 | */ |
||
| 993 | private function buildImageCdnUrl(): string |
||
| 1011 | ); |
||
| 1012 | } |
||
| 1013 | |||
| 1014 | /** |
||
| 1015 | * Checks if the asset is not missing and is typed as an image. |
||
| 1016 | * |
||
| 1017 | * @throws RuntimeException |
||
| 1018 | */ |
||
| 1019 | private function checkImage(): void |
||
| 1020 | { |
||
| 1021 | if ($this->data['missing']) { |
||
| 1022 | throw new RuntimeException(\sprintf('Unable to resize "%s": file not found.', $this->data['path'])); |
||
| 1023 | } |
||
| 1024 | if ($this->data['type'] != 'image') { |
||
| 1025 | throw new RuntimeException(\sprintf('Unable to resize "%s": not an image.', $this->data['path'])); |
||
| 1026 | } |
||
| 1027 | } |
||
| 1028 | |||
| 1029 | /** |
||
| 1030 | * Remove redondant '/thumbnails/<width(xheight)>/' in the path. |
||
| 1031 | */ |
||
| 1032 | private function deduplicateThumbPath(string $path): string |
||
| 1042 | } |
||
| 1043 | } |
||
| 1044 |