/**
  * {@inheritDoc}
  */
 public function parse(\Twig_Token $token)
 {
     $inputs = $this->assets;
     $filters = [];
     $attributes = ['output' => $this->output, 'var_name' => 'asset_url', 'vars' => []];
     $stream = $this->parser->getStream();
     while (!$stream->test(\Twig_Token::BLOCK_END_TYPE)) {
         if ($stream->test(\Twig_Token::NAME_TYPE, 'filter')) {
             $filters = array_merge($filters, array_filter(array_map('trim', explode(',', $this->parseValue($stream, false)))));
         } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'output')) {
             $attributes['output'] = $this->parseValue($stream, false);
         } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'debug')) {
             $attributes['debug'] = $this->parseValue($stream);
         } elseif ($stream->test(\Twig_Token::NAME_TYPE, 'combine')) {
             $attributes['combine'] = $this->parseValue($stream);
         } else {
             $token = $stream->getCurrent();
             throw new \Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s"', \Twig_Token::typeToEnglish($token->getType(), $token->getLine()), $token->getValue()), $token->getLine());
         }
     }
     $stream->expect(\Twig_Token::BLOCK_END_TYPE);
     $body = $this->parser->subparse([$this, 'testEndTag'], true);
     $stream->expect(\Twig_Token::BLOCK_END_TYPE);
     $nameUnCompress = $this->factory->generateAssetName($inputs['compress'][0], $filters, $attributes);
     $nameCompress = substr(sha1(serialize($inputs['uncompress'][0]) . 'oro_assets'), 0, 7);
     return new OroAsseticNode(['compress' => $this->factory->createAsset($inputs['compress'][0], $filters, $attributes + ['name' => $nameCompress, 'debug' => false]), 'un_compress' => $this->factory->createAsset($inputs['uncompress'][0], [], $attributes + ['name' => $nameUnCompress, 'debug' => true])], ['un_compress' => $nameUnCompress, 'compress' => $nameCompress], $filters, $inputs, $body, $attributes, $token->getLine(), $this->getTag());
 }
Ejemplo n.º 2
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;
 }
Ejemplo n.º 3
0
    public function testNoFilterManager()
    {
        $this->setExpectedException('LogicException', 'There is no filter manager.');

        $factory = new AssetFactory('.');
        $factory->createAsset(array('foo'), array('foo'));
    }
Ejemplo n.º 4
0
 public function setAsset($asset)
 {
     $assets = $this->assetFactory->createAsset($asset)->all();
     $asset = $assets[0];
     $absolutePath = $asset->getSourceRoot() . DIRECTORY_SEPARATOR . $asset->getSourcePath();
     $pathInfo = pathinfo($absolutePath);
     list($width, $height, $imageType) = getimagesize($absolutePath);
     $this->absolutePath = $absolutePath;
     $this->width = $width;
     $this->height = $height;
     $this->imageType = $imageType;
     $this->ratio = $width / $height;
     $this->fileName = $pathInfo['filename'];
     $this->extension = $pathInfo['extension'];
     return $this;
 }
Ejemplo n.º 5
0
 /**
  * @param \Twig_NodeInterface $body
  * @param array $filters
  * @param array $attributes
  * @param int $lineno
  * @return AsseticNode
  */
 protected function createDebugAsseticNode(\Twig_NodeInterface $body, array $filters, array $attributes, $lineno)
 {
     $inputs = $this->assetsConfiguration->getCssFiles(true);
     $name = $this->assetFactory->generateAssetName($inputs, $filters, $attributes);
     $asset = $this->assetFactory->createAsset($inputs, $filters, $attributes + array('name' => $name));
     return new DebugAsseticNode($asset, $body, $inputs, $filters, $name, $attributes, $lineno, $this->getTag());
 }
