AssetDumper.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace Drupal\Core\Asset;
  3. use Drupal\Component\Utility\Crypt;
  4. /**
  5. * Dumps a CSS or JavaScript asset.
  6. */
  7. class AssetDumper implements AssetDumperInterface {
  8. /**
  9. * {@inheritdoc}
  10. *
  11. * The file name for the CSS or JS cache file is generated from the hash of
  12. * the aggregated contents of the files in $data. This forces proxies and
  13. * browsers to download new CSS when the CSS changes.
  14. */
  15. public function dump($data, $file_extension) {
  16. // Prefix filename to prevent blocking by firewalls which reject files
  17. // starting with "ad*".
  18. $filename = $file_extension . '_' . Crypt::hashBase64($data) . '.' . $file_extension;
  19. // Create the css/ or js/ path within the files folder.
  20. $path = 'public://' . $file_extension;
  21. $uri = $path . '/' . $filename;
  22. // Create the CSS or JS file.
  23. file_prepare_directory($path, FILE_CREATE_DIRECTORY);
  24. if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
  25. return FALSE;
  26. }
  27. // If CSS/JS gzip compression is enabled and the zlib extension is available
  28. // then create a gzipped version of this file. This file is served
  29. // conditionally to browsers that accept gzip using .htaccess rules.
  30. // It's possible that the rewrite rules in .htaccess aren't working on this
  31. // server, but there's no harm (other than the time spent generating the
  32. // file) in generating the file anyway. Sites on servers where rewrite rules
  33. // aren't working can set css.gzip to FALSE in order to skip
  34. // generating a file that won't be used.
  35. if (extension_loaded('zlib') && \Drupal::config('system.performance')->get($file_extension . '.gzip')) {
  36. if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
  37. return FALSE;
  38. }
  39. }
  40. return $uri;
  41. }
  42. }