public function dump()
 {
     $finder = new Finder();
     $twigNamespaces = $this->loader->getNamespaces();
     foreach ($twigNamespaces as $ns) {
         if (count($this->loader->getPaths($ns)) > 0) {
             $iterator = $finder->files()->in($this->loader->getPaths($ns));
             foreach ($iterator as $file) {
                 /** @var SplFileInfo $file */
                 $resource = new TwigResource($this->loader, '@' . $ns . '/' . $file->getRelativePathname());
                 $this->lam->addResource($resource, 'twig');
             }
         }
     }
     foreach ($this->lam->getNames() as $name) {
         $asset = $this->lam->get($name);
         $formula = $this->lam->getFormula($name);
         $debug = isset($formula[2]['debug']) ? $formula[2]['debug'] : $this->lam->isDebug();
         $combine = isset($formula[2]['combine']) ? $formula[2]['combine'] : null;
         if (null !== $combine ? !$combine : $debug) {
             foreach ($asset as $leaf) {
                 $this->aw->writeAsset($leaf);
             }
         } else {
             $this->aw->writeAsset($asset);
         }
     }
 }
Example #2
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);
 }
Example #3
0
 public function writeAssets()
 {
     $storage = $this->app['config']->get('theme::config.storage_folder');
     $writer = new AssetWriter(app_path() . '/' . $storage);
     $writer->writeManagerAssets($this->am);
     return $this;
 }
Example #4
0
 /**
  * Create a new AssetCollection instance for the given group.
  *
  * @param  string                         $name
  * @param  bool                           $overwrite force writing
  * @return \Assetic\Asset\AssetCollection
  */
 public function createGroup($name, $overwrite = false)
 {
     if (isset($this->groups[$name])) {
         return $this->groups[$name];
     }
     $assets = $this->createAssetArray($name);
     $filters = $this->createFilterArray($name);
     $coll = new AssetCollection($assets, $filters);
     if ($output = $this->getConfig($name, 'output')) {
         $coll->setTargetPath($output);
     }
     // check output cache
     $write_output = true;
     if (!$overwrite) {
         if (file_exists($output = public_path($coll->getTargetPath()))) {
             $output_mtime = filemtime($output);
             $asset_mtime = $coll->getLastModified();
             if ($asset_mtime && $output_mtime >= $asset_mtime) {
                 $write_output = false;
             }
         }
     }
     // store assets
     if ($overwrite || $write_output) {
         $writer = new AssetWriter(public_path());
         $writer->writeAsset($coll);
     }
     return $this->groups[$name] = $coll;
 }
Example #5
0
 public function build($collection_name)
 {
     $build_path_setting = Config::get("assetie::build_path");
     $build_directory = public_path() . DIRECTORY_SEPARATOR . $build_path_setting;
     /**
      * the designated name of the build, i.e. base_123.js
      */
     $build_name = $collection_name . "." . $this->buildExtension;
     $build_file = $build_directory . DIRECTORY_SEPARATOR . $build_name;
     $buildExists = file_exists($build_file);
     $build_url = URL::asset($build_path_setting . DIRECTORY_SEPARATOR . $build_name);
     $debugMode = Config::get("app.debug");
     if (!$buildExists || $debugMode) {
         $files = \Collection::dump($collection_name)[$this->group];
         $collection_hash = sha1(serialize($files));
         $hash_in_cache = Cache::get("collection_" . $this->group . "_" . $collection_name);
         $collectionChanged = $collection_hash != $hash_in_cache;
         $src_dir = app_path() . DIRECTORY_SEPARATOR . Config::get("assetie::directories." . $this->group) . DIRECTORY_SEPARATOR;
         $forceRebuild = false;
         if ($collectionChanged) {
             $forceRebuild = true;
         } else {
             if ($buildExists) {
                 /**
                  * only recompile if no compiled build exists or when in debug mode and
                  * build's source files or collections.php has been changed
                  */
                 $forceRebuild = $this->checkModification($build_file, $files, $src_dir);
             }
         }
         if (!$buildExists || $forceRebuild) {
             $am = new AssetManager();
             $assets = [];
             foreach ($files as $file) {
                 $filters = $this->getFilters($file);
                 $assets[] = new FileAsset($src_dir . $file, $filters);
             }
             $collection = new AssetCollection($assets);
             // , $filters
             $collection->setTargetPath($build_name);
             $am->set('collection', $collection);
             $writer = new AssetWriter($build_directory);
             $writer->writeManagerAssets($am);
         }
         // Cache::forever("collection_" . $collection_name, $collection_hash);
         $cache_key = "collection_" . $this->group . "_" . $collection_name;
         if (Cache::has($cache_key) && $collectionChanged) {
             Cache::forget($cache_key);
         }
         if ($collectionChanged) {
             Cache::put($cache_key, $collection_hash, 60);
             // 1 hour
         }
     }
     return $build_url;
 }
Example #6
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('Dumping assets:');
     foreach ($this->assetManager->getNames() as $name) {
         $asset = $this->assetManager->get($name);
         $this->assetWriter->writeAsset($asset);
         $output->writeln("    <info>{$name}</info> -> <info>{$asset->getTargetPath()}</info>");
     }
     $count = count($this->assetManager->getNames());
     $output->writeln('');
     $output->writeln("Successfully dumped <info>{$count}</info> assets.");
 }
 public function dumpAction()
 {
     $appConfig = $this->locate('Configuration');
     $writer = new AssetWriter($appConfig['zf2_assetic']['assetDumpPath']);
     $writer->writeManagerAssets($this->assetManager);
     $httpRouter = $this->locate('httpRouter');
     $assetManifest = array('assets' => array());
     foreach ($this->assetManager->getNames() as $name) {
         $asset = $this->assetManager->get($name);
         $url = $httpRouter->assemble(array('resourcePath' => $asset->getTargetPath()), array('name' => $appConfig['zf2_assetic']['controllerRouteName']));
         $assetManifest['assets'][$name] = $url;
     }
     $manifestDir = dirname($appConfig['zf2_assetic']['assetManifestPath']);
     if (!is_dir($manifestDir)) {
         mkdir($manifestDir, 755, true);
     }
     if (false === file_put_contents($appConfig['zf2_assetic']['assetManifestPath'], json_encode($assetManifest))) {
         throw new \Exception('Unable to write asset manifest');
     }
 }
Example #8
0
 public function writeAsset(AssetInterface $asset, $combine = true)
 {
     if ($combine) {
         $assets = array($asset);
     } else {
         $assets = $asset;
         // manda o proprio collection, que já é um
     }
     foreach ($assets as $asset) {
         parent::writeAsset($asset);
     }
 }