Ejemplo n.º 6
0
 public function getChildren(AssetFactory $factory, $content, $loadPath = null)
 {
     $children = array();
     $includePaths = $this->includePaths;
     if (null !== $loadPath && !in_array($loadPath, $includePaths)) {
         array_unshift($includePaths, $loadPath);
     }
     if (empty($includePaths)) {
         return $children;
     }
     foreach (CssUtils::extractImports($content) as $reference) {
         if ('.css' === substr($reference, -4)) {
             continue;
         }
         // the reference may or may not have an extension or be a partial
         if (pathinfo($reference, PATHINFO_EXTENSION)) {
             $needles = array($reference, $this->partialize($reference));
         } else {
             $needles = array($reference . '.scss', $this->partialize($reference) . '.scss');
         }
         foreach ($includePaths as $includePath) {
             foreach ($needles as $needle) {
                 if (file_exists($file = $includePath . '/' . $needle)) {
                     $child = $factory->createAsset($file, array(), array('root' => $includePath));
                     $children[] = $child;
                     $child->load();
                     $children = array_merge($children, $this->getChildren($factory, $child->getContent(), $includePath));
                 }
             }
         }
     }
     return $children;
 }
Ejemplo n.º 7
0
 public function getChildren(AssetFactory $factory, $content, $loadPath = null)
 {
     $hash = md5($content);
     if ($this->cache->has($hash)) {
         return $factory->createAsset($this->cache->get($hash), array(), array('root' => $loadPath));
     } else {
         return parent::getChildren($factory, $content, $loadPath);
     }
 }
Ejemplo n.º 8
0
 /**
  * Builds assetic attributes from parameters extracted from template
  * source.
  *
  * @param string $blockName Smarty block name
  * @param array  $params    Block attributes
  *
  * @return An array with assetic attributes ready to append to $formulae.
  */
 protected function buildFormula($blockName, array $params = array())
 {
     // inject the block name into the $params array
     $params[AsseticExtension::OPTION_SMARTY_BLOCK_NAME] = $blockName;
     list($inputs, $filters, $options) = $this->extension->buildAttributes($params);
     $asset = $this->factory->createAsset($inputs, $filters, $options);
     $options['output'] = $asset->getTargetPath();
     unset($options[AsseticExtension::OPTION_SMARTY_BLOCK_NAME]);
     return array($options['name'] => array($inputs, $filters, $options));
 }
Ejemplo n.º 9
0
 /**
  * {@inheritDoc}
  */
 public function createAsset($inputs = array(), $filters = array(), array $options = array())
 {
     // Fixes problem with generated output
     if (!is_array($inputs)) {
         $inputs = array($inputs);
     }
     // set output the same as output if only one input
     if (count($inputs) === 1 && (!isset($options['output']) || $options['output'] === "*")) {
         $options['output'] = reset($inputs);
     }
     return parent::createAsset($inputs, $filters, $options);
 }
Ejemplo n.º 10
0
 /**
  * Add assets from array to this collection.
  *
  * @param array $assets
  * @throws Exceptions\UnexpectedValueException
  */
 public function addAssets(array $assets)
 {
     // \0 is hack. NULL do not work because is internally converted to "" and str_pos(..., "") throw error
     $sourceRoot = $this->getSourceRoot() !== NULL ? $this->getSourceRoot() : "";
     $assetFactory = new AssetFactory($sourceRoot);
     foreach ($assets as $asset) {
         if (is_string($asset)) {
             $this->add($assetFactory->createAsset($asset));
         } else {
             if ($asset instanceof AssetInterface) {
                 $this->add($asset);
             } else {
                 throw new UnexpectedValueException("Unexpected asset type. Expected string or AssetInterface. Given " . (is_object($asset) ? get_class($asset) : gettype($asset)));
             }
         }
     }
 }
Ejemplo n.º 11
0
 /**
  * Create the combined assets from a set of inputs and store the cog
  * namespace for later use.
  *
  * @param  array  $inputs
  * @param  array  $filters
  * @param  array  $options
  * @return \Assetic\Asset\AssetCollection
  */
 public function createAsset($inputs = array(), $filters = array(), array $options = array())
 {
     if (!is_array($inputs)) {
         $inputs = array($inputs);
     }
     $paths = $this->_getFullPaths($inputs);
     $namespaces = $this->_getNamespaces($inputs);
     $collection = parent::createAsset($paths, $filters, $options);
     // Store the cog namespace against each asset for use in the cogule filter
     foreach ($collection as $asset) {
         if (!isset($namespaces[$asset->getSourceRoot() . '/' . $asset->getSourcePath()])) {
             continue;
         }
         $asset->cogNamespace = $namespaces[$asset->getSourceRoot() . '/' . $asset->getSourcePath()];
     }
     return $collection;
 }
