Same name and namespace in other branches
  1. 6.x includes/common.inc \drupal_build_css_cache()
  2. 7.x includes/common.inc \drupal_build_css_cache()

Aggregate and optimize CSS files, putting them in the files directory.

Parameters

$types: An array of types of CSS files (e.g., screen, print) to aggregate and compress into one file.

$filename: The name of the aggregate CSS file.

Return value

The name of the CSS file.

Related topics

1 call to drupal_build_css_cache()
drupal_get_css in includes/common.inc
Returns a themed representation of all stylesheets that should be attached to the page. It loads the CSS in order, with 'core' CSS first, then 'module' CSS, then 'theme' CSS files. This ensures proper cascading of styles…

File

includes/common.inc, line 1655
Common functions that many Drupal modules will need to reference.

Code

function drupal_build_css_cache($types, $filename) {
  $data = '';

  // Create the css/ within the files folder.
  $csspath = file_create_path('css');
  file_check_directory($csspath, FILE_CREATE_DIRECTORY);
  if (!file_exists($csspath . '/' . $filename)) {

    // Build aggregate CSS file.
    foreach ($types as $type) {
      foreach ($type as $file => $cache) {
        if ($cache) {
          $contents = file_get_contents($file);

          // Remove multiple charset declarations for standards compliance (and fixing Safari problems)
          $contents = preg_replace('/^@charset\\s+[\'"](\\S*)\\b[\'"];/i', '', $contents);

          // Return the path to where this CSS file originated from, stripping off the name of the file at the end of the path.
          $path = base_path() . substr($file, 0, strrpos($file, '/')) . '/';

          // Wraps all @import arguments in url().
          $contents = preg_replace('/@import\\s+(?!url)[\'"]?(\\S*)\\b[\'"]?/i', '@import url("\\1")', $contents);

          // Fix all paths within this CSS file, ignoring absolute paths.
          $data .= preg_replace('/url\\(([\'"]?)(?![a-z]+:)/i', 'url(\\1' . $path . '\\2', $contents);
        }
      }
    }

    // @import rules must proceed any other style, so we move those to the top.
    $regexp = '/@import[^;]+;/i';
    preg_match_all($regexp, $data, $matches);
    $data = preg_replace($regexp, '', $data);
    $data = implode('', $matches[0]) . $data;

    // Perform some safe CSS optimizations.
    $data = preg_replace('<
      \\s*([@{}:;,]|\\)\\s|\\s\\()\\s* |  # Remove whitespace around separators, but keep space around parentheses.
      /\\*([^*\\\\]|\\*(?!/))+\\*/ |   # Remove comments that are not CSS hacks.
      [\\n\\r]                        # Remove line breaks.
      >x', '\\1', $data);

    // Create the CSS file.
    file_save_data($data, $csspath . '/' . $filename, FILE_EXISTS_REPLACE);
  }
  return $csspath . '/' . $filename;
}