You are here

class CssOptimizer in Advanced CSS/JS Aggregation 8.3

Same name and namespace in other branches
  1. 8.4 src/Asset/CssOptimizer.php \Drupal\advagg\Asset\CssOptimizer

The CSS Optimizer.

Hierarchy

Expanded class hierarchy of CssOptimizer

1 string reference to 'CssOptimizer'
advagg.services.yml in ./advagg.services.yml
advagg.services.yml
1 service uses CssOptimizer
advagg.optimizer.css in ./advagg.services.yml
Drupal\advagg\Asset\CssOptimizer

File

src/Asset/CssOptimizer.php, line 12

Namespace

Drupal\advagg\Asset
View source
class CssOptimizer extends AssetOptimizer {

  /**
   * {@inheritdoc}
   */
  public function __construct(ConfigFactoryInterface $config_factory, ContainerAwareEventDispatcher $event_dispatcher, CacheBackendInterface $cache) {
    $this->extension = 'css';
    parent::__construct($config_factory, $event_dispatcher, $cache);
  }

  /**
   * {@inheritdoc}
   */
  protected function addDnsPrefetch(array $asset) {
    $prefetch = [];
    if (!isset($asset['contents'])) {
      return $prefetch;
    }
    $matches = [];
    $pattern = '%url\\(\\s*+[\'"]?+(http:\\/\\/|https:\\/\\/|\\/\\/)([^\'"()\\s]++)[\'"]?+\\s*+\\)%i';
    preg_match_all($pattern, $asset['contents'], $matches);
    if (!empty($matches[1])) {
      foreach ($matches[1] as $key => $match) {
        $parse = @parse_url($match . $matches[2][$key]);
        if (!empty($parse['host'])) {
          $prefetch[] = $parse['host'];
        }
      }
    }
    return $prefetch;
  }

  /**
   * {@inheritdoc}
   */
  protected function fixType(array &$asset) {

    // Default asset type to file if not set/invalid.
    if (!in_array($asset['type'], [
      'file',
      'external',
      'settings',
    ])) {
      $asset['type'] = 'file';
    }
    $path = $asset['data'];
    if ($asset['type'] === 'external') {

      // If type is external but path doesn't start with http, https, or //
      // change it to file.
      if (stripos($path, 'http') !== 0 && stripos($path, '//') !== 0) {
        $asset['type'] = 'file';
      }
      elseif (stripos($path, $this->basePath) !== FALSE && !$this->config
        ->get('css.preserve_external')) {
        $asset['type'] = 'file';
        $asset['group'] = CSS_BASE;
        $asset['every_page'] = TRUE;
        $asset['weight'] = -40000;
        $asset['data'] = substr($asset['data'], stripos($asset['data'], $this->basePath) + $this->basePathLen);
      }
    }
    elseif ($asset['type'] === 'file' && (stripos($path, 'http') === 0 || stripos($path, '//') === 0)) {
      $asset['type'] = 'external';
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function optimizeFile(array &$asset, array $data) {
    $contents = $this
      ->updateUrls($data['contents'], $asset['data']);
    if ($this->config
      ->get('css.combine_media') && $asset['media'] !== 'all') {
      $contents = "@media {$asset['media']}{{$contents}}";
      $asset['media'] = 'all';
    }
    $asset_event = new AssetOptimizationEvent($contents, $asset, $data);
    $this->eventDispatcher
      ->dispatch(AssetOptimizationEvent::CSS, $asset_event);
    $contents = $asset_event
      ->getContent();
    $asset = $asset_event
      ->getAsset();

    // If file contents are unaltered return FALSE.
    if ($contents === $data['contents'] && !$this->gZip) {
      return FALSE;
    }
    return $this
      ->writeFile($contents, $data['cid']);
  }

  /**
   * Update any internal urls.
   *
   * @param string $contents
   *   The file contents.
   * @param string $path
   *   The file path.
   *
   * @return string
   *   The updated contents.
   */
  public function updateUrls($contents, $path) {

    // Determine the file's directory including the Drupal base path.
    $directory = base_path() . dirname($path) . '/';

    // Alter all internal url() paths. Leave external paths alone. We don't need
    // to normalize absolute paths here because that will be done later. Also
    // ignore SVG paths (# or %23). Expected form: url("/images/file.jpg") which
    // gets converted to url("${directory}/images/file.jpg").
    return preg_replace('/url\\(\\s*([\'"]?)(?![a-z]+:|\\/+|\\#|\\%23+)([^\'")]+)([\'"]?)\\s*\\)/i', 'url(\\1' . $directory . '\\2\\3)', $contents);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AssetOptimizer::$brotli protected property Whether or not to brotli compress assets.
AssetOptimizer::$cache protected property The AdvAgg cache.
AssetOptimizer::$cacheLevel protected property Config level of caching of assets.
AssetOptimizer::$cacheTime protected property The cache time.
AssetOptimizer::$config protected property A config object for the advagg configuration.
AssetOptimizer::$dnsPrefetch protected property Array of domains to prefetch. Copied to $GLOBALS for later use.
AssetOptimizer::$eventDispatcher protected property Event Dispatcher service.
AssetOptimizer::$extension protected property Asset type (css or js).
AssetOptimizer::$fixType protected property Config to control fixing the asset type (file, external). 2
AssetOptimizer::$gZip protected property Whether or not to gzip assets.
AssetOptimizer::convertPathForceHttps protected function Convert http:// to https://.
AssetOptimizer::convertPathProtocolRelative protected function Converts absolute paths to be protocol relative paths.
AssetOptimizer::generateHtaccess public static function Generate an htaccess file in the optimized asset dirs to improve serving.
AssetOptimizer::getCacheTime protected function Get how long to cache an asset. Varies on cache level setting.
AssetOptimizer::processAssetArray public function Process a core asset array.
AssetOptimizer::scanFile protected function Given a filename calculate various hashes, gather meta data then optimize.
AssetOptimizer::shouldBrotli protected function Determine if settings and available PHP modules allow brotli-ing assets.
AssetOptimizer::shouldGZip protected function Determine if settings and available PHP modules allow GZipping assets.
AssetOptimizer::sortStable public static function Stable sort for CSS and JS items.
AssetOptimizer::writeFile protected function The filename for the CSS or JS optimized file is the cid.
CssOptimizer::addDnsPrefetch protected function Extract any domains to prefetch DNS. Overrides AssetOptimizer::addDnsPrefetch
CssOptimizer::fixType protected function Checks for and if found fixes incorrectly set asset types. Overrides AssetOptimizer::fixType
CssOptimizer::optimizeFile protected function Perform any in-place optimization & pass to event for further optimization. Overrides AssetOptimizer::optimizeFile
CssOptimizer::updateUrls public function Update any internal urls.
CssOptimizer::__construct public function Constructs the Optimizer object. Overrides AssetOptimizer::__construct