public function testProcess_withAssetCollection_shouldHash() { $collection = new AssetCollection(); $collection->add($this->getFileAsset('asset.txt')); $collection->add($this->getStringAsset('string', 'string.txt')); $collection->setTargetPath('collection.txt'); $this->getCacheBustingWorker()->process($collection, $this->getAssetFactory()); $this->assertSame('collection-ae851400.txt', $collection->getTargetPath()); }
/** * @return AssetCollectionInterface */ public function getAssets() { if ($this->dirty) { $this->assets = new AssetCollection([], [], TL_ROOT); ksort($this->sortedAssets); foreach ($this->sortedAssets as $assets) { foreach ($assets as $asset) { $this->assets->add($asset); } } $this->dirty = false; } return $this->assets; }
/** * {@inheritDoc} */ public function resolve($name) { if (!isset($this->collections[$name])) { return null; } if (!is_array($this->collections[$name])) { throw new \RuntimeException("Collection with name {$name} is not an array."); } $collection = new AssetCollection(); $mimeType = 'application/javascript'; $collection->setTargetPath($name); foreach ($this->collections[$name] as $asset) { if (!is_string($asset)) { throw new \RuntimeException('Asset should be of type string. got ' . gettype($asset)); } if (null === ($content = $this->riotTag->__invoke($asset))) { throw new \RuntimeException("Riot tag '{$asset}' could not be found."); } $res = new StringAsset($content); $res->mimetype = $mimeType; $asset .= ".js"; $this->getAssetFilterManager()->setFilters($asset, $res); $collection->add($res); } $collection->mimetype = $mimeType; return $collection; }
/** * Resolve to the plugins for this module (expand). * * @throws \SxBootstrap\Exception\RuntimeException * @return \Assetic\Asset\AssetCollection */ protected function resolvePlugins() { $config = $this->config; $pluginFiles = $this->getPluginNames($config->getMakeFile()); $includedPlugins = $config->getIncludedPlugins(); $excludedPlugins = $config->getExcludedPlugins(); if (!empty($excludedPlugins) && !empty($includedPlugins)) { throw new Exception\RuntimeException('You may not set both excluded and included plugins.'); } $pluginsAsset = new AssetCollection(); $mimeType = null; foreach ($pluginFiles as $plugin) { if (!empty($excludedPlugins) && in_array($plugin, $excludedPlugins)) { continue; } elseif (!empty($includedPlugins) && !in_array($plugin, $includedPlugins)) { continue; } $res = $this->getAggregateResolver()->resolve('js/bootstrap-' . $plugin . '.js'); if (null === $res) { throw new Exception\RuntimeException("Asset '{$plugin}' could not be found."); } if (!$res instanceof AssetInterface) { throw new Exception\RuntimeException("Asset '{$plugin}' does not implement Assetic\\Asset\\AssetInterface."); } if (null !== $mimeType && $res->mimetype !== $mimeType) { throw new Exception\RuntimeException(sprintf('Asset "%s" from collection "%s" doesn\'t have the expected mime-type "%s".', $plugin, $config->getPluginAlias(), $mimeType)); } $mimeType = $res->mimetype; $this->getAssetFilterManager()->setFilters($plugin, $res); $pluginsAsset->add($res); } $pluginsAsset->mimetype = $mimeType; return $pluginsAsset; }
/** * {@inheritdoc} */ public function process() { $filters = new FilterCollection(array(new CssRewriteFilter())); $assets = new AssetCollection(); $styles = $this->packageStyles($this->packages); foreach ($styles as $package => $packageStyles) { foreach ($packageStyles as $style => $paths) { foreach ($paths as $path) { // The full path to the CSS file. $assetPath = realpath($path); // The root of the CSS file. $sourceRoot = dirname($path); // The style path to the CSS file when external. $sourcePath = $package . '/' . $style; // Where the final CSS will be generated. $targetPath = $this->componentDir; // Build the asset and add it to the collection. $asset = new FileAsset($assetPath, $filters, $sourceRoot, $sourcePath); $asset->setTargetPath($targetPath); $assets->add($asset); } } } $css = $assets->dump(); if (file_put_contents($this->componentDir . '/require.css', $css) === FALSE) { $this->io->write('<error>Error writing require.css to destination</error>'); return false; } }
/** * Adds support for pipeline assets. * * {@inheritdoc} */ protected function parseInput($input, array $options = array()) { if (is_string($input) && '|' == $input[0]) { switch (pathinfo($options['output'], PATHINFO_EXTENSION)) { case 'js': $type = 'js'; break; case 'css': $type = 'css'; break; default: throw new \RuntimeException('Unsupported pipeline asset type provided: ' . $input); } $assets = new AssetCollection(); foreach ($this->locator->locatePipelinedAssets(substr($input, 1), $type) as $formula) { $filters = array(); if ($formula['filter']) { $filters[] = $this->getFilter($formula['filter']); } $asset = new FileAsset($formula['root'] . '/' . $formula['file'], $filters, $options['root'][0], $formula['file']); $asset->setTargetPath($formula['file']); $assets->add($asset); } return $assets; } return parent::parseInput($input, $options); }
protected function createAsset($name, array $assets) { $inputs = array(); $collection = new AssetCollection(); $filters = array(); foreach ($assets as $type => $value) { if ($type === 'filters') { $filters = $value; } elseif (!is_array($value) && $value[0] === '@') { $collection->add(new AssetReference($this->am, substr_replace($value, '', 0, 1))); } elseif ($type === 'files') { foreach ($value as $keyOrSource => $sourceOrFilter) { if (!is_array($sourceOrFilter)) { $collection->add(new \Assetic\Asset\FileAsset($sourceOrFilter)); } else { $filter = array(); foreach ($sourceOrFilter as $filterName) { $filter[] = $this->fm->get($filterName); } $collection->add(new \Assetic\Asset\FileAsset($keyOrSource, $filter)); } } } elseif ($type === 'globs') { foreach ($value as $keyOrGlob => $globOrFilter) { if (!is_array($globOrFilter)) { $collection->add(new \Assetic\Asset\GlobAsset($globOrFilter)); } else { $filter = array(); foreach ($globOrFilter as $filterName) { $filter[] = $this->fm->get($filterName); } $collection->add(new \Assetic\Asset\GlobAsset($keyOrGlob, $filter)); } } } } $this->am->set($name, new AssetCache($collection, new \Assetic\Cache\FilesystemCache($this->config['cacheDir'] . '/chunks'))); $filename = str_replace('_', '.', $name); $this->_compiledAssets[$name] = "{$this->config['baseUrl']}/" . $filename; file_put_contents("{$this->config['assetDir']}/{$filename}", $this->factory->createAsset("@{$name}", $filters)->dump()); @chmod($filename, 0777); }
public function js(array $params) { $jsfiles = Registry::getInstance()->assets['js']; $collection = new AssetCollection(); foreach ($jsfiles as $file) { $collection->add(new FileAsset($file, array(new JsCompressorFilter(APP_PATH . "/vendor/bin/yuicompressor.jar")))); } $cache = new AssetCache($collection, new FilesystemCache(APP_PATH . "/cache/assetic/js")); header('Content-Type: text/javascript'); echo $cache->dump(); }
/** * {@inheritdoc} */ public function process() { $filters = array(new CssRewriteFilter()); if ($this->config->has('component-styleFilters')) { $customFilters = $this->config->get('component-styleFilters'); if (isset($customFilters) && is_array($customFilters)) { foreach ($customFilters as $filter => $filterParams) { $reflection = new \ReflectionClass($filter); $filters[] = $reflection->newInstanceArgs($filterParams); } } } $filterCollection = new FilterCollection($filters); $assets = new AssetCollection(); $styles = $this->packageStyles($this->packages); foreach ($styles as $package => $packageStyles) { $packageAssets = new AssetCollection(); $packagePath = $this->componentDir . '/' . $package; foreach ($packageStyles as $style => $paths) { foreach ($paths as $path) { // The full path to the CSS file. $assetPath = realpath($path); // The root of the CSS file. $sourceRoot = dirname($path); // The style path to the CSS file when external. $sourcePath = $package . '/' . $style; //Replace glob patterns with filenames. $filename = basename($style); if (preg_match('~^\\*(\\.[^\\.]+)$~', $filename, $matches)) { $sourcePath = str_replace($filename, basename($assetPath), $sourcePath); } // Where the final CSS will be generated. $targetPath = $this->componentDir; // Build the asset and add it to the collection. $asset = new FileAsset($assetPath, $filterCollection, $sourceRoot, $sourcePath); $asset->setTargetPath($targetPath); $assets->add($asset); // Add asset to package collection. $sourcePath = preg_replace('{^.*' . preg_quote($package) . '/}', '', $sourcePath); $asset = new FileAsset($assetPath, $filterCollection, $sourceRoot, $sourcePath); $asset->setTargetPath($packagePath); $packageAssets->add($asset); } } if (file_put_contents($packagePath . '/' . $package . '-built.css', $packageAssets->dump()) === FALSE) { $this->io->write("<error>Error writing {$package}-built.css to destination</error>"); } } if (file_put_contents($this->componentDir . '/require.css', $assets->dump()) === FALSE) { $this->io->write('<error>Error writing require.css to destination</error>'); return false; } return null; }
public function jsPackAction() { $collection = new AssetCollection(); foreach ($this->container->getParameter('cms.cms_resources.js_pack') as $asset) { $collection->add(new FileAsset($asset)); } $content = $this->container->getCache()->fetch('cms_assets', 'js_pack', function () use($collection) { return $collection->dump(); }, $collection->getLastModified()); return new Response($content, 200, array('Content-Type' => 'text/javascript')); }
public function testDefault() { $asset = __DIR__ . "/../../resources/test.coffee"; $assetCollection = new AssetCollection(); $assetCollection->add(new FileAsset($asset)); $assetCollection->ensureFilter(new CoffeeScriptPhpFilter()); $ret = $assetCollection->dump(); $exp = "var MyClass, myObject;"; $this->assertRegExp("/{$exp}/", $ret); $exp = "Generated by CoffeeScript PHP"; $this->assertRegExp("/{$exp}/", $ret); }
public function init() { $css = new AssetCollection(); $js = new AssetCollection(); $path =& $this->path; array_walk($this->config['css'], function ($v, $i) use(&$css, $path) { $asset = new FileAsset($path . $v, [new \Assetic\Filter\CssMinFilter()]); $css->add($asset); }); array_walk($this->config['js'], function ($v, $i) use(&$js, $path) { $asset = new FileAsset($path . $v); $js->add($asset); }); $css->setTargetPath('/theme/' . $this->skin . '_styles.css'); $js->setTargetPath('/theme/' . $this->skin . '_scripts.js'); $this->am->set('css', $css); $this->am->set('js', $js); }
public function testIterationFilters() { $count = 0; $filter = new CallablesFilter(function () use(&$count) { ++$count; }); $coll = new AssetCollection(); $coll->add(new StringAsset('')); $coll->ensureFilter($filter); foreach ($coll as $asset) { $asset->dump(); } $this->assertEquals(1, $count, 'collection filters are called when child assets are iterated over'); }
/** * Eejecuta la rutina de minificacion * * Los tipos de recursos aceptados son: * Resources:CSS * Resources:JS * Resources:NONE * * @param int $compile El tipo de recurso a minificar */ public function compile($compile = Resources::NONE) { require_once __DIR__ . '/cssmin-v3.0.1.php'; require_once __DIR__ . '/jsmin.php'; $asset = new AssetCollection(); $this->resources->each(function ($key, $value) use(&$asset) { if ($value->flag) { $asset->add(new FileAsset($value->asset)); } else { $asset->add(new GlobAsset($value->asset)); } }); if ($compile == Resources::JS) { $asset->ensureFilter(new \Assetic\Filter\JSMinFilter()); } if ($compile == Resources::CSS) { $asset->ensureFilter(new \Assetic\Filter\CssMinFilter()); } // the code is merged when the asset is dumped $bundles = \Raptor\Core\Location::get('web_bundles'); if (!file_exists($bundles . $this->bundleName)) { mkdir($bundles . $this->bundleName, 0777, true); } if ($this->name[0] == '/' or $this->name[0] == DIRECTORY_SEPARATOR) { unset($this->name[0]); } $dir = dirname($bundles . $this->bundleName . '/' . $this->name); if (!file_exists($dir)) { mkdir($dir, 0777, true); } if ($this->force == true) { file_put_contents($bundles . $this->bundleName . '/' . $this->name, $asset->dump()); } else { if (!file_exists($bundles . $this->bundleName . '/' . $this->name)) { file_put_contents($bundles . $this->bundleName . '/' . $this->name, $asset->dump()); } } }
protected function _to_collection($files) { $collection = new AssetCollection(); foreach ($files as $file) { $file = Helpers::remove_prepending_forward_slash($file); if (strpos($file, '*') === false) { $asset = new FileAsset($this->_get_asset_path() . $file); } else { $asset = new GlobAsset($this->_get_asset_path() . $file); } $collection->add($asset); } return $collection; }
protected function assetic($files, $type) { $urls = []; foreach ($files as $key => $file) { $assetType = $this->parseInput($file); if ($assetType == 'http') { $urls[] = $file; unset($files[$key]); } } if (empty($files)) { return $urls; } $name = md5(implode(',', $files)) . '.' . $type; $cachePath = $this->config['paths']['pcache']; $cache = $this->config['paths']['cache']; $cachedFile = $this->config['locations']['cache'] . $name; $file = $cachePath . $name; $debug = $this->config['debug']; if (!$debug && file_exists($file)) { $urls[] = $cachedFile; return $urls; } $aw = new AssetWriter($cachePath); $am = new AssetManager(); // Create the collection $collection = new AssetCollection(); // Create the cache $cache = new FilesystemCache($cache); foreach ($files as $file) { $assetType = $this->parseInput($file); // Create the asset if ($assetType == 'file') { $asset = new FileAsset($file); } elseif ($assetType == 'glob') { $asset = new GlobAsset($file); } elseif ($assetType == 'http') { $asset = new HttpAsset($file); } elseif ($assetType == 'reference') { $asset = new AssetReference($am, substr($file, 1)); } $filters = $this->getFilters($file); if (!empty($filters)) { foreach ($filters as $filter) { // Add the filter $asset->ensureFilter($filter); } } // Cache the asset so we don't have to reapply filters on future page loads $cachedAsset = new AssetCache($asset, $cache); // Add the cached asset to the collection $collection->add($cachedAsset); } if (!file_exists($file) || $collection->getLastModified() > filemtime($file)) { $am->set($type, $collection); $am->get($type)->setTargetPath($name); $aw->writeManagerAssets($am); } $urls[] = $cachedFile; return $urls; }
/** * Build the assets list for a package. * * @param Package $package * @param OutputInterface $output * * @return AssetCollection */ protected function buildAssetCollection(Package $package, OutputInterface $output, $indention = '') { if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $output->writeln(sprintf('%s* build collection from <comment>%s</comment>', $indention, $package->getName())); } if (count($package->getFilters()) && $output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) { $output->writeln(sprintf('%s ~ filters:', $indention)); foreach ($package->getFilters() as $filterName => $filter) { $output->writeln(sprintf('%s - <comment>%s</comment> [%s]', $indention, $filterName, get_class($filter))); } } if ($package->getExtends()) { if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $output->writeln(sprintf('%s ~ extend package <comment>%s</comment>', $indention, $package->getExtends())); } $extendPackage = $this->packages[$package->getExtends()]; $assets = $this->buildAssetCollection($extendPackage, $output, $indention . ' '); if (count($package->getFilters())) { $assets->clearFilters(); foreach ($package->getFilters() as $filter) { $assets->ensureFilter($filter); } } } else { $assets = new AssetCollection([], $package->getFilters(), getcwd()); } if ($package->getFiles()) { foreach ($package->getFiles() as $file) { if ($file instanceof PackageFile) { if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $output->writeln(sprintf('%s + add collection <comment>%s</comment>', $indention, $file->getPackageName())); } $mergePackage = $this->packages[$file->getPackageName()]; $asset = $this->buildAssetCollection($mergePackage, $output, $indention . ' '); foreach ($file->getFilters() as $filter) { $asset->ensureFilter($filter); } } else { if ($file instanceof Remotefile) { if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $output->writeln(sprintf('%s + add remote file <comment>%s</comment>', $indention, $file->getUrl())); } $asset = new HttpAsset($file->getUrl(), $file->getFilters()); } else { if ($file instanceof StringFile) { if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $output->writeln(sprintf('%s + add <comment>string</comment>', $indention)); } $asset = new StringAsset($file->getContent(), $file->getFilters()); } else { if ($file instanceof LocalFile) { if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $output->writeln(sprintf('%s + add local file <comment>%s</comment>', $indention, $file->getPathname())); } $asset = new FileAsset($file->getPathname(), $file->getFilters()); } else { continue; } } } } if (count($file->getFilters()) && $output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) { $output->writeln(sprintf('%s ~ filters:', $indention)); foreach ($file->getFilters() as $filterName => $filter) { $output->writeln(sprintf('%s - <comment>%s</comment> [%s]', $indention, $filterName, get_class($filter))); } } $assets->add($asset); } } return $assets; }
public function getAssetCollection(array $assetPaths) { $app = Facade::getFacadeApplication(); $factory = $app->make('Assetic\\Factory\\AssetFactory'); $fsr = $this->app->make('Concrete\\Package\\AssetPipeline\\Src\\Asset\\Filter\\SettingsRepositoryInterface'); $fm = $factory->getFilterManager(); $assets = new AssetCollection(); // Set the filters to he filter manager foreach ($fsr->getAllFilterSettings() as $key => $flt) { if (!$this->app->bound('assets/filter/' . $key)) { throw new Exception(t("Filter not available for key: %s", $key)); } $fm->set($key, $this->app->make('assets/filter/' . $key, $this)); } // Create the asset and push it into the AssetCollection // with the filter keys that should be applied to that // asset $plainAssets = array(); foreach ($assetPaths as $k => $path) { $appliedFilters = array(); foreach ($fsr->getAllFilterSettings() as $key => $flt) { if (!isset($flt['applyTo']) || !$flt['applyTo'] || !is_string($flt['applyTo'])) { continue; } if (preg_match('#' . str_replace('#', '\\#', $flt['applyTo']) . '#', $path)) { $appliedFilters[] = $key; } } if (count($appliedFilters) > 0) { $assets->add($factory->createAsset($path, $appliedFilters)); } else { $plainAssets[] = $path; } } // Add assets that did not go through any filters if (count($plainAssets) > 0) { $assets->add($factory->createAsset($plainAssets)); } return $assets; }
/** * {@inheritDoc} */ public function resolve($name) { if (!isset($this->collections[$name])) { return null; } if (!is_array($this->collections[$name])) { throw new Exception\RuntimeException("Collection with name {$name} is not an an array."); } $collection = new AssetCollection(); $mimeType = null; $collection->setTargetPath($name); foreach ($this->collections[$name] as $asset) { if (!is_string($asset)) { throw new Exception\RuntimeException('Asset should be of type string. got ' . gettype($asset)); } if (null === ($res = $this->getAggregateResolver()->resolve($asset))) { throw new Exception\RuntimeException("Asset '{$asset}' could not be found."); } if (!$res instanceof AssetInterface) { throw new Exception\RuntimeException("Asset '{$asset}' does not implement Assetic\\Asset\\AssetInterface."); } if (null !== $mimeType && $res->mimetype !== $mimeType) { throw new Exception\RuntimeException(sprintf('Asset "%s" from collection "%s" doesn\'t have the expected mime-type "%s".', $asset, $name, $mimeType)); } $mimeType = $res->mimetype; $this->getAssetFilterManager()->setFilters($asset, $res); $collection->add($res); } $collection->mimetype = $mimeType; return $collection; }
/** * Concatenate all scripts together into one destination file. */ public function aggregateScripts($package, array $scripts, $file) { // Aggregate all the assets into one file. $assets = new AssetCollection(); foreach ($scripts as $script) { // Collect each candidate from a glob file search. $path = $this->getVendorDir($package) . DIRECTORY_SEPARATOR . $script; $matches = $this->fs->recursiveGlobFiles($path); foreach ($matches as $match) { $assets->add(new FileAsset($match)); } } $js = $assets->dump(); // Write the file if there are any JavaScript assets. if (!empty($js)) { $destination = $this->componentDir . DIRECTORY_SEPARATOR . $file; $this->fs->ensureDirectoryExists(dirname($destination)); return file_put_contents($destination, $js); } return false; }
public function register(Container $app) { $app['assetic.assets'] = $app['assetic.filters'] = $app['assetic.workers'] = array(); $app['assetic.asset_manager'] = function () use($app) { $am = new AssetManager(); if (isset($app['assetic.assets'])) { $assets = $app['assetic.assets']; if (!is_array($assets)) { $assets = array($assets); } foreach ($assets as $name => $asset) { if (!is_array($asset)) { // não collection, transformar em collection $asset = array($asset); } $col = new AssetCollection(); foreach ($asset as $a) { if (is_string($a)) { // é referencia $a = new AssetReference($am, $a); } if (!$a instanceof AssetInterface) { throw new \InvalidArgumentException("'assetic.assets' precisa ser um array de AssetInterface"); } $col->add($a); } $am->set($name, $col); } } return $am; }; $app['assetic.filter_manager'] = function () use($app) { $fm = new FilterManager(); if (isset($app['assetic.filters'])) { $filters = $app['assetic.filters']; if (!is_array($filters)) { $filters = array($filters); } foreach ($filters as $name => $filter) { $fm->set($name, $filter); } } return $fm; }; $app['assetic.factory'] = function () use($app) { $factory = new AssetFactory($app['assetic.dist_path']); $factory->setAssetManager($app['assetic.asset_manager']); $factory->setFilterManager($app['assetic.filter_manager']); $factory->setDebug(isset($app['debug']) ? $app['debug'] : false); $factory->setDefaultOutput($app['assetic.dist_path']); if (isset($app['assetic.workers']) && is_array($app['assetic.workers'])) { foreach ($app['assetic.workers'] as $worker) { $factory->addWorker($worker); } } return $factory; }; $app['assetic.lazy_asset_manager'] = function () use($app) { $am = new LazyAssetManager($app['assetic.factory']); if (isset($app['twig'])) { // carrega os assets pelo twig $am->setLoader('twig', new TwigFormulaLoader($app['twig'])); $loader = $app['twig.loader.filesystem']; $namespaces = $loader->getNamespaces(); foreach ($namespaces as $ns) { if (count($loader->getPaths($ns)) > 0) { $iterator = Finder::create()->files()->in($loader->getPaths($ns)); foreach ($iterator as $file) { $resource = new TwigResource($loader, '@' . $ns . '/' . $file->getRelativePathname()); $am->addResource($resource, 'twig'); } } } } return $am; }; $app['assetic.asset_writer'] = function () use($app) { return new AssetWriter($app['assetic.dist_path']); }; if (isset($app['twig'])) { $app['twig'] = $app->extend('twig', function ($twig, $app) { $functions = array('cssrewrite' => array('options' => array('combine' => true))); $twig->addExtension(new AsseticExtension($app['assetic.factory'], $functions)); return $twig; }); } }
/** * 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) : ''; }
public function testGetLastModifiedCollection() { $leaf = $this->getMock('Assetic\\Asset\\AssetInterface'); $child = $this->getMock('Assetic\\Asset\\AssetInterface'); $filter1 = $this->getMock('Assetic\\Filter\\FilterInterface'); $filter2 = $this->getMock('Assetic\\Filter\\DependencyExtractorInterface'); $asset = new AssetCollection(); $asset->add($leaf); $leaf->expects($this->any())->method('getLastModified')->will($this->returnValue(123)); $leaf->expects($this->any())->method('getFilters')->will($this->returnValue(array($filter1, $filter2))); $leaf->expects($this->once())->method('ensureFilter')->with($filter1); $filter2->expects($this->once())->method('getChildren')->with($this->factory)->will($this->returnValue(array($child))); $child->expects($this->any())->method('getLastModified')->will($this->returnValue(456)); $child->expects($this->any())->method('getFilters')->will($this->returnValue(array())); $this->assertEquals(456, $this->factory->getLastModified($asset)); }
public function testClearingFiltersWorksAfterCollectionHasBeenIterated() { $coll = new AssetCollection(); $coll->add(new StringAsset("")); $coll->ensureFilter(new CallablesFilter()); /* This iteration is necessary to internally prime the collection's "clones" with one filter. */ foreach ($coll as $asset) { $this->assertCount(1, $asset->getFilters()); } $coll->clearFilters(); foreach ($coll as $asset) { $this->assertCount(0, $asset->getFilters()); } }
protected function getAsseticAssets($onlyTypes = [], $onlySections = []) { $return = []; $onlyTypes = $this->getKeysIfEmpty($this->collections, $onlyTypes); foreach ($onlyTypes as $type) { if (!isset($this->collections[$type])) { continue; } $onlySections = $this->getKeysIfEmpty($this->collections[$type], $onlySections); foreach ($onlySections as $section) { if (!isset($this->collections[$type][$section])) { continue; } else { $collections = $this->collections[$type][$section]; } /** * Sort collections by priority. */ ksort($collections); foreach ($collections as $priority => $collection) { $typePath = path('storage') . 'cache' . path('ds') . 'www' . path('ds') . $type . path('ds'); $assetCollection = new AssetCollection([], [], $typePath); foreach ($collection as $asset) { $filters = []; if ($type == 'less') { $filters[] = new LessPckgFilter(); $filters[] = new PathPckgFilter(); } if (in_array($type, ['css', 'less'])) { $filters[] = new PathPckgFilter(); } $assetCollection->add(new FileAsset($asset, $filters)); } $lastModified = $assetCollection->getLastModified(); $cachePath = $typePath . $priority . '-' . $section . '-' . $lastModified . '.' . $type; $assetCollection->setTargetPath($cachePath); file_put_contents($cachePath, $assetCollection->dump()); $return[] = str_replace('##LINK##', str_replace(path('root'), path('ds'), $cachePath), $this->types[$type]); } } } return $return; }
protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); $filesystem = $container->get('filesystem'); $languages = $container->getParameter('hatimeria_ext_js.locales'); $files = $container->getParameter('hatimeria_ext_js.compiled_files'); $domains = $container->getParameter("hatimeria_ext_js.translation_domains"); $vendorPath = $container->getParameter("hatimeria_ext_js.javascript_vendor_path"); $hdefault = new JavascriptController(); $hdefault->setContainer($container); $dynamic = $hdefault->dynamicAction()->getContent(); $hdirect = new DirectController(); $hdirect->setContainer($container); $api = $hdirect->getApiAction()->getContent(); $expose = $container->get('bazinga.exposetranslation.controller'); $routing = $container->get('fos_js_routing.controller'); $compressor = new JsCompressorFilter('vendor/bundles/Hatimeria/ExtJSBundle/Resources/jar/yuicompressor.jar'); $extjs = "web/bundles/hatimeriaextjs/js/extjs/"; // @todo recursive glob foreach ($languages as $lang) { $ac = new AssetCollection(); $ac->add(new FileAsset("web/" . $vendorPath . "/ext-all.js")); $ac->add(new FileAsset($extjs . "/core/overrides.js")); $ac->add(new StringAsset($dynamic)); $ac->add(new FileAsset($extjs . "/translation/Translation.js")); foreach ($domains as $domain) { $ac->add(new StringAsset($expose->exposeTranslationAction($domain, $lang, 'js')->getContent())); } $ac->add(new FileAsset("web/" . $vendorPath . "locale/ext-lang-" . $lang . ".js")); $ac->add(new FileAsset($extjs . "/core/direct-api-handler.js")); $ac->add(new FileAsset($extjs . "/routing/Routing.js")); $ac->add(new GlobAsset($extjs . "/core/utils/*")); $ac->add(new GlobAsset($extjs . "/core/mixins/*")); $ac->add(new GlobAsset($extjs . "/core/store/*")); $ac->add(new GlobAsset($extjs . "/core/model/*")); $ac->add(new GlobAsset($extjs . "/core/grid/*")); $ac->add(new GlobAsset($extjs . "/core/response/*")); $ac->add(new GlobAsset($extjs . "/core/window/*")); $ac->add(new FileAsset($extjs . "/core/form/BaseForm.js")); $ac->add(new GlobAsset($extjs . "/core/form/*")); $ac->add(new GlobAsset($extjs . "/core/field/*")); $ac->add(new GlobAsset($extjs . "/core/user/*")); $ac->add(new GlobAsset($extjs . "/treeselect/store/*")); $ac->add(new GlobAsset($extjs . "/treeselect/panel/*")); $ac->add(new GlobAsset($extjs . "/treeselect/field/*")); $ac->add(new StringAsset($api)); $ac->add(new StringAsset($routing->indexAction('js')->getContent())); foreach ($files as $file) { $ac->add(new FileAsset('web/' . $file)); } $ac->ensureFilter($compressor); $compiled = $ac->dump(); @mkdir('web/compiled/js', 0755, true); file_put_contents(sprintf("web/compiled/js/ext-%s.js", $lang), $compiled); } $output->writeln('Assets compiled'); }
/** * Create asset collection from collection array * * @param $collection * @param array $additionalFilters * @return AssetCollection */ private function getAssetCollection($collection, $additionalFilters = []) { $assets = new AssetCollection(); $hint = $this->paths->hint($collection); foreach ($this->collections[$collection] as $file => $filters) { $filters = array_filter(array_unique(array_merge($filters, $additionalFilters))); $filters = $this->transformFilters($filters, $hint); if (in_array('glob', $filters)) { unset($filters[array_search('glob', $filters)]); $file = new GlobAsset($file, $filters); } else { $file = new FileAsset($file, $filters); } $assets->add($file); } return $assets; }
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]; }