/** * Generates the cache for the given files. * * @access protected * @param string $type * @param string $fileName * @return false|string */ protected function buildFileCache($type, $fileName) { if (!file_exists($fileName)) { return false; } // Load the content $content = $this->fileBackend->loadFromFile($fileName); // Optimze the content $content = $this->optimizeContent($type, $fileName, $content); // Minify the content, if possible and activated if (($type === AssetManager::CSS || $type === AssetManager::JS) && $this->minifyAssets) { $content = $this->minifyContent($type, $content); } // Generate the new file name $fileInfo = pathinfo($fileName); $hash = $this->getHash($fileName); $version = $fileInfo['filename'] . '-' . uniqid() . '.' . $fileInfo['extension']; $targetFile = $this->buildFilePath($type, $hash, $version); // Save the cached file $this->removeOldCacheFile($fileName); $this->fileBackend->saveToFile($content, $targetFile); // Save the cached files in the data array $this->cachedFiles[$hash] = array('file' => $targetFile, 'checksum' => md5_file($fileName), 'timestamp' => time()); $this->saveAssetsCache(); return $targetFile; }
/** * Optimizes the urls in the css content. * * @access protected * @param string $content * @param string $file * @return string */ protected function optimizeUrls($content, $file) { preg_match_all('/url\\((.[^\\)]*)\\)/is', $content, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $uri = $match[1]; // Remove the apostrophs if (strpos($uri, '\'') === 0 || strpos($uri, '"') === 0) { $uri = substr($uri, 1, -1); } // If the uri is an absolute url we do not change anything if (strpos($uri, 'http') === 0) { continue; } $additionalData = $this->getAdditionalUriData($uri); $uri = $this->removeAdditionalUriData($uri); $path = dirname($file); $fullFilePath = realpath($path . '/' . $uri); $fileInformation = pathinfo($fullFilePath); $imageExtensions = array('png', 'jpg', 'jpeg', 'gif'); if (in_array($fileInformation['extension'], $imageExtensions)) { // Load the file content $fileContent = $this->fileBackend->loadFromFile($fullFilePath); // Encode the file content $encodedContent = base64_encode($fileContent); $urlData = 'data:image/gif;base64,' . $encodedContent; // Replace the reference in the css content $content = str_replace($match[1], '\'' . $urlData . '\'', $content); } else { $type = AssetManager::BINARY; // Cache the file $cachedFile = $this->assetCacheManager->generateCachedFile($type, $fullFilePath); $url = $this->assetCacheManager->getUrlToTheAssetLoader($cachedFile['file']); // Add the additional data if ($additionalData !== '') { $url .= $additionalData; } // Replace the reference in the css content $content = str_replace($match[1], '\'' . $url . '\'', $content); } } return $content; }