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);
         }
     }
 }
Esempio n. 2
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.");
 }
Esempio n. 3
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;
 }
Esempio n. 4
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);
 }
Esempio n. 5
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);
     }
 }
 /**
  * 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);
             }
         }
     }
 }
Esempio n. 8
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, '/');
 }
Esempio n. 9
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;
     }
 }
Esempio n. 10
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");
 }
Esempio n. 11
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"));
 }
Esempio n. 12
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) : '';
}
Esempio n. 13
0
 public function computeAsset($relative_path, $name = null)
 {
     $paths = is_array($relative_path) ? $relative_path : array($relative_path);
     if (count($paths) > 1 && null === $name) {
         throw new Exception('You have to define a name for asset collection');
     }
     $am = new LazyAssetManager(new AssetFactory(''));
     $assets = array();
     $asset_collection = new AssetCollection();
     if ($this->settings['modes'] & Modes::CONCAT) {
         $assets[] = $asset_collection;
     }
     foreach ($paths as $p) {
         $file = $this->loader->fromAppPath($p);
         $asset = $file->asset(['compass' => $this->settings['modes'] & Modes::COMPASS]);
         $ext = str_replace(array('sass', 'scss'), 'css', File::getExt($p));
         $filename = substr($p, 0, strrpos($p, '.'));
         if ($this->settings['modes'] & Modes::CONCAT) {
             $asset_collection->add($asset);
             if (null === $name) {
                 $name = $filename . $ext;
             }
             $asset_collection->setTargetPath($name);
         } else {
             $asset->setTargetPath($filename . $ext);
             $assets[] = $asset;
         }
     }
     foreach ($assets as $asset) {
         // add the timestamp
         $target_path = explode('/', $asset->getTargetPath());
         $file_name = array_pop($target_path);
         $target_path[] = $am->getLastModified($asset) . '-' . $file_name;
         $web_path = implode('/', $target_path);
         $asset->setTargetPath($web_path);
         if (!file_exists($this->settings['public_path'] . '/' . $this->settings['compiled_dir'] . '/' . $asset->getTargetPath())) {
             if ($this->settings['modes'] & Modes::MINIFY) {
                 switch ($ext) {
                     case '.css':
                         $asset->ensureFilter(new \Assetic\Filter\CssMinFilter());
                         break;
                     case '.js':
                         $asset->ensureFilter(new \Assetic\Filter\JSMinFilter());
                         break;
                 }
             }
             $writer = new AssetWriter($this->settings['public_path'] . '/' . $this->settings['compiled_dir']);
             $writer->writeAsset($asset);
         }
     }
     return $assets[0];
 }
Esempio n. 14
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();
 }
Esempio n. 15
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;
        }
    }
}
 /**
  * Write collection in web folder
  *
  * @param Assetic\Factory\AssetFactory $assetFactory
  * @param string $file
  */
 protected function writeAssets($assetFactory, $file, $web, $tragetFile)
 {
     if (true === $this->lastModifedHandler($assetFactory->getLastModified(), $file, $web . $tragetFile)) {
         $writer = new AssetWriter($web);
         $writer->writeAsset($assetFactory);
     }
 }
Esempio n. 17
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;
 }
 /**
  * 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;
         }
     }
 }
Esempio n. 19
0
use Assetic\Factory\Worker\CacheBustingWorker;
use Assetic\Asset\AssetCollection;
use Assetic\Asset\AssetReference;
use Assetic\Asset\FileAsset;
use Assetic\Asset\GlobAsset;
use Assetic\Asset\HttpAsset;
use Assetic\AssetWriter;
$am = new AssetManager();
$am->set('base_scripts', new GlobAsset('assets/js/*'));
$am->set('base_styles', new GlobAsset('assets/css/*'));
$factory = new AssetFactory('/assets/cache/');
$factory->setAssetManager($am);
$factory->setDebug(true);
$factory->addWorker(new CacheBustingWorker());
$js = $factory->createAsset(['https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js', 'https://controls.office.com/appChrome/1.0/Office.Controls.AppChrome.js', 'https://controls.office.com/people/1.0/Office.Controls.People.js', 'https://raw.githubusercontent.com/OfficeDev/Office-UI-Fabric/release/1.1.0/dist/js/jquery.fabric.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js', '@base_scripts'], [], ["output" => "app.js"]);
$css = $factory->createAsset(['https://controls.office.com/appChrome/1.0/Office.Controls.AppChrome.min.css', 'https://controls.office.com/people/1.0/Office.Controls.People.min.css', 'https://raw.githubusercontent.com/OfficeDev/Office-UI-Fabric/release/1.1.0/dist/css/fabric.min.css', 'https://raw.githubusercontent.com/OfficeDev/Office-UI-Fabric/release/1.1.0/dist/css/fabric.components.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css', '@base_styles'], [], ["output" => "app.css"]);
$writer = new AssetWriter('assets/cache/');
$writer->writeAsset($js);
echo "Generated " . $js->getTargetPath() . PHP_EOL;
$writer->writeAsset($css);
echo "Generated " . $css->getTargetPath() . PHP_EOL;
$cache = [];
$cache["js"] = $js->getTargetPath();
$cache["css"] = $css->getTargetPath();
file_put_contents("assets/cache/cache.json", json_encode($cache));
foreach (glob("assets/cache/*") as $file) {
    if (!in_array(basename($file), [$cache["js"], $cache["css"], "cache.json"])) {
        unlink($file);
    }
}
echo "Done" . PHP_EOL;
Esempio n. 20
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"));
 }
Esempio n. 21
0
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();
    //$restaurantProcessor->generateList();