Ejemplo n.º 12
0
 public function getChildren(AssetFactory $factory, $content, $loadPath = null)
 {
     $loadPaths = $this->loadPaths;
     if ($loadPath) {
         array_unshift($loadPaths, $loadPath);
     }
     if (!$loadPaths) {
         return array();
     }
     $children = array();
     foreach (CssUtils::extractImports($content) as $reference) {
         if ('.css' === substr($reference, -4)) {
             // skip normal css imports
             // todo: skip imports with media queries
             continue;
         }
         // the reference may or may not have an extension or be a partial
         if (pathinfo($reference, PATHINFO_EXTENSION)) {
             $needles = array($reference, self::partialize($reference));
         } else {
             $needles = array($reference . '.scss', $reference . '.sass', self::partialize($reference) . '.scss', self::partialize($reference) . '.sass');
         }
         foreach ($loadPaths as $loadPath) {
             foreach ($needles as $needle) {
                 if (file_exists($file = $loadPath . '/' . $needle)) {
                     $coll = $factory->createAsset($file, array(), array('root' => $loadPath));
                     foreach ($coll as $leaf) {
                         /** @var $leaf AssetInterface */
                         $leaf->ensureFilter($this);
                         $children[] = $leaf;
                         goto next_reference;
                     }
                 }
             }
         }
         next_reference:
     }
     return $children;
 }
Ejemplo n.º 13
0
 /**
  * Creates a new asset.
  *
  * @param array|string $inputs  An array of input strings
  * @param array|string $filters An array of filter names
  * @param array        $options An array of options
  *
  * @return \Assetic\Asset\AssetCollection An asset collection
  */
 public function createAsset($inputs = array(), $filters = array(), array $options = array())
 {
     $am = $this->getAssetManager();
     if ($am instanceof LazyAssetManager) {
         if (isset($options['name'])) {
             $name = $options['name'];
         } else {
             $name = $options['name'] = $this->generateAssetName($inputs, $filters, $options);
         }
         $am->setFormula($name, [$inputs, $filters, $options]);
     }
     return parent::createAsset($inputs, $filters, $options);
 }
Ejemplo n.º 14
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;
     }
 }
Ejemplo n.º 15
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);
 }
Ejemplo n.º 16
0
 /**
  * Creates an asset for a list of inputs relative to the given Puli
  * directory.
  *
  * See {@link PuliAssetFactory} for a description of the resolution logic
  * of inputs to assets.
  *
  * @param string|null $currentDir The Puli directory of the currently loaded
  *                                Twig template. This is `null` if the
  *                                template was not loaded through Puli.
  * @param string[]    $inputs     An array of input strings.
  * @param string[]    $filters    An array of filter names.
  * @param array       $options    An array of options.
  *
  * @return AssetCollectionInterface The created asset.
  *
  * @see PuliAssetFactory
  */
 public function createAssetForCurrentDir($currentDir, array $inputs = array(), array $filters = array(), array $options = array())
 {
     if (isset($options['name'])) {
         // If the name is already set to a generated name, resolve that
         // name now
         if ($options['name'] instanceof LazyAssetName) {
             $options['name']->setCurrentDir($currentDir);
         }
     } else {
         // Always generate a name if none is set
         $options['name'] = $this->generateAssetNameForCurrentDir($currentDir, $inputs, $filters, $options);
     }
     // Remember the current directory for parseInput()
     $options['current_dir'] = $currentDir;
     return parent::createAsset($inputs, $filters, $options);
 }
