You are here

protected function AssetOptimizer::scanFile in Advanced CSS/JS Aggregation 8.4

Same name and namespace in other branches
  1. 8.3 src/Asset/AssetOptimizer.php \Drupal\advagg\Asset\AssetOptimizer::scanFile()

Given a filename calculate various hashes, gather meta data then optimize.

If any file optimizations are applied, updates the asset array. Also if enabled preemptively creates compressed versions.

Parameters

array $asset: A core asset array.

1 call to AssetOptimizer::scanFile()
AssetOptimizer::processAssetArray in src/Asset/AssetOptimizer.php
Process a core asset array.

File

src/Asset/AssetOptimizer.php, line 202

Class

AssetOptimizer
Defines the base AdvAgg optimizer.

Namespace

Drupal\advagg\Asset

Code

protected function scanFile(array &$asset) {

  // Clear PHP's internal file status cache.
  clearstatcache(TRUE, $asset['data']);
  $cid = Crypt::hashBase64($asset['data'] . $this->config
    ->get('global_counter'));
  $cached = $this->cache
    ->get($cid);
  if ($cached && file_exists($cached->data['file'])) {
    if ($this->config
      ->get('css.combine_media') && isset($asset['media']) && $asset['media'] !== 'all') {
      $asset['media'] = 'all';
    }
    $asset['size'] = $cached->data['filesize'];
    if ($this->cacheLevel === 3) {
      $asset['data'] = $cached->data['file'];
      $this->dnsPrefetch += $cached->data['prefetch'];
      return;
    }
    $data = [
      'filesize' => (int) @filesize($asset['data']),
      'mtime' => @filemtime($asset['data']),
    ];
    if ($this->cacheLevel === 2) {
      if ($cached->data['mtime'] === $data['mtime']) {
        $asset['data'] = $cached->data['file'];
        $this->dnsPrefetch += $cached->data['prefetch'];
        return;
      }
    }
    $data['contents'] = @file_get_contents($asset['data']);
    $data['hash'] = Crypt::hashBase64($data['contents']);
    if ($this->cacheLevel === 1) {
      if ($cached->data['hash'] === $data['hash']) {
        $asset['data'] = $cached->data['file'];
        $this->dnsPrefetch += $cached->data['prefetch'];
        return;
      }
    }
  }
  if (empty($data)) {
    $data = [
      'filesize' => (int) @filesize($asset['data']),
      'mtime' => @filemtime($asset['data']),
      'contents' => @file_get_contents($asset['data']),
    ];
    $data['hash'] = Crypt::hashBase64($data['contents']);
  }
  $data['cid'] = $cid;
  $asset['size'] = $data['filesize'];
  if ($data['file'] = $this
    ->optimizeFile($asset, $data)) {
    $asset['contents'] = $data['contents'];
    $data['prefetch'] = $this
      ->addDnsPrefetch($asset);
    $this->dnsPrefetch += $data['prefetch'];
    $data['original'] = $asset['data'];
    unset($data['contents']);
    unset($data['cid']);
    $this->cache
      ->set($cid, $data, $this
      ->getCacheTime(), [
      'advagg',
    ]);
    $asset['data'] = $data['file'];
  }
}