/**
  * Resolves an URL from an asset.
  *
  * @param AssetInterface $asset the asset containing the URL
  * @param string         $url   url read in file
  *
  * @return string an URL, a filepath
  */
 public static function resolveUrl(AssetInterface $asset, $url)
 {
     // given URL is absolute URL
     if (false !== strpos($url, '://')) {
         return $url;
     }
     // source directory of the asset
     $root = dirname($asset->getSourceRoot() . '/' . $asset->getTargetPath());
     // path directory where asset is being copied
     $path = dirname($asset->getTargetPath());
     if ('.' === $path) {
         $image = $url;
     } else {
         $image = $path . '/' . $url;
     }
     if (null !== $root) {
         $image = $root . '/' . $url;
     }
     // cleanup local URLs
     if (false === strpos($image, '://')) {
         $image = self::removeQueryString($image);
         $image = self::removeAnchor($image);
         return self::resolveUps($image);
     }
     return $image;
 }
 protected function getAssetUrl(AssetInterface $asset, $options = array())
 {
     $package = isset($options['package']) ? $options['package'] : null;
     if (null === $this->packages) {
         return $this->assetsHelper->getUrl($asset->getTargetPath(), $package);
     }
     return $this->packages->getPackage($package)->getUrl($asset->getTargetPath());
 }
 private function compileAssetUrl(\Twig_Compiler $compiler, AssetInterface $asset)
 {
     $compiler->repr($asset->getTargetPath());
     if (file_exists(PUB_DIR . DS . $asset->getTargetPath())) {
         return;
     }
     $writer = new \Assetic\AssetWriter(PUB_DIR . DS);
     $writer->writeAsset($asset);
 }
Ejemplo n.º 4
0
 /**
  * {@inheritdoc}
  */
 public function filterDump(AssetInterface $asset)
 {
     $webDir = $this->webDir;
     $isController = 0 === strpos($asset->getTargetPath(), '_controller/');
     $target = PathUtils::normalizePath($this->webDir . '/' . str_replace('_controller/', '', $asset->getTargetPath()));
     $source = PathUtils::normalizePath($asset->getSourceRoot() . '/' . $asset->getSourcePath());
     $content = $this->filterReferences($asset->getContent(), function ($matches) use($isController, $source, $target, $webDir) {
         if (file_exists($webDir . '/' . $matches['url'])) {
             return str_replace($matches['url'], PathUtils::findShortestPath($target, $webDir . '/' . $matches['url'], $isController), $matches[0]);
         }
         return $matches[0];
     });
     $asset->setContent($content);
 }
Ejemplo n.º 5
0
 /**
  * @param AssetInterface $asset
  * @param AssetWriter $writer
  * @param array $cachePath
  * @param array $headers
  */
 public function __construct(AssetInterface $asset, AssetWriter $writer, $cachePath, array $headers = [])
 {
     $file = $asset->getTargetPath();
     $cachePath = $cachePath . '/' . $file;
     $cached = false;
     $cacheTime = time();
     if (is_file($cachePath)) {
         $mTime = $asset->getLastModified();
         $cacheTime = filemtime($cachePath);
         if ($mTime > $cacheTime) {
             @unlink($cachePath);
             $cacheTime = $mTime;
         } else {
             $cached = true;
         }
     }
     if (!$cached) {
         $writer->writeAsset($asset);
     }
     $stream = function () use($cachePath) {
         readfile($cachePath);
     };
     $headers['Content-Length'] = filesize($cachePath);
     if (preg_match('/.+\\.([a-zA-Z0-9]+)/', $file, $matches)) {
         $ext = $matches[1];
         if (isset($this->mimeTypes[$ext])) {
             $headers['Content-Type'] = $this->mimeTypes[$ext];
         }
     }
     parent::__construct($stream, 200, $headers);
     $date = new \DateTime();
     $date->setTimestamp($cacheTime);
     $this->setLastModified($date);
 }
Ejemplo n.º 6
0
 public function process(AssetInterface $asset)
 {
     $hash = hash_init('sha1');
     switch ($this->strategy) {
         case self::STRATEGY_MODIFICATION:
             hash_update($hash, $asset->getLastModified());
             break;
         case self::STRATEGY_CONTENT:
             hash_update($hash, $asset->dump());
             break;
     }
     foreach ($asset as $i => $leaf) {
         if ($sourcePath = $leaf->getSourcePath()) {
             hash_update($hash, $sourcePath);
         } else {
             hash_update($hash, $i);
         }
     }
     $hash = substr(hash_final($hash), 0, 7);
     $url = $asset->getTargetPath();
     $oldExt = pathinfo($url, PATHINFO_EXTENSION);
     $newExt = '-' . $hash . '.' . $oldExt;
     if (!$oldExt || 0 < preg_match('/' . preg_quote($newExt, '/') . '$/', $url)) {
         return;
     }
     $asset->setTargetPath(substr($url, 0, (strlen($oldExt) + 1) * -1) . $newExt);
 }