Ejemplo n.º 17
0
use Assetic\Factory\AssetFactory;
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);
    }
}
Ejemplo n.º 18
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();
 }
 /**
  * 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;
         }
     }
 }
Ejemplo n.º 20
0
 public function getChildren(AssetFactory $factory, $content, $loadPath = null)
 {
     $sc = new Compiler();
     $sc->addImportPath($loadPath);
     foreach ($this->importPaths as $path) {
         $sc->addImportPath($path);
     }
     $children = array();
     foreach (CssUtils::extractImports($content) as $match) {
         $file = $sc->findImport($match);
         if ($file) {
             $children[] = $child = $factory->createAsset($file, array(), array('root' => $loadPath));
             $child->load();
             $children = array_merge($children, $this->getChildren($factory, $child->getContent(), $loadPath));
         }
     }
     return $children;
 }
Ejemplo n.º 21
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, '/');
 }
use Assetic\Cache\ApcCache;
use Assetic\Asset\AssetCache;
use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Assetic\Asset\GlobAsset;
use Assetic\AssetWriter;
use Assetic\Filter\Yui\CssCompressorFilter as YuiCompressorFilter;
use Assetic\Filter\GoogleClosure\CompilerJarFilter as GoogleClosureFilter;
$fm = new FilterManager();
$am = new AssetManager();
$factory = new AssetFactory(__DIR__ . '/', true);
$factory->setDefaultOutput('/');
$factory->setFilterManager($fm);
$factory->setAssetManager($am);
$yui_compressor = new YuiCompressorFilter(__DIR__ . '/utils/yuicompressor-2.4.8.jar');
$fm->set('yui_css', $yui_compressor);
$google_closure_compiler = new GoogleClosureFilter(__DIR__ . '/utils/google-closure-compiler.jar');
$google_closure_compiler->setLanguage($google_closure_compiler::LANGUAGE_ECMASCRIPT5);
$fm->set('google_js', $google_closure_compiler);
// The Asset Manager allows us to keep our assets organized.
$am->set('main_js', new AssetCollection(array(new FileAsset(__DIR__ . '/../assets/js/lib/angular.js'), new FileAsset(__DIR__ . '/../assets/js/lib/underscore.js'), new FileAsset(__DIR__ . '/../assets/js/lib/angular-route.js'), new FileAsset(__DIR__ . '/../assets/js/lib/angular-resource.js'), new FileAsset(__DIR__ . '/../assets/js/lib/heartcode-canvasloader.js'), new FileAsset(__DIR__ . '/../assets/js/app/myKraigsList.js'))));
$am->set('main_css', new AssetCollection(array(new FileAsset(__DIR__ . '/../assets/css/body.css'), new FileAsset(__DIR__ . '/../assets/css/angular-csp.css'))));
$write_cache = function ($asset) {
    $cache = new AssetCache($asset, new FilesystemCache(__DIR__ . '/../cache/assets/'));
    $writer = new AssetWriter(__DIR__ . '/compiled/');
    $writer->writeAsset($cache);
};
$js_asset = $factory->createAsset(array('@main_js'), array('google_js'), array('output' => '/js/application.js'));
$css_asset = $factory->createAsset(array('@main_css'), array('yui_css'), array('output' => '/css/application.css'));
$write_cache($js_asset);
$write_cache($css_asset);
Ejemplo n.º 23
0
 /**
  * @param array $options
  * @param string $name
  * @param Factory\AssetFactory $factory
  *
  * @return void
  */
 public function prepareCollection($options, $name, Factory\AssetFactory $factory)
 {
     $assets = isset($options['assets']) ? $options['assets'] : [];
     $filters = isset($options['filters']) ? $options['filters'] : [];
     $options = isset($options['options']) ? $options['options'] : [];
     $options['output'] = isset($options['output']) ? $options['output'] : $name;
     $moveRaw = isset($options['move_raw']) && $options['move_raw'];
     $targetPath = !empty($options['targetPath']) ? $options['targetPath'] : '';
     if (substr($targetPath, -1) != DIRECTORY_SEPARATOR) {
         $targetPath .= DIRECTORY_SEPARATOR;
     }
     $filters = $this->initFilters($filters);
     $asset = $factory->createAsset($assets, $filters, $options);
     // Allow to move all files 1:1 to new directory
     // its particularly useful when this assets are i.e. images.
     if ($moveRaw) {
         if (isset($options['disable_source_path'])) {
             $this->moveRaw($asset, $targetPath, $factory, $options['disable_source_path']);
         } else {
             $this->moveRaw($asset, $targetPath, $factory);
         }
     } else {
         $asset = $this->cacheAsset($asset);
         $this->assetManager->set($name, $asset);
         // Save asset on disk
         $this->writeAsset($asset, $factory);
     }
 }
Ejemplo n.º 24
0
 /**
  * Creates a new asset.
  *
  * Prefixing a filter name with a question mark will cause it to be
  * omitted when the factory is in debug mode.
  *
  * Available options:
  *
  *  * output: An output string
  *  * name:   An asset name for interpolation in output patterns
  *  * debug:  Forces debug mode on or off for this asset
  *  * root:   An array or string of more root directories
  *
  * @param array|string $inputs  An array of input strings
  * @param array|string $filters An array of filter names
  * @param array        $options An array of options
  *
  * @return AssetCollection An asset collection
  */
 public function createAsset($inputs = array(), $filters = array(), array $options = array())
 {
     return $this->assetFactory->createAsset($inputs, $filters, $options);
 }
Ejemplo n.º 25
0
 public function getChildren(AssetFactory $factory, $content, $loadPath = null)
 {
     $loadPaths = $this->loadPaths;
     if (null !== $loadPath) {
         $loadPaths[] = $loadPath;
     }
     if (empty($loadPaths)) {
         return array();
     }
     $children = array();
     foreach (LessUtils::extractImports($content) as $reference) {
         if ('.css' === substr($reference, -4)) {
             // skip normal css imports
             // todo: skip imports with media queries
             continue;
         }
         if ('.less' !== substr($reference, -5)) {
             $reference .= '.less';
         }
         foreach ($loadPaths as $loadPath) {
             if (file_exists($file = $loadPath . '/' . $reference)) {
                 $coll = $factory->createAsset($file, array(), array('root' => $loadPath));
                 foreach ($coll as $leaf) {
                     $leaf->ensureFilter($this);
                     $children[] = $leaf;
                     goto next_reference;
                 }
             }
         }
         next_reference:
     }
     return $children;
 }
Ejemplo n.º 26
0
 private function optimize($files, AssetFactory $assetFactory)
 {
     return $assetFactory->createAsset($files, '?yui_js')->dump();
 }
Ejemplo n.º 27
0
 /**
  * @param array $options
  * @param string $name
  * @param Factory\AssetFactory $factory
  * @return void
  */
 public function prepareCollection($options, $name, Factory\AssetFactory $factory)
 {
     $assets = isset($options['assets']) ? $options['assets'] : array();
     $filters = isset($options['filters']) ? $options['filters'] : $this->configuration->getDefault()['filters'];
     $options = isset($options['options']) ? $options['options'] : array();
     $options['output'] = isset($options['output']) ? $options['output'] : $name;
     $moveRaw = isset($options['move_raw']) && $options['move_raw'];
     $filters = $this->initFilters($filters);
     $asset = $factory->createAsset($assets, $filters, $options);
     // Allow to move all files 1:1 to new directory
     // its particularly useful when this assets are i.e. images.
     if ($moveRaw) {
         $this->moveRaw($asset);
     } else {
         $asset = $this->cacheAsset($asset);
         $this->assetManager->set($name, $asset);
     }
 }
Ejemplo n.º 28
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;
        }
    }
}
Ejemplo n.º 29
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);
     }
 }
Ejemplo n.º 30
0
 /**
  * Build styles collection add filter return link to web recource
  *
  * @param array $assets file collection
  * @param string $key collection name
  * @param string $path path to assets recources
  * @param string $web path to web resource
  */
 public function styleAssets($collection, $key, $path, $web)
 {
     if (true === $collection['debug']) {
         $this->debugWriteAssets(CON_ROOT_PATH, DOCUMENT_ROOT, $web, $collection);
         return true;
     }
     $am = $this->setAssetsCollection($collection['assets'], $key, $path);
     $this->fm = null;
     $factory = new AssetFactory(DOCUMENT_ROOT . $web, $collection['debug']);
     $factory->setAssetManager($am);
     $filters = array();
     if (false === $collection['debug']) {
         if (isset($collection['includes'])) {
             $this->includeResources($collection['includes']);
         }
         if (isset($collection['filters'])) {
             foreach ($collection['filters'] as $alias => $filter) {
                 $filters[] = '?' . $alias;
                 $this->getFm()->set($alias, new $filter());
             }
             $factory->setFilterManager($this->getFm());
             $factory->addWorker(new CacheBustingWorker());
         }
     }
     $css = $factory->createAsset(array('@' . $key), $filters);
     $css->setTargetPath($key . '.css');
     $this->writeAssets($css, self::ASSETS_LASTMODIFIED . $key, DOCUMENT_ROOT . $web, '/' . $key . '.css');
     $this->setStylesheets($this->linkStylesheet($web . '/' . $key . '.css', $collection['attr']));
     return true;
 }