Example #9
0
 /**
  * Dump all assets
  */
 public function all()
 {
     foreach ($this->getAssetsXMLFiles() as $path => $XMLFile) {
         $this->out('');
         $this->out(sprintf('<info>Start dumping "%s" assets:</info>', $path));
         $xml = new Xml();
         $domDocument = $xml->build($XMLFile, ['return' => 'domdocument']);
         $xpath = new DOMXPath($domDocument);
         $assetsNodeList = $xpath->query('/assetic/assets/asset');
         $assetManager = new AssetManager();
         /** @var $assetNode DOMElement */
         foreach ($assetsNodeList as $assetNode) {
             $source = strtr($assetNode->getElementsByTagName('source')->item(0)->nodeValue, $this->paths);
             $destination = strtr($assetNode->getElementsByTagName('destination')->item(0)->nodeValue, $this->paths);
             $assetManager->set($assetNode->getAttribute('name'), $fileAsset = new FileAsset($source));
             $fileAsset->setTargetPath($destination);
             $this->out($source . ' <info> >>> </info> ' . WWW_ROOT . $destination);
         }
         $assetWriter = new AssetWriter(WWW_ROOT);
         $assetWriter->writeManagerAssets($assetManager);
         $this->dumpStaticFiles($domDocument);
         $this->out('<info>End</info>');
     }
 }
 /**
  * Filter resource.
  *
  * Filter resource, applying filters and saving output into output location.
  *
  * @param ResourceInterface $resource Resource to filter.
  * @return ResourceInterface Resulting filtered resources.
  */
 private function filterResource(ResourceInterface $resource, array $filters)
 {
     if ($resource instanceof FileResource) {
         $asset = new FileAsset($resource->getSource(), $filters);
     } elseif ($resource instanceof HttpResource) {
         $asset = new HttpAsset($resource->getSource(), $filters);
     } elseif ($resource instanceof StringResource) {
         $asset = new StringAsset($resource->getSource(), $filters, $resource->getSourceRoot());
     } else {
         throw new InvalidArgumentException(sprintf('Instance of "%s" expected, "%s" given.', implode('", "', array('RunOpenCode\\AssetsInjection\\Resource\\FileResource', 'RunOpenCode\\AssetsInjection\\Resource\\HttpResource', 'RunOpenCode\\AssetsInjection\\Resource\\StringResource')), get_class($resource)));
     }
     $asset->setTargetPath($this->calculateTargetFilename($resource));
     $path = sprintf('%s%s%s', $this->options['output_dir'], DIRECTORY_SEPARATOR, $asset->getTargetPath());
     if (!file_exists($path) || filectime($path) !== $resource->getLastModified()) {
         $this->assetWriter->writeAsset($asset);
         touch($path, $resource->getLastModified() ? $resource->getLastModified() : time());
     }
     return new FileResource($path);
 }
 /**
  * Dumps the assets of given manager
  *
  * Doesn't use AssetWriter::writeManagerAssets since we also want to dump non-combined assets
  * (for example, when using twig extension in debug mode).
  *
  * @param AssetManager $am
  * @param AssetWriter  $writer
  */
 protected function dumpManagerAssets(AssetManager $am)
 {
     foreach ($am->getNames() as $name) {
         $asset = $am->get($name);
         if ($am instanceof LazyAssetManager) {
             $formula = $am->getFormula($name);
         }
         $this->writer->writeAsset($asset);
         if (!isset($formula[2])) {
             continue;
         }
         $debug = isset($formula[2]['debug']) ? $formula[2]['debug'] : $am->isDebug();
         $combine = isset($formula[2]['combine']) ? $formula[2]['combine'] : null;
         if (null !== $combine ? !$combine : $debug) {
             foreach ($asset as $leaf) {
                 $this->writer->writeAsset($leaf);
             }
         }
     }
 }
Example #12
0
 /**
  * Set Writer for css
  *
  * @author Kondratenko Alexander (Xander)
  */
 public function writeStaticCssLinks()
 {
     $writer = new AssetWriter(assets_server_path('static'));
     $writer->writeManagerAssets($this->am_css);
 }
Example #13
0
 /**
  * Build the site
  */
 public function build()
 {
     $that = $this;
     $this->root = realpath($this->root);
     // First, clean up non-existent files
     if (file_exists($this->outputDir)) {
         $deleteFinder = new Finder();
         $deleteFinder->in($this->outputDir)->filter(function (SplFileInfo $dstFile) {
             // Filter out entries where the source does not exist, or is not the same type
             $srcFile = new SplFileInfo("{$this->root}/{$dstFile->getRelativePathname()}", $dstFile->getRelativePath(), $dstFile->getRelativePathname());
             $old = $dstFile->isDir() && !$srcFile->isDir() || $dstFile->isFile() && !$srcFile->isFile();
             $event = new OldFileEvent($this, $srcFile, $dstFile, $old);
             $this->dispatcher->dispatch(BrancherEvents::OLDFILE, $event);
             return $event->isOld();
         });
         $this->filesystem->remove($deleteFinder);
     }
     // Find all files in root directory
     $renderFinder = new Finder();
     $renderFinder->files()->in(realpath($this->root))->ignoreDotFiles(false);
     array_map([$renderFinder, 'notPath'], array_filter(array_map(function ($exclude) use($that) {
         return $this->filesystem->makePathRelative(realpath($exclude), $that->root);
     }, array_merge($this->excludes, [$this->outputDir]))));
     $this->dispatcher->dispatch(BrancherEvents::SETUP, new SetupEvent($this, $renderFinder));
     // Render every file and dump to output
     $directoryVisited = [];
     /** @var \Symfony\Component\Finder\SplFileInfo $fileInfo */
     foreach ($renderFinder as $fileInfo) {
         $path = $fileInfo->getRelativePath();
         if (!isset($directoryVisited[$path])) {
             $pathObj = new SplFileInfo($fileInfo->getPath(), basename($fileInfo->getRelativePath()), $fileInfo->getRelativePath());
             $event = new DirectoryEnterEvent($this, $pathObj, $this->getSpecialConfig($fileInfo->getPath()));
             $this->dispatcher->dispatch(BrancherEvents::DIRECTORY_ENTER, $event);
             $directoryVisited[$path] = !$event->isShouldSkip();
         }
         if ($directoryVisited[$fileInfo->getRelativePath()] === false) {
             continue;
         }
         if ($fileInfo->getFilename() === $this->specialFile) {
             continue;
         }
         if (substr($this->finfo->file($fileInfo->getPathname()), 0, 4) === 'text') {
             $this->renderFile($fileInfo->getRelativePathname(), $fileInfo->getRelativePathname(), ['path' => $fileInfo->getRelativePathname()]);
         } else {
             // Dump binary files verbatim into output directory
             $this->filesystem->copy($fileInfo->getPathname(), "{$this->outputDir}/{$fileInfo->getRelativePathname()}");
         }
     }
     // Finally, we need to add all remaining templates as resources to Assetic
     // so it will dump the proper files
     /** @var \Twig_Loader_Filesystem $loader */
     $loader = $this->twig->getLoader();
     if ($loader instanceof \Twig_Loader_Filesystem) {
         $resourceFinder = new Finder();
         foreach ($loader->getNamespaces() as $ns) {
             $resourceFinder->in($loader->getPaths($ns));
         }
         /** @var \Symfony\Component\Finder\SplFileInfo $template */
         foreach ($resourceFinder as $template) {
             $this->manager->addResource(new TwigResource($loader, $template->getRelativePathname()), 'twig');
         }
     }
     $this->writer->writeManagerAssets($this->manager);
     $this->dispatcher->dispatch(BrancherEvents::TEARDOWN, new TeardownEvent($this));
 }