Ejemplo n.º 7
0
 /**
  * {@inheritdoc}
  */
 public function getTargetPath()
 {
     if ($this->innerAsset) {
         return $this->innerAsset->getTargetPath();
     }
     return $this->targetPath;
 }
Ejemplo n.º 8
0
 /**
  * Performs the asset dump.
  *
  * @param AssetInterface  $asset  An asset
  * @param OutputInterface $stdout The command output
  *
  * @throws RuntimeException If there is a problem writing the asset
  */
 private function doDump(AssetInterface $asset, OutputInterface $stdout)
 {
     $combinations = VarUtils::getCombinations($asset->getVars(), $this->getContainer()->getParameter('assetic.variables'));
     foreach ($combinations as $combination) {
         $asset->setValues($combination);
         // resolve the target path
         $target = rtrim($this->basePath, '/') . '/' . $asset->getTargetPath();
         $target = str_replace('_controller/', '', $target);
         $target = VarUtils::resolve($target, $asset->getVars(), $asset->getValues());
         if (!is_dir($dir = dirname($target))) {
             $stdout->writeln(sprintf('<comment>%s</comment> <info>[dir+]</info> %s', date('H:i:s'), $dir));
             if (false === @mkdir($dir, 0777, true)) {
                 throw new \RuntimeException('Unable to create directory ' . $dir);
             }
         }
         $stdout->writeln(sprintf('<comment>%s</comment> <info>[file+]</info> %s', date('H:i:s'), $target));
         if (OutputInterface::VERBOSITY_VERBOSE <= $stdout->getVerbosity()) {
             if ($asset instanceof AssetCollectionInterface) {
                 foreach ($asset as $leaf) {
                     $root = $leaf->getSourceRoot();
                     $path = $leaf->getSourcePath();
                     $stdout->writeln(sprintf('        <comment>%s/%s</comment>', $root ?: '[unknown root]', $path ?: '[unknown path]'));
                 }
             } else {
                 $root = $asset->getSourceRoot();
                 $path = $asset->getSourcePath();
                 $stdout->writeln(sprintf('        <comment>%s/%s</comment>', $root ?: '[unknown root]', $path ?: '[unknown path]'));
             }
         }
         if (false === @file_put_contents($target, $asset->dump())) {
             throw new \RuntimeException('Unable to write file ' . $target);
         }
     }
 }
Ejemplo n.º 9
0
 public function writeAsset(AssetInterface $asset)
 {
     foreach ($this->getCombinations($asset->getVars()) as $combination) {
         $asset->setValues($combination);
         static::write($this->dir . '/' . PathUtils::resolvePath($asset->getTargetPath(), $asset->getVars(), $asset->getValues()), $asset->dump());
     }
 }
 public function process(AssetInterface $asset, AssetFactory $factory)
 {
     $targetUrl = $asset->getTargetPath();
     if ($targetUrl && '/' != $targetUrl[0] && 0 !== strpos($targetUrl, '_controller/')) {
         $asset->setTargetPath('_controller/' . $targetUrl);
     }
     return $asset;
 }
 public function filterDump(AssetInterface $asset)
 {
     $sourceBase = $asset->getSourceRoot();
     $sourcePath = $asset->getSourcePath();
     $targetPath = $asset->getTargetPath();
     if (null === $sourcePath || null === $targetPath || $sourcePath == $targetPath) {
         return;
     }
     // learn how to get from the target back to the source
     if (false !== strpos($sourceBase, '://')) {
         list($scheme, $url) = explode('://', $sourceBase . '/' . $sourcePath, 2);
         list($host, $path) = explode('/', $url, 2);
         $host = $scheme . '://' . $host . '/';
         $path = false === strpos($path, '/') ? '' : dirname($path);
         $path .= '/';
     } else {
         // assume source and target are on the same host
         $host = '';
         // pop entries off the target until it fits in the source
         if ('.' == dirname($sourcePath)) {
             $path = str_repeat('../', substr_count($targetPath, '/'));
         } elseif ('.' == ($targetDir = dirname($targetPath))) {
             $path = dirname($sourcePath) . '/';
         } else {
             while (0 !== strpos($sourcePath, $targetDir)) {
                 if (false !== ($pos = strrpos($targetDir, '/'))) {
                     $targetDir = substr($targetDir, 0, $pos);
                 } else {
                     $targetDir = '';
                     break;
                 }
             }
             $path = '/';
             $path .= ltrim(substr(dirname($sourcePath) . '/', strlen($targetDir)), '/');
         }
     }
     $content = $this->filterReferences($asset->getContent(), function ($matches) use($host, $path) {
         if (false !== strpos($matches['url'], '://') || 0 === strpos($matches['url'], '//') || 0 === strpos($matches['url'], 'data:')) {
             // absolute or protocol-relative or data uri
             return $matches[0];
         }
         if ('/' == $matches['url'][0]) {
             // root relative
             return str_replace($matches['url'], $host . $matches['url'], $matches[0]);
         }
         // document relative
         $url = $matches['url'];
         $parts = array();
         foreach (explode('/', $host . $path . $url) as $part) {
             if ('..' === $part && count($parts) && '..' !== end($parts)) {
                 array_pop($parts);
             }
             $parts[] = $part;
         }
         return str_replace($matches['url'], implode('/', $parts), $matches[0]);
     });
     $asset->setContent($content);
 }
Ejemplo n.º 12
0
 protected function compileAssetUrl(\Twig_Compiler $compiler, AssetInterface $asset, $name)
 {
     $compiler
         ->raw('isset($context[\'assetic\'][\'use_controller\']) && $context[\'assetic\'][\'use_controller\'] ? ')
         ->subcompile($this->getPathFunction($name))
         ->raw(' : ')
         ->subcompile($this->getAssetFunction($asset->getTargetPath()))
     ;
 }
Ejemplo n.º 13
0
 /**
  * Processes an asset.
  *
  * @param AssetInterface $asset An asset
  *
  * @return AssetInterface|null May optionally return a replacement asset
  */
 public function process(AssetInterface $asset)
 {
     $path = $asset->getTargetPath();
     $ext = pathinfo($path, PATHINFO_EXTENSION);
     $revision = $this->getRevision();
     if (null !== $revision) {
         $path = substr_replace($path, "{$revision}.{$ext}", -1 * strlen($ext));
         $asset->setTargetPath($path);
     }
 }
 public function writeAsset(AssetInterface $asset)
 {
     foreach (VarUtils::getCombinations($asset->getVars(), $this->values) as $combination) {
         $asset->setValues($combination);
         $path = $this->dir . '/' . VarUtils::resolve($asset->getTargetPath(), $asset->getVars(), $asset->getValues());
         if (!is_dir($path) && (!file_exists($path) || filemtime($path) <= $asset->getLastModified())) {
             static::write($path, $asset->dump());
         }
     }
 }
 public function process(AssetInterface $asset, AssetFactory $factory)
 {
     $path = $asset->getTargetPath();
     $ext = pathinfo($path, PATHINFO_EXTENSION);
     $lastModified = $asset->getLastModified();
     if (null !== $lastModified) {
         $path = substr_replace($path, "{$lastModified}.{$ext}", -1 * strlen($ext));
         $asset->setTargetPath($path);
     }
 }
Ejemplo n.º 16
0
 /**
  * @param mixed[]        $reference
  * @param AssetInterface $asset
  *
  * @return string
  */
 public function rewrite(array $reference, AssetInterface $asset)
 {
     if (!$this->isRewritable($reference['url'], $asset->getSourcePath(), $asset->getTargetPath())) {
         return $reference[0];
     }
     $absoluteSourcePath = $this->getAssetPath(dirname($this->createAssetPath($asset->getSourceRoot(), $asset->getSourcePath())), parse_url($reference['url'])['path']);
     $webTargetPath = $this->createAssetPath($this->rewriteDirectory, $this->namer->name($absoluteSourcePath, $asset));
     $absoluteTargetPath = $this->webDirectory . $webTargetPath;
     $this->filesystem->{$this->strategy}($absoluteSourcePath, $absoluteTargetPath, true);
     return str_replace($reference['url'], $this->packages->getUrl($webTargetPath), $reference[0]);
 }
Ejemplo n.º 17
0
 public function filterDump(AssetInterface $asset)
 {
     $sourceBase = $asset->getSourceRoot();
     $sourcePath = $asset->getSourcePath();
     $targetPath = $asset->getTargetPath();
     if (null === $sourcePath || null === $targetPath || $sourcePath == $targetPath) {
         return;
     }
     $content = \Minify_CSS_UriRewriter::rewrite($asset->getContent(), $sourceBase);
     $asset->setContent($content);
 }
 public function setupAsset(AssetInterface $asset)
 {
     if ($this->isDebug() && !$this->isCombine() && $asset instanceof AssetCollection) {
         // Move assets as single instance not as a collection
         foreach ($asset as $value) {
             /** @var AssetCollection $value */
             $path = $this->getBaseUrl() . $this->getBasePath() . $value->getTargetPath();
             $this->helper($path);
         }
     } else {
         $path = $this->getBaseUrl() . $this->getBasePath() . $asset->getTargetPath();
         $this->helper($path);
     }
 }
Ejemplo n.º 19
0
 public function writeAsset(AssetInterface $asset)
 {
     foreach (VarUtils::getCombinations($asset->getVars(), $this->values) as $combination) {
         $asset->setValues($combination);
         $path = $this->dir . '/' . VarUtils::resolve($asset->getTargetPath(), $asset->getVars(), $asset->getValues());
         if ($this->force || !file_exists($path) || $this->factory->getLastModified($asset) > filemtime($path)) {
             $this->log('Writing: ' . $path);
             if (!$this->dryRun) {
                 static::write($path, $asset->combineThenDump());
             }
         } else {
             $this->log('Skipping: ' . $path);
         }
     }
 }
Ejemplo n.º 20
0
 /**
  * @param \Twig_Compiler $compiler
  * @param AssetInterface $asset
  * @param $name
  */
 protected function compileAsset(\Twig_Compiler $compiler, AssetInterface $asset, $name)
 {
     $compiler->write("// asset \"{$name}\"\n")->write('$context[')->repr($this->getAttribute('var_name'))->raw('] = ');
     if ($this->compressedAsset == $asset) {
         $this->compileCombineDebugAssetUrl($compiler, $asset->getTargetPath(), $name);
     } else {
         $inputs = $this->getAttribute('inputs');
         if (!in_array($asset->getSourcePath(), $inputs['uncompress'][0])) {
             $this->compileAssetUrl($compiler, $asset, $name);
         } else {
             $this->compileCombineDebugAssetUrl($compiler, $asset->getSourcePath(), $name);
         }
     }
     $compiler->raw(";\n")->subcompile($this->getNode('body'));
 }
Ejemplo n.º 21
0
 /**
  * @param AssetInterface $asset
  * @param array $options
  * @return string
  */
 protected function helper(AssetInterface $asset, array $options = array())
 {
     $path = $this->baseUrl . $this->basePath . $asset->getTargetPath();
     $extension = pathinfo($path, PATHINFO_EXTENSION);
     $extension = strtolower($extension);
     if (isset($options['addFileMTime']) && $options['addFileMTime']) {
         $path .= '?' . $asset->getLastModified();
     }
     switch ($extension) {
         case 'js':
             return $this->getScriptTag($path, $options);
         case 'css':
             return $this->getStylesheetTag($path, $options);
     }
     return '';
 }
Ejemplo n.º 22
0
 protected function compileAssetUrl(\Twig_Compiler $compiler, AssetInterface $asset, $name)
 {
     if (!($vars = $asset->getVars())) {
         $compiler->repr($asset->getTargetPath());
         return;
     }
     $compiler->raw("strtr(")->string($asset->getTargetPath())->raw(", array(");
     $first = true;
     foreach ($vars as $var) {
         if (!$first) {
             $compiler->raw(", ");
         }
         $first = false;
         $compiler->string("{" . $var . "}")->raw(" => \$context['assetic']['vars']['{$var}']");
     }
     $compiler->raw("))");
 }
Ejemplo n.º 23
0
 public function process(AssetInterface $asset, AssetFactory $factory)
 {
     if (!($path = $asset->getTargetPath())) {
         // no path to work with
         return;
     }
     if (!($search = pathinfo($path, PATHINFO_EXTENSION))) {
         // nothing to replace
         return;
     }
     $replace = $this->separator . $this->getHash($asset, $factory) . '.' . $search;
     if (preg_match('/' . preg_quote($replace, '/') . '$/', $path)) {
         // already replaced
         return;
     }
     $asset->setTargetPath(preg_replace('/\\.' . preg_quote($search, '/') . '$/', $replace, $path));
 }
Ejemplo n.º 24
0
 public function filterDump(AssetInterface $asset)
 {
     $originalTargetPath = $asset->getTargetPath();
     $targetPath = str_replace('_controller/', '', $originalTargetPath);
     $asset->setTargetPath($targetPath);
     try {
         parent::filterDump($asset);
     } catch (\Exception $e) {
         if ($targetPath === $asset->getTargetPath()) {
             $asset->setTargetPath($originalTargetPath);
         }
         throw $e;
     }
     if ($targetPath === $asset->getTargetPath()) {
         $asset->setTargetPath($originalTargetPath);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function filterDump(AssetInterface $asset)
 {
     $directory = $this->directory;
     if (null === $asset->getSourcePath() || null === $asset->getTargetPath()) {
         return;
     }
     $content = $this->filterUrls($asset->getContent(), function ($matches) use($asset, $directory) {
         $url = $matches['url'];
         if (false !== strpos($url, '://') || 0 === strpos($url, 'data:')) {
             return $matches[0];
         }
         $file = PathUtils::resolveUrl($asset, $url);
         $target = $directory->add($file);
         $path = PathUtils::resolveRelative($target, $asset->getTargetPath()) . basename($file);
         return str_replace($matches['url'], $path, $matches[0]);
     });
     $asset->setContent($content);
 }
 private function doDump(AssetInterface $asset, $documentRoot)
 {
     $writer = new AssetWriter(sys_get_temp_dir(), $this->container->getParameter('assetic.variables'));
     $ref = new \ReflectionMethod($writer, 'getCombinations');
     $ref->setAccessible(true);
     $combinations = $ref->invoke($writer, $asset->getVars());
     foreach ($combinations as $combination) {
         $asset->setValues($combination);
         $target = rtrim($documentRoot, '/') . '/' . str_replace('_controller/', '', PathUtils::resolvePath($asset->getTargetPath(), $asset->getVars(), $asset->getValues()));
         if (!is_dir($dir = dirname($target))) {
             if (false === @mkdir($dir, 0777, true)) {
                 throw new \RuntimeException('Unable to create directory ' . $dir);
             }
         }
         if (false === @file_put_contents($target, $asset->dump())) {
             throw new \RuntimeException('Unable to write file ' . $target);
         }
     }
 }
Ejemplo n.º 27
0
 private function dumpAsset(AssetInterface $asset)
 {
     // HTTP caching
     $mtime = gmdate('D, d M y H:i:s', $asset->getLastModified()) . 'GMT';
     if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && ($mtime = $_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
         header('HTTP/1.1 304 Not Modified');
         exit;
     }
     // set headers & dump asset
     $extension = pathinfo($asset->getTargetPath(), PATHINFO_EXTENSION);
     if (array_key_exists($extension, self::$extensionsToMimeTypes)) {
         $mimeType = self::$extensionsToMimeTypes[$extension];
         header("Content-Type: {$mimeType}");
         header("Last-Modified: {$mtime}");
         header('Cache-Control: public');
     }
     echo $asset->dump();
     exit;
 }
Ejemplo n.º 28
0
 public function filterDump(AssetInterface $asset)
 {
     $sourceBase = $asset->getSourceRoot();
     $sourcePath = $asset->getSourcePath();
     $targetPath = $asset->getTargetPath();
     if (null === $sourcePath || null === $targetPath || $sourcePath == $targetPath) {
         return;
     }
     $cogNamespace = $asset->cogNamespace;
     $content = $this->filterReferences($asset->getContent(), function ($matches) use($cogNamespace) {
         if (false !== strpos($matches['url'], '://') || 0 === strpos($matches['url'], '//') || 0 === strpos($matches['url'], 'data:') || isset($matches['url'][0]) && '/' == $matches['url'][0]) {
             // absolute or protocol-relative or data uri
             return $matches[0];
         }
         $url = $matches['url'];
         while (0 === strpos($url, '../')) {
             $url = substr($url, 3);
         }
         $url = '../../cogules/' . $cogNamespace . '/' . $url;
         return str_replace($matches['url'], $url, $matches[0]);
     });
     $asset->setContent($content);
 }
Ejemplo n.º 29
0
 protected function getAssetUrl(AssetInterface $asset, array $options = array())
 {
     return $asset->getTargetPath();
 }
 public function setupAsset(AssetInterface $asset)
 {
     $path = $this->getBaseUrl() . $asset->getTargetPath();
     return $this->helper($path, $asset->getLastModified());
 }