Example #14
0
function smarty_block_assetic($params, $content, $template, &$repeat)
{
    // In debug mode, we have to be able to loop a certain number of times, so we use a static counter
    static $count;
    static $assetsUrls;
    $realpath = realpath(__DIR__ . '/../../../' . $params['config_path']);
    $root = realpath($realpath . '/../') . '/';
    $base_path = null;
    $bundles = null;
    $dependencies = null;
    $themesService = \Zend_Registry::get('container')->getService('newscoop_newscoop.themes_service');
    $themePath = $themesService->getThemePath();
    $viewBildPath = '/themes/' . $themePath . $params['build_path'];
    $params['build_path'] = $root . $params['build_path'];
    // Set defaults
    if (!array_key_exists('debug', $params)) {
        $params['debug'] = false;
    }
    // Read config file
    if (isset($params['config_path'])) {
        $base_path = __DIR__ . '/../../../' . $params['config_path'];
    }
    $config = json_decode(file_get_contents($base_path . '/config.json'));
    // Opening tag (first call only)
    if ($repeat) {
        // Read bundles and dependencies config files
        if (file_exists($base_path . '/bundles.json')) {
            $bundles = json_decode(file_get_contents($base_path . '/bundles.json'));
        }
        if (file_exists($base_path . '/dependencies.json')) {
            $dependencies = json_decode(file_get_contents($base_path . '/dependencies.json'));
        }
        $am = new AssetManager();
        $fm = new FilterManager();
        if (property_exists($config, 'cssembed_path')) {
            $cssEmbedFilter = new Filter\CssEmbedFilter($config->cssembed_path, $config->java_path);
            $cssEmbedFilter->setRoot($root);
            $fm->set('cssembed', $cssEmbedFilter);
        }
        if (property_exists($config, 'yuicompressor_path') && property_exists($config, 'java_path')) {
            $fm->set('yui_js', new Filter\Yui\JsCompressorFilter($config->yuicompressor_path, $config->java_path));
            $fm->set('yui_css', new Filter\Yui\CssCompressorFilter($config->yuicompressor_path, $config->java_path));
        }
        $fm->set('less', new Filter\LessphpFilter());
        $fm->set('sass', new Filter\Sass\SassFilter());
        $fm->set('closure_api', new Filter\GoogleClosure\CompilerApiFilter());
        $fm->set('rewrite', new Filter\CssRewriteFilter());
        if (property_exists($config, 'closurejar_path') && property_exists($config, 'java_path')) {
            $fm->set('closure_jar', new Filter\GoogleClosure\CompilerJarFilter($config->closurejar_path, $config->java_path));
        }
        // Factory setup
        $factory = new AssetFactory($root);
        $factory->setAssetManager($am);
        $factory->setFilterManager($fm);
        $factory->setDefaultOutput('*.' . $params['output']);
        $factory->setDebug($params['debug']);
        if (isset($params['filters'])) {
            $filters = explode(',', $params['filters']);
        } else {
            $filters = array();
        }
        // Prepare the assets writer
        $writer = new AssetWriter($params['build_path']);
        // If a bundle name is provided
        if (isset($params['bundle'])) {
            $asset = $factory->createAsset($bundles->{$params}['output']->{$params}['bundle'], $filters);
            $cache = new AssetCache($asset, new FilesystemCache($params['build_path']));
            $writer->writeAsset($cache);
            // If individual assets are provided
        } elseif (isset($params['assets'])) {
            $assets = array();
            // Include only the references first
            foreach (explode(',', $params['assets']) as $a) {
                // If the asset is found in the dependencies file, let's create it
                // If it is not found in the assets but is needed by another asset and found in the references, don't worry, it will be automatically created
                if (isset($dependencies->{$params}['output']->assets->{$a})) {
                    // Create the reference assets if they don't exist
                    foreach ($dependencies->{$params}['output']->assets->{$a} as $ref) {
                        try {
                            $am->get($ref);
                        } catch (InvalidArgumentException $e) {
                            $path = $dependencies->{$params}['output']->references->{$ref};
                            $assetTmp = $factory->createAsset($path);
                            $am->set($ref, $assetTmp);
                            $assets[] = '@' . $ref;
                        }
                    }
                }
            }
            // Now, include assets
            foreach (explode(',', $params['assets']) as $a) {
                // Add the asset to the list if not already present, as a reference or as a simple asset
                $ref = null;
                if (isset($dependencies->{$params}['output'])) {
                    foreach ($dependencies->{$params}['output']->references as $name => $file) {
                        if ($file == $a) {
                            $ref = $name;
                            break;
                        }
                    }
                }
                if (array_search($a, $assets) === FALSE && ($ref === null || array_search('@' . $ref, $assets) === FALSE)) {
                    $assets[] = $a;
                }
            }
            // Create the asset
            $asset = $factory->createAsset($assets, $filters);
            $cache = new AssetCache($asset, new FilesystemCache($params['build_path']));
            $writer->writeAsset($cache);
        }
        // If debug mode is active, we want to include assets separately
        if ($params['debug']) {
            $assetsUrls = array();
            foreach ($asset as $a) {
                $cache = new AssetCache($a, new FilesystemCache($params['build_path']));
                $writer->writeAsset($cache);
                $assetsUrls[] = $a->getTargetPath();
            }
            // It's easier to fetch the array backwards, so we reverse it to insert assets in the right order
            $assetsUrls = array_reverse($assetsUrls);
            $count = count($assetsUrls);
            if (isset($config->site_url)) {
                $template->assign($params['asset_url'], $config->site_url . '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]);
            } else {
                $template->assign($params['asset_url'], $viewBildPath . '/' . $assetsUrls[$count - 1]);
            }
            // Production mode, include an all-in-one asset
        } else {
            if (isset($config->site_url)) {
                $template->assign($params['asset_url'], $config->site_url . '/' . $params['build_path'] . '/' . $asset->getTargetPath());
            } else {
                $template->assign($params['asset_url'], $viewBildPath . '/' . $asset->getTargetPath());
            }
        }
        // Closing tag
    } else {
        if (isset($content)) {
            // If debug mode is active, we want to include assets separately
            if ($params['debug']) {
                $count--;
                if ($count > 0) {
                    if (isset($config->site_url)) {
                        $template->assign($params['asset_url'], $config->site_url . '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]);
                    } else {
                        $template->assign($params['asset_url'], '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]);
                    }
                }
                $repeat = $count > 0;
            }
            return $content;
        }
    }
}
Example #15
0
 /**
  * Generates assets from $asset_path in $output_path, using $filters.
  *
  * @param        $assetSource
  * @param        $assetDirectoryBase
  * @param string $webAssetsDirectoryBase the full path to the asset file (or file collection, e.g. *.less)
  *
  * @param string $webAssetsTemplate the full disk path to the base assets output directory in the web space
  * @param        $webAssetsKey
  * @param string $outputUrl         the URL to the base assets output directory in the web space
  *
  * @param string $assetType the asset type: css, js, ... The generated files will have this extension. Pass an empty string to use the asset source extension.
  * @param array  $filters   a list of filters, as defined below (see switch($filter_name) ...)
  *
  * @param boolean $debug true / false
  *
  * @return string The URL to the generated asset file.
  */
 public function processAsset($assetSource, $assetDirectoryBase, $webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey, $outputUrl, $assetType, $filters, $debug)
 {
     Tlog::getInstance()->addDebug("Processing asset: assetSource={$assetSource}, assetDirectoryBase={$assetDirectoryBase}, webAssetsDirectoryBase={$webAssetsDirectoryBase}, webAssetsTemplate={$webAssetsTemplate}, webAssetsKey={$webAssetsKey}, outputUrl={$outputUrl}");
     $assetName = basename($assetSource);
     $inputDirectory = realpath(dirname($assetSource));
     $assetFileDirectoryInAssetDirectory = trim(str_replace(array($assetDirectoryBase, $assetName), '', $assetSource), DS);
     $am = new AssetManager();
     $fm = new FilterManager();
     // Get the filter list
     $filterList = $this->decodeAsseticFilters($fm, $filters);
     // Factory setup
     $factory = new AssetFactory($inputDirectory);
     $factory->setAssetManager($am);
     $factory->setFilterManager($fm);
     $factory->setDefaultOutput('*' . (!empty($assetType) ? '.' : '') . $assetType);
     $factory->setDebug($debug);
     $asset = $factory->createAsset($assetName, $filterList);
     $outputDirectory = $this->getDestinationDirectory($webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey);
     // Get the URL part from the relative path
     $outputRelativeWebPath = $webAssetsTemplate . DS . $webAssetsKey;
     $assetTargetFilename = $asset->getTargetPath();
     /*
      * This is the final name of the generated asset
      * We preserve file structure intending to keep - for example - relative css links working
      */
     $assetDestinationPath = $outputDirectory . DS . $assetFileDirectoryInAssetDirectory . DS . $assetTargetFilename;
     Tlog::getInstance()->addDebug("Asset destination full path: {$assetDestinationPath}");
     // We generate an asset only if it does not exists, or if the asset processing is forced in development mode
     if (!file_exists($assetDestinationPath) || $this->debugMode && ConfigQuery::read('process_assets', true)) {
         $writer = new AssetWriter($outputDirectory . DS . $assetFileDirectoryInAssetDirectory);
         Tlog::getInstance()->addDebug("Writing asset to {$outputDirectory}" . DS . "{$assetFileDirectoryInAssetDirectory}");
         $writer->writeAsset($asset);
     }
     // Normalize path to generate a valid URL
     if (DS != '/') {
         $outputRelativeWebPath = str_replace(DS, '/', $outputRelativeWebPath);
         $assetFileDirectoryInAssetDirectory = str_replace(DS, '/', $assetFileDirectoryInAssetDirectory);
         $assetTargetFilename = str_replace(DS, '/', $assetTargetFilename);
     }
     return rtrim($outputUrl, '/') . '/' . trim($outputRelativeWebPath, '/') . '/' . trim($assetFileDirectoryInAssetDirectory, '/') . '/' . ltrim($assetTargetFilename, '/');
 }
Example #16
0
 public function renderThemeAssets()
 {
     $conf = (array) $this->getThemeAssets();
     $factory = new Factory\AssetFactory($conf['root_path']);
     $factory->setAssetManager($this->getAssetManager());
     $factory->setFilterManager($this->getFilterManager());
     $factory->setDebug($this->configuration->isDebug());
     $mobileDetect = $this->serviceManager->get('dxMobileDetect');
     $isTablet = $mobileDetect->isTablet();
     $assetName = 'assets';
     $filterName = 'filters';
     $optionName = 'options';
     $outputName = 'output';
     if ($mobileDetect->isMobile()) {
         $assetName = $assetName . 'Mobile';
         $filterName = $filterName . 'Mobile';
         $optionName = $optionName . 'Mobile';
         $outputName = $outputName . 'Mobile';
     }
     if ($mobileDetect->isTablet()) {
         $assetName = $assetName . 'Tablet';
         $filterName = $filterName . 'Tablet';
         $optionName = $optionName . 'Tablet';
         $outputName = $outputName . 'Mobile';
     }
     $collections = (array) $conf['collections'];
     foreach ($collections as $name => $options) {
         $assets = isset($options[$assetName]) ? $options[$assetName] : isset($options['assets']) ? $options['assets'] : array();
         $filtersx = isset($options[$filterName]) ? $options[$filterName] : isset($options['filters']) ? $options['filters'] : array();
         $options = isset($options[$optionName]) ? $options[$optionName] : isset($options['options']) ? $options['options'] : array();
         $options['output'] = isset($options[$outputName]) ? $options[$outputName] : isset($options['output']) ? $options['output'] : $name;
         $filters = $this->initFilters($filtersx);
         /** @var $asset \Assetic\Asset\AssetCollection */
         $asset = $factory->createAsset($assets, $filters, $options);
         # allow to move all files 1:1 to new directory
         # its particulary usefull when this assets are images.
         if (isset($options['move_raw']) && $options['move_raw']) {
             foreach ($asset as $key => $value) {
                 $name = md5($value->getSourceRoot() . $value->getSourcePath());
                 $value->setTargetPath($value->getSourcePath());
                 $value = $this->cache($value);
                 $this->assetManager->set($name, $value);
             }
         } else {
             $asset = $this->cache($asset);
             $this->assetManager->set($name, $asset);
         }
     }
     $writer = new AssetWriter($this->configuration->getWebPath());
     $writer->writeManagerAssets($this->assetManager);
 }
Example #17
0
 /**
  * getUrlToAssets
  *
  * Create an asset file from a list of assets
  *
  * @param string       $type    type of asset, css or js
  * @param array        $assets  list of source files to process
  * @param string|array $filters either a comma separated list of known namsed filters
  *                              or an array of named filters and/or filter object
  * @param string       $target  target path, will default to assets directory
  *
  * @return string URL to asset file
  */
 public function getUrlToAssets($type, $assets, $filters = 'default', $target = null)
 {
     if (is_scalar($assets)) {
         $assets = array($assets);
         // just a single path name
     }
     if ($filters == 'default') {
         if (isset($this->default_filters[$type])) {
             $filters = $this->default_filters[$type];
         } else {
             $filters = '';
         }
     }
     if (!is_array($filters)) {
         if (empty($filters)) {
             $filters = array();
         } else {
             $filters = explode(',', str_replace(' ', '', $filters));
         }
     }
     if (isset($this->default_output[$type])) {
         $output = $this->default_output[$type];
     } else {
         $output = '';
     }
     $xoops = \Xoops::getInstance();
     if (isset($target)) {
         $target_path = $target;
     } else {
         $target_path = $xoops->path('assets');
     }
     try {
         $am = $this->assetManager;
         $fm = new FilterManager();
         foreach ($filters as $filter) {
             if (is_object($filter) && $filter instanceof $this->filterInterface) {
                 $filterArray[] = $filter;
             } else {
                 switch (ltrim($filter, '?')) {
                     case 'cssembed':
                         $fm->set('cssembed', new Filter\PhpCssEmbedFilter());
                         break;
                     case 'cssmin':
                         $fm->set('cssmin', new Filter\CssMinFilter());
                         break;
                     case 'cssimport':
                         $fm->set('cssimport', new Filter\CssImportFilter());
                         break;
                     case 'cssrewrite':
                         $fm->set('cssrewrite', new Filter\CssRewriteFilter());
                         break;
                     case 'lessphp':
                         $fm->set('lessphp', new Filter\LessphpFilter());
                         break;
                     case 'scssphp':
                         $fm->set('scssphp', new Filter\ScssphpFilter());
                         break;
                     case 'jsmin':
                         $fm->set('jsmin', new Filter\JSMinFilter());
                         break;
                     default:
                         throw new \Exception(sprintf('%s filter not implemented.', $filter));
                         break;
                 }
             }
         }
         // Factory setup
         $factory = new AssetFactory($target_path);
         $factory->setAssetManager($am);
         $factory->setFilterManager($fm);
         $factory->setDefaultOutput($output);
         $factory->setDebug($this->debug);
         $factory->addWorker(new CacheBustingWorker());
         // Prepare the assets writer
         $writer = new AssetWriter($target_path);
         // Translate asset paths, remove duplicates
         $translated_assets = array();
         foreach ($assets as $k => $v) {
             // translate path if not a reference or absolute path
             if (0 == preg_match("/^\\/|^\\\\|^[a-zA-Z]:|^@/", $v)) {
                 $v = $xoops->path($v);
             }
             if (!in_array($v, $translated_assets)) {
                 $translated_assets[] = $v;
             }
         }
         // Create the asset
         $asset = $factory->createAsset($translated_assets, $filters);
         $asset_path = $asset->getTargetPath();
         if (!is_readable($target_path . $asset_path)) {
             $xoops->events()->triggerEvent('debug.timer.start', array('writeAsset', $asset_path));
             $oldumask = umask(02);
             $writer->writeAsset($asset);
             umask($oldumask);
             $xoops->events()->triggerEvent('debug.timer.stop', 'writeAsset');
         }
         return $xoops->url('assets/' . $asset_path);
     } catch (\Exception $e) {
         $xoops->events()->triggerEvent('core.exception', $e);
         return null;
     }
 }
Example #18
0
 public function generateAssets()
 {
     $assetDir = \OC::$server->getConfig()->getSystemValue('assetdirectory', \OC::$SERVERROOT);
     $jsFiles = self::findJavascriptFiles(OC_Util::$scripts);
     $jsHash = self::hashFileNames($jsFiles);
     if (!file_exists("{$assetDir}/assets/{$jsHash}.js")) {
         $jsFiles = array_map(function ($item) {
             $root = $item[0];
             $file = $item[2];
             // no need to minifiy minified files
             if (substr($file, -strlen('.min.js')) === '.min.js') {
                 return new FileAsset($root . '/' . $file, array(new SeparatorFilter(';')), $root, $file);
             }
             return new FileAsset($root . '/' . $file, array(new JSMinFilter(), new SeparatorFilter(';')), $root, $file);
         }, $jsFiles);
         $jsCollection = new AssetCollection($jsFiles);
         $jsCollection->setTargetPath("assets/{$jsHash}.js");
         $writer = new AssetWriter($assetDir);
         $writer->writeAsset($jsCollection);
     }
     $cssFiles = self::findStylesheetFiles(OC_Util::$styles);
     $cssHash = self::hashFileNames($cssFiles);
     if (!file_exists("{$assetDir}/assets/{$cssHash}.css")) {
         $cssFiles = array_map(function ($item) {
             $root = $item[0];
             $file = $item[2];
             $assetPath = $root . '/' . $file;
             $sourceRoot = \OC::$SERVERROOT;
             $sourcePath = substr($assetPath, strlen(\OC::$SERVERROOT));
             return new FileAsset($assetPath, array(new CssRewriteFilter(), new CssMinFilter(), new CssImportFilter()), $sourceRoot, $sourcePath);
         }, $cssFiles);
         $cssCollection = new AssetCollection($cssFiles);
         $cssCollection->setTargetPath("assets/{$cssHash}.css");
         $writer = new AssetWriter($assetDir);
         $writer->writeAsset($cssCollection);
     }
     $this->append('jsfiles', OC_Helper::linkTo('assets', "{$jsHash}.js"));
     $this->append('cssfiles', OC_Helper::linkTo('assets', "{$cssHash}.css"));
 }
Example #19
0
 /**
  * Compile Less Themes that are defined in a twig file with lessphp filter
  *
  * @param mixed  $themes  An array of Theme entities or a string of the template with following syntax:
  *                        'ClarolineCoreBundle:less:bootstrap-default/theme.html.twig'
  * @param string $webPath
  *
  * @todo Find something better for web path
  */
 public function compileTheme($themes, $webPath = '.')
 {
     $assetManager = $this->container->get('assetic.asset_manager');
     $twigEnvironment = $this->container->get('twig');
     $twigLoader = $this->container->get('twig.loader');
     // enable loading assets from twig templates
     $assetManager->setLoader('twig', new TwigFormulaLoader($twigEnvironment));
     $lessGenerated = array();
     if (is_array($themes)) {
         foreach ($themes as $theme) {
             if ($theme->getPath() === 'less-generated') {
                 $lessGenerated[] = $theme->getName();
             } else {
                 $resource = new TwigResource($twigLoader, $theme->getPath());
                 $assetManager->addResource($resource, 'twig');
             }
         }
     } elseif (is_object($themes) and $themes->getPath() === 'less-generated') {
         $lessGenerated[] = $themes->getName();
     } else {
         $resource = new TwigResource($twigLoader, $themes);
         $assetManager->addResource($resource, 'twig');
     }
     $this->compileRaw($lessGenerated);
     $writer = new AssetWriter($webPath);
     $writer->writeManagerAssets($assetManager);
 }
 /**
  * Returns the public path of an asset
  *
  * @return string A public path
  */
 public function asseticBlock(array $params = array(), $content = null, $template, &$repeat)
 {
     // In debug mode, we have to be able to loop a certain number of times, so we use a static counter
     static $count;
     static $assetsUrls;
     // Read config file
     if (isset($params['config_path'])) {
         $base_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $params['config_path'];
     } else {
         // Find the config file in Symfony2 config dir
         $base_path = __DIR__ . '/../../../../app/config/smarty-assetic';
     }
     $config = json_decode(file_get_contents($base_path . '/config.json'));
     // Opening tag (first call only)
     if ($repeat) {
         // Read bundles and dependencies config files
         $bundles = json_decode(file_get_contents($base_path . '/bundles.json'));
         $dependencies = json_decode(file_get_contents($base_path . '/dependencies.json'));
         $am = new AssetManager();
         $fm = new FilterManager();
         $fm->set('yui_js', new Filter\Yui\JsCompressorFilter($config->yuicompressor_path, $config->java_path));
         $fm->set('yui_css', new Filter\Yui\CssCompressorFilter($config->yuicompressor_path, $config->java_path));
         $fm->set('less', new Filter\LessphpFilter());
         $fm->set('sass', new Filter\Sass\SassFilter());
         $fm->set('closure_api', new Filter\GoogleClosure\CompilerApiFilter());
         $fm->set('closure_jar', new Filter\GoogleClosure\CompilerJarFilter($config->closurejar_path, $config->java_path));
         // Factory setup
         $factory = new AssetFactory($_SERVER['DOCUMENT_ROOT']);
         $factory->setAssetManager($am);
         $factory->setFilterManager($fm);
         $factory->setDefaultOutput('assetic/*.' . $params['output']);
         if (isset($params['filter'])) {
             $filters = explode(',', $params['filter']);
         } else {
             $filters = array();
         }
         // Prepare the assets writer
         $writer = new AssetWriter($params['build_path']);
         // If a bundle name is provided
         if (isset($params['bundle'])) {
             $asset = $factory->createAsset($bundles->{$params}['output']->{$params}['bundle'], $filters, array($params['debug']));
             $cache = new AssetCache($asset, new FilesystemCache($params['build_path']));
             $writer->writeAsset($cache);
             // If individual assets are provided
         } elseif (isset($params['assets'])) {
             $assets = array();
             // Include only the references first
             foreach (explode(',', $params['assets']) as $a) {
                 // If the asset is found in the dependencies file, let's create it
                 // If it is not found in the assets but is needed by another asset and found in the references, don't worry, it will be automatically created
                 if (isset($dependencies->{$params}['output']->assets->{$a})) {
                     // Create the reference assets if they don't exist
                     foreach ($dependencies->{$params}['output']->assets->{$a} as $ref) {
                         try {
                             $am->get($ref);
                         } catch (InvalidArgumentException $e) {
                             $assetTmp = $factory->createAsset($dependencies->{$params}['output']->references->{$ref});
                             $am->set($ref, $assetTmp);
                             $assets[] = '@' . $ref;
                         }
                     }
                 }
             }
             // Now, include assets
             foreach (explode(',', $params['assets']) as $a) {
                 // Add the asset to the list if not already present, as a reference or as a simple asset
                 $ref = null;
                 if (isset($dependencies->{$params}['output'])) {
                     foreach ($dependencies->{$params}['output']->references as $name => $file) {
                         if ($file == $a) {
                             $ref = $name;
                             break;
                         }
                     }
                 }
                 if (array_search($a, $assets) === FALSE && ($ref === null || array_search('@' . $ref, $assets) === FALSE)) {
                     $assets[] = $a;
                 }
             }
             // Create the asset
             $asset = $factory->createAsset($assets, $filters, array($params['debug']));
             $cache = new AssetCache($asset, new FilesystemCache($params['build_path']));
             $writer->writeAsset($cache);
         }
         // If debug mode is active, we want to include assets separately
         if ($params['debug']) {
             $assetsUrls = array();
             foreach ($asset as $a) {
                 $cache = new AssetCache($a, new FilesystemCache($params['build_path']));
                 $writer->writeAsset($cache);
                 $assetsUrls[] = $a->getTargetPath();
             }
             // It's easier to fetch the array backwards, so we reverse it to insert assets in the right order
             $assetsUrls = array_reverse($assetsUrls);
             $count = count($assetsUrls);
             if (isset($config->site_url)) {
                 $template->assign($params['asset_url'], $config->site_url . '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]);
             } else {
                 $template->assign($params['asset_url'], '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]);
             }
             // Production mode, include an all-in-one asset
         } else {
             if (isset($config->site_url)) {
                 $template->assign($params['asset_url'], $config->site_url . '/' . $params['build_path'] . '/' . $asset->getTargetPath());
             } else {
                 $template->assign($params['asset_url'], '/' . $params['build_path'] . '/' . $asset->getTargetPath());
             }
         }
         // Closing tag
     } else {
         if (isset($content)) {
             // If debug mode is active, we want to include assets separately
             if ($params['debug']) {
                 $count--;
                 if ($count > 0) {
                     if (isset($config->site_url)) {
                         $template->assign($params['asset_url'], $config->site_url . '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]);
                     } else {
                         $template->assign($params['asset_url'], '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]);
                     }
                 }
                 $repeat = $count > 0;
             }
             return $content;
         }
     }
 }
 public function testFoor()
 {
     $am = $this->factoryAm();
     $writer = new AssetWriter(__DIR__ . "/../assets/build");
     $writer->writeManagerAssets($am);
 }
        if (APP_WEB_SITE_DIR) {
            $writer = new AssetWriter(APP_WEB_SITE_DIR . '/theme/default/img/');
            $writer->writeManagerAssets($am);
        }
        if (APP_WEB_SINGLE_SITE_DIR) {
            $writer = new AssetWriter(APP_WEB_SINGLE_SITE_DIR . '/theme/default/img/');
            $writer->writeManagerAssets($am);
        }
    }
    # Sysadmin
    if (APP_WEB_SYSADMIN_DIR || APP_WEB_SINGLE_SITE_DIR || APP_WEB_INDEX_DIR) {
        $am = new AssetManager();
        foreach ($imgFiles['sysadmin'] as $nameonly => $filename) {
            $fa = new FileAsset($filename, $imgFilters);
            $fa->setTargetPath($nameonly);
            $am->set(str_replace('.', '_', $nameonly), $fa);
        }
        if (APP_WEB_SYSADMIN_DIR) {
            $writer = new AssetWriter(APP_WEB_SYSADMIN_DIR . '/theme/default/imgsysadmin/');
            $writer->writeManagerAssets($am);
        }
        if (APP_WEB_SINGLE_SITE_DIR) {
            $writer = new AssetWriter(APP_WEB_SINGLE_SITE_DIR . '/theme/default/imgsysadmin/');
            $writer->writeManagerAssets($am);
        }
        if (APP_WEB_INDEX_DIR) {
            $writer = new AssetWriter(APP_WEB_INDEX_DIR . '/theme/default/imgsysadmin/');
            $writer->writeManagerAssets($am);
        }
    }
}
Example #23
0
/**
 * Include and manage Assets into templates.
 *
 * Supported styles:
 *  - CSS
 *  - LESS via /vendor/leafo/LessphpFilter
 *  - SCSS via /vendor/leafo/ScssphpFilter
 *
 * Supported scripts:
 *  - JavaScript
 *  - Coffee Script via Assetic\Filter\CoffeeScriptFilter
 *
 * @param array                    $options  Assets source options.
 * @param Smarty_Internal_Template $template Smarty Template object.
 *
 * @uses   Core\Config
 * @uses   Core\Utils
 * @see    Assetic
 *
 * @return string
 */
function smarty_function_assets(array $options, Smarty_Internal_Template $template)
{
    $result = array();
    if (isset($options['source'])) {
        $assetsPath = Core\Config()->paths('assets');
        $optimization_enabled = Core\Config()->ASSETS['optimize'];
        $combination_enabled = Core\Config()->ASSETS['combine'];
        $caching_enabled = Core\Config()->ASSETS['cache'];
        $dist_path = $assetsPath['distribution'];
        $source_path = $assetsPath['source'];
        $dist_url = Core\Config()->urls('assets');
        $media = isset($options['media']) ? $options['media'] : 'all';
        $rel = isset($options['rel']) ? $options['rel'] : 'stylesheet';
        $mimetype = isset($options['type']) ? $options['type'] : 'text/css';
        $assets = is_array($options['source']) ? $options['source'] : array($options['source']);
        $assets_id = md5(implode(Core\Utils::arrayFlatten($assets)));
        $assets_to_process = array();
        /* Format assets if needed */
        if (!Core\Utils::arrayIsAssoc($options['source'])) {
            $formatted_assets = array();
            foreach ($options['source'] as $file) {
                $file_extension = pathinfo($file, PATHINFO_EXTENSION);
                $formatted_assets[$file_extension][] = $file;
                $formatted_assets[$file_extension] = array_unique($formatted_assets[$file_extension]);
            }
            $assets = $formatted_assets;
        }
        if ($caching_enabled) {
            if ($combination_enabled) {
                if (array_intersect(array('css', 'less', 'scass'), array_keys($assets))) {
                    $cached_asset = 'css' . DIRECTORY_SEPARATOR . $assets_id . '.css';
                    if (file_exists($dist_path . $cached_asset)) {
                        $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset);
                        $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media);
                    } else {
                        $assets_to_process = $assets;
                    }
                } elseif (array_intersect(array('js'), array_keys($assets))) {
                    $cached_asset = 'js' . DIRECTORY_SEPARATOR . $assets_id . '.js';
                    if (file_exists($dist_path . $cached_asset)) {
                        $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset);
                        $result[] = sprintf('<script src="%s"></script>', $dist_url . $target);
                    } else {
                        $assets_to_process = $assets;
                    }
                }
            } else {
                foreach ($assets as $type => $files) {
                    switch ($type) {
                        case 'css':
                        case 'less':
                        case 'scass':
                            foreach ($files as $file) {
                                $filename = basename($file, '.css');
                                $filename = basename($filename, '.less');
                                $filename = basename($filename, '.scss');
                                $cached_asset = 'css' . DIRECTORY_SEPARATOR . $filename . '.css';
                                if (file_exists($dist_path . $cached_asset)) {
                                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset);
                                    $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media);
                                } else {
                                    $assets_to_process[$type][] = $file;
                                }
                            }
                            break;
                        case 'js':
                        case 'coffee':
                            foreach ($files as $file) {
                                $filename = basename($file, '.js');
                                $filename = basename($filename, '.coffee');
                                $cached_asset = 'js' . DIRECTORY_SEPARATOR . $filename . '.js';
                                if (file_exists($dist_path . $cached_asset)) {
                                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset);
                                    $result[] = sprintf('<script src="%s"></script>', $dist_url . $target);
                                } else {
                                    $assets_to_process[$type][] = $file;
                                }
                            }
                            break;
                    }
                }
            }
        }
        if (!$caching_enabled || $assets_to_process) {
            $assets = $assets_to_process ? $assets_to_process : $assets;
            $writer = new AssetWriter($dist_path);
            $styles = new AssetCollection(array(), $optimization_enabled ? array(new CssMinFilter()) : array());
            $scripts = new AssetCollection(array(), $optimization_enabled ? array(new JsMinFilter()) : array());
            foreach ($assets as $type => $files) {
                switch ($type) {
                    case 'js':
                        foreach ($files as $file) {
                            $scripts->add(new FileAsset($source_path . $file));
                        }
                        break;
                    case 'css':
                        foreach ($files as $file) {
                            $styles->add(new FileAsset($source_path . $file));
                        }
                        break;
                    case 'less':
                        foreach ($files as $file) {
                            $styles->add(new FileAsset($source_path . $file, array(new LessphpFilter())));
                        }
                        break;
                    case 'scss':
                        foreach ($files as $file) {
                            $styles->add(new FileAsset($source_path . $file, array(new ScssphpFilter())));
                        }
                        break;
                    case 'coffee':
                        foreach ($files as $file) {
                            $scripts->add(new FileAsset($source_path . $file), array(new CoffeeScriptFilter()));
                        }
                        break;
                }
            }
            if ($combination_enabled) {
                if ($styles->all()) {
                    $am = new AssetManager($dist_path);
                    $styles->setTargetPath('css' . DIRECTORY_SEPARATOR . $assets_id . '.css');
                    $am->set('styles', $styles);
                    $writer->writeManagerAssets($am);
                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $styles->getTargetPath());
                    $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media);
                }
                if ($scripts->all()) {
                    $am = new AssetManager($dist_path);
                    $scripts->setTargetPath('js' . DIRECTORY_SEPARATOR . $assets_id . '.js');
                    $am->set('scripts', $scripts);
                    $writer->writeManagerAssets($am);
                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $scripts->getTargetPath());
                    $result[] = sprintf('<script src="%s"></script>', $dist_url . $target);
                }
            } else {
                foreach ($styles->all() as $style) {
                    $filename = basename($style->getSourcePath(), '.css');
                    $filename = basename($filename, '.less');
                    $filename = basename($filename, '.scss');
                    $style->setTargetPath('css' . DIRECTORY_SEPARATOR . $filename . '.css');
                    $writer->writeAsset($style);
                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $style->getTargetPath());
                    $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media);
                }
                foreach ($scripts->all() as $script) {
                    $filename = basename($script->getSourcePath(), '.js');
                    $filename = basename($filename, '.coffee');
                    $script->setTargetPath('js' . DIRECTORY_SEPARATOR . $filename . '.js');
                    $writer->writeAsset($script);
                    $target = str_replace(DIRECTORY_SEPARATOR, '/', $script->getTargetPath());
                    $result[] = sprintf('<script src="%s"></script>', $dist_url . $target);
                }
            }
        }
    }
    return $result ? implode("\n\t", $result) : '';
}
Example #24
0
use Assetic\Asset\GlobAsset;
use Assetic\AssetManager;
use Assetic\Asset\AssetCache;
use Assetic\Cache\FilesystemCache;
use Shrubbery\QueryProcesor;
use Shrubbery\RestaurantProcessor;
use Shrubbery\Config;
$app = new Silex\Application();
$app['debug'] = true;
$app['asset_path'] = 'views';
//todo move this to a separate function
$bundles = array(new Symfony\Bundle\AsseticBundle\AsseticBundle());
$styles = new FileAsset('./vendor/twitter/bootstrap/dist/css/bootstrap.css');
$cache = new AssetCache($styles, new FilesystemCache('./views/cache'));
$cache->setTargetPath('bootstrap.css');
$writer = new AssetWriter('./views/assets');
$writer->writeAsset($cache);
//end todo
$getRestaurantList = new RestaurantProcessor();
$jsonObj = $getRestaurantList->readFromDatabase();
//Section for adding configuration
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../templates'));
$twig = $app['twig'];
$twig->addExtension(new \Entea\Twig\Extension\AssetExtension($app));
$app->get('/', function (Request $request) use($app) {
    $output = '';
    $finalList = '';
    $apiKey = '';
    $ini_Obj = parse_ini_file("data.ini", true);
    $apiKey = $ini_Obj["apiKey"];
    $restaurantProcessor = new RestaurantProcessor();
Example #25
0
 private function getMinifiedAsset()
 {
     if (!(new SplFileInfo($this->asset->getPath()))->isWritable()) {
         throw new Exception("path " . $this->asset->getPath() . " is not writable");
     }
     $factory = new AssetFactory($this->asset->getPath());
     $factory->addWorker(new CacheBustingWorker());
     $factory->setDefaultOutput('*');
     $fm = new FilterManager();
     $fm->set('min', $this->filter);
     $factory->setFilterManager($fm);
     $asset = $factory->createAsset(call_user_func(function ($files) {
         $r = [];
         foreach ($files as $file) {
             $r[] = $file['fs'];
         }
         return $r;
     }, $this->files), ['min'], ['name' => $this->asset->getBasename()]);
     // only write the asset file if it does not already exist..
     if (!file_exists($this->asset->getPath() . DIRECTORY_SEPARATOR . $asset->getTargetPath())) {
         $writer = new AssetWriter($this->asset->getPath());
         $writer->writeAsset($asset);
         // TODO: write some code to garbage collect files of a certain age?
         // possible alternative, modify CacheBustingWorker to have option
         // to append a timestamp instead of a hash
     }
     return $asset;
 }
Example #26
0
 public function initLoadedModules(array $loadedModules)
 {
     $moduleConfiguration = $this->configuration->getModules();
     foreach ($loadedModules as $moduleName => $module) {
         $moduleName = strtolower($moduleName);
         if (!isset($moduleConfiguration[$moduleName])) {
             continue;
         }
         $conf = (array) $moduleConfiguration[$moduleName];
         $factory = new Factory\AssetFactory($conf['root_path']);
         $factory->setAssetManager($this->getAssetManager());
         $factory->setFilterManager($this->getFilterManager());
         $factory->setDebug($this->configuration->isDebug());
         $collections = (array) $conf['collections'];
         foreach ($collections as $name => $options) {
             $assets = isset($options['assets']) ? $options['assets'] : array();
             $filters = isset($options['filters']) ? $options['filters'] : array();
             $options = isset($options['options']) ? $options['options'] : array();
             $options['output'] = isset($options['output']) ? $options['output'] : $name;
             $filters = $this->initFilters($filters);
             /** @var $asset \Assetic\Asset\AssetCollection */
             $asset = $factory->createAsset($assets, $filters, $options);
             # allow to move all files 1:1 to new directory
             # its particulary usefull when this assets are images.
             if (isset($options['move_raw']) && $options['move_raw']) {
                 foreach ($asset as $key => $value) {
                     $name = md5($value->getSourceRoot() . $value->getSourcePath());
                     $value->setTargetPath($value->getSourcePath());
                     $value = $this->cache($value);
                     $this->assetManager->set($name, $value);
                 }
             } else {
                 $asset = $this->cache($asset);
                 $this->assetManager->set($name, $asset);
             }
         }
         $writer = new AssetWriter($this->configuration->getWebPath());
         $writer->writeManagerAssets($this->assetManager);
     }
 }
Example #27
0
 public function compress()
 {
     $am = new AssetManager();
     $am->set('jquery', new FileAsset($jsPath . '/jquery/jquery.js'));
     $am->set('base_css', new GlobAsset($cssPath . '/bootstrap/bootstrap.css'));
     $am->set('jquery_anytime', new AssetCollection(array(new AssetReference($am, 'jquery'), new FileAsset($jsPath . '/jquery/jquery.anytime.js'))));
     $fm = new FilterManager();
     $fm->set('yui_js', new Yui\JsCompressorFilter(__DIR__ . '/yuicompressor.jar', 'C:\\Program Files\\Java\\jdk1.7.0_09\\bin\\java.exe'));
     $factory = new AssetFactory(__DIR__);
     $factory->setAssetManager($am);
     $factory->setFilterManager($fm);
     $factory->setDebug(true);
     $js = $factory->createAsset(array('@jquery_anytime'), array(), array('output' => 'all.js'));
     $writer = new AssetWriter(__DIR__);
     $writer->writeAsset($js);
     //$css->setTargetPath(ASSETS);
     //$js->dump();
 }
Example #28
0
 /**
  * generates a single css asset file from an array of css files if at least one of them has changed
  * otherwise it just returns the path to the old asset file
  * @param $files
  * @return string
  */
 private function generateCssAsset($files)
 {
     $assetDir = \OC::$server->getConfig()->getSystemValue('assetdirectory', \OC::$SERVERROOT);
     $hash = self::hashFileNames($files);
     if (!file_exists("{$assetDir}/assets/{$hash}.css")) {
         $files = array_map(function ($item) {
             $root = $item[0];
             $file = $item[2];
             $assetPath = $root . '/' . $file;
             $sourceRoot = \OC::$SERVERROOT;
             $sourcePath = substr($assetPath, strlen(\OC::$SERVERROOT));
             return new FileAsset($assetPath, array(new CssRewriteFilter(), new CssMinFilter(), new CssImportFilter()), $sourceRoot, $sourcePath);
         }, $files);
         $cssCollection = new AssetCollection($files);
         $cssCollection->setTargetPath("assets/{$hash}.css");
         $writer = new AssetWriter($assetDir);
         $writer->writeAsset($cssCollection);
     }
     return \OC::$server->getURLGenerator()->linkTo('assets', "{$hash}.css");
 }
Example #29
0
 public function generateAssets()
 {
     $jsFiles = self::findJavascriptFiles(OC_Util::$scripts);
     $jsHash = self::hashScriptNames($jsFiles);
     if (!file_exists("assets/{$jsHash}.js")) {
         $jsFiles = array_map(function ($item) {
             $root = $item[0];
             $file = $item[2];
             return new FileAsset($root . '/' . $file, array(), $root, $file);
         }, $jsFiles);
         $jsCollection = new AssetCollection($jsFiles);
         $jsCollection->setTargetPath("assets/{$jsHash}.js");
         $writer = new AssetWriter(\OC::$SERVERROOT);
         $writer->writeAsset($jsCollection);
     }
     $cssFiles = self::findStylesheetFiles(OC_Util::$styles);
     $cssHash = self::hashScriptNames($cssFiles);
     if (!file_exists("assets/{$cssHash}.css")) {
         $cssFiles = array_map(function ($item) {
             $root = $item[0];
             $file = $item[2];
             $assetPath = $root . '/' . $file;
             $sourceRoot = \OC::$SERVERROOT;
             $sourcePath = substr($assetPath, strlen(\OC::$SERVERROOT));
             return new FileAsset($assetPath, array(new CssRewriteFilter()), $sourceRoot, $sourcePath);
         }, $cssFiles);
         $cssCollection = new AssetCollection($cssFiles);
         $cssCollection->setTargetPath("assets/{$cssHash}.css");
         $writer = new AssetWriter(\OC::$SERVERROOT);
         $writer->writeAsset($cssCollection);
     }
     $this->append('jsfiles', OC_Helper::linkTo('assets', "{$jsHash}.js"));
     $this->append('cssfiles', OC_Helper::linkTo('assets', "{$cssHash}.css"));
 }
Example #30
0
use Assetic\AssetManager;
use Assetic\AssetWriter;
use Assetic\Extension\Twig\AsseticExtension;
use Assetic\Extension\Twig\TwigFormulaLoader;
use Assetic\Extension\Twig\TwigResource;
use Assetic\Factory\AssetFactory;
use Assetic\Factory\LazyAssetManager;
use Assetic\Filter\LessFilter;
use Assetic\FilterManager;
use Symfony\Component\Finder\Finder;
$loader = new Twig_Loader_Filesystem(VIEWS_PATH);
$options = ['cache' => DEBUG_APP ? false : 'cache'];
$twig = new Twig_Environment($loader, $options);
$assetManager = new AssetManager();
$filterManager = new FilterManager();
$filterManager->set('less', new LessFilter(NODE_PATH, [NODE_MODULE_PATH]));
$assetFactory = new AssetFactory('assets/');
$assetFactory->setDebug(false);
$assetFactory->setAssetManager($assetManager);
$assetFactory->setFilterManager($filterManager);
$twig->addExtension(new AsseticExtension($assetFactory));
$lazyAssetManager = new LazyAssetManager($assetFactory);
$lazyAssetManager->setLoader('twig', new TwigFormulaLoader($twig));
$finder = new Finder();
$finder->files()->in('assets')->exclude('css')->exclude('js')->exclude('images')->name("*.twig");
foreach ($finder as $template) {
    $resource = new TwigResource($loader, $template->getFileName());
    $lazyAssetManager->addResource($resource, 'twig');
}
$writer = new AssetWriter('.');
$writer->writeManagerAssets($lazyAssetManager);