protected function getAsseticFactory() { if (empty($this->config["input_path"][0])) { throw new \Exception('Empty input path'); } $factory = new AssetFactory($this->config["input_path"][0], $this->config["debug"]); $factory->setDefaultOutput(""); // add a FilterManager to the AssetFactory $fm = new FilterManager(); $factory->setFilterManager($fm); // adding some filters to the filter manager if ($this->config["less_filter"]) { $lessphpFilter = new LessphpFilter(); if ($this->lessPresets) { $lessphpFilter->setPresets($this->lessPresets); } $fm->set("less", $lessphpFilter); } if ($this->config["scss_filter"]) { $scssFilter = new ScssphpFilter(); $fm->set("scss", $scssFilter); } $fm->set("min", new CssMinFilter()); return $factory; }
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; }
protected function getAsseticFactory() { if (empty($this->config["input_path"][0])) { throw new \Exception("Empty input path"); } $factory = new AssetFactory($this->config["input_path"][0], $this->config["debug"]); $factory->setDefaultOutput(""); // add a FilterManager to the AssetFactory $fm = new FilterManager(); $factory->setFilterManager($fm); $fm->set("jshrink", new JShrinkFilter()); return $factory; }
/** * {@inheritDoc} */ public function init(Application $app) { $app['assets'] = $app->share(function () use($app) { $assetManager = new AssetManager(); $filterManager = new FilterManager(); $filterManager->set('less', new LessphpFilter()); $filterManager->set('cssmin', new CssMinFilter()); $filterManager->set('jsmin', new JSqueezeFilter()); $factory = new AssetFactory($app['assets.path']); $factory->setAssetManager($assetManager); $factory->setFilterManager($filterManager); $factory->setDefaultOutput('misc/*'); return $factory; }); }
/** * * @param Application $app */ function register(Application $app) { $app['assetic.asset.root'] = ''; $app['assetic.asset.output_root'] = ''; $app['assetic.debug'] = false; $app['assetic.filter'] = array(); $app['assetic.filter.default'] = array('cssmin' => '\\Assetic\\Filter\\CssMinFilter', 'cssrewrite' => '\\Assetic\\Filter\\CssRewriteFilter'); $app['assetic.filter_manager'] = $app->share(function ($app) { $filterManager = new FilterManager(); return $filterManager; }); $app['assetic.asset_manager'] = $app->share(function ($app) { $assetManager = new AssetManager(); return $assetManager; }); $app['assetic.asset_factory'] = $app->share(function ($app) { $assetFactory = new AssetFactory($app['assetic.asset.root']); $assetFactory->setDefaultOutput($app['assetic.asset.output_root']); $assetFactory->setFilterManager($app['assetic.filter_manager']); $assetFactory->setAssetManager($app['assetic.asset_manager']); $assetFactory->setDebug($app['assetic.debug']); return $assetFactory; }); $app['assetic.lazy_asset_manager'] = $app->share(function ($app) { $lazyAssetManager = new LazyAssetManager($app['assetic.asset_factory']); $lazyAssetManager->setLoader('twig', new TwigAsseticIntegrationFormulaLoader($app['twig'], null, $app)); return $lazyAssetManager; }); $app['assetic.asset_writer'] = $app->share(function ($app) { $assetWriter = new AssetWriter($app['assetic.asset.output_root']); return $assetWriter; }); /* * Twig * */ // Replace Twig loader $app['twig.loader.filesystem'] = $app->share(function ($app) { return new \Wake\Twig_AsseticLoader_Filesystem($app['twig.path']); }); $app['twig.loader'] = $app->share(function ($app) { return new \Wake\Twig_AsseticLoader_Chain(array($app['twig.loader.array'], $app['twig.loader.filesystem'])); }); }
/** * 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, '/'); }
/** * 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; } }
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; } } }
use Assetic\Factory\AssetFactory; use Assetic\FilterManager; use Assetic\AssetManager; use Assetic\Cache\FilesystemCache; 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); };
/** * Returns the public path of an asset * * @return string A public path */ public function asseticBlock(array $params = array(), $content = null, $template, &$repeat) { // In debug mode, we have to be able to loop a certain number of times, so we use a static counter static $count; static $assetsUrls; // Read config file if (isset($params['config_path'])) { $base_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $params['config_path']; } else { // Find the config file in Symfony2 config dir $base_path = __DIR__ . '/../../../../app/config/smarty-assetic'; } $config = json_decode(file_get_contents($base_path . '/config.json')); // Opening tag (first call only) if ($repeat) { // Read bundles and dependencies config files $bundles = json_decode(file_get_contents($base_path . '/bundles.json')); $dependencies = json_decode(file_get_contents($base_path . '/dependencies.json')); $am = new AssetManager(); $fm = new FilterManager(); $fm->set('yui_js', new Filter\Yui\JsCompressorFilter($config->yuicompressor_path, $config->java_path)); $fm->set('yui_css', new Filter\Yui\CssCompressorFilter($config->yuicompressor_path, $config->java_path)); $fm->set('less', new Filter\LessphpFilter()); $fm->set('sass', new Filter\Sass\SassFilter()); $fm->set('closure_api', new Filter\GoogleClosure\CompilerApiFilter()); $fm->set('closure_jar', new Filter\GoogleClosure\CompilerJarFilter($config->closurejar_path, $config->java_path)); // Factory setup $factory = new AssetFactory($_SERVER['DOCUMENT_ROOT']); $factory->setAssetManager($am); $factory->setFilterManager($fm); $factory->setDefaultOutput('assetic/*.' . $params['output']); if (isset($params['filter'])) { $filters = explode(',', $params['filter']); } else { $filters = array(); } // Prepare the assets writer $writer = new AssetWriter($params['build_path']); // If a bundle name is provided if (isset($params['bundle'])) { $asset = $factory->createAsset($bundles->{$params}['output']->{$params}['bundle'], $filters, array($params['debug'])); $cache = new AssetCache($asset, new FilesystemCache($params['build_path'])); $writer->writeAsset($cache); // If individual assets are provided } elseif (isset($params['assets'])) { $assets = array(); // Include only the references first foreach (explode(',', $params['assets']) as $a) { // If the asset is found in the dependencies file, let's create it // If it is not found in the assets but is needed by another asset and found in the references, don't worry, it will be automatically created if (isset($dependencies->{$params}['output']->assets->{$a})) { // Create the reference assets if they don't exist foreach ($dependencies->{$params}['output']->assets->{$a} as $ref) { try { $am->get($ref); } catch (InvalidArgumentException $e) { $assetTmp = $factory->createAsset($dependencies->{$params}['output']->references->{$ref}); $am->set($ref, $assetTmp); $assets[] = '@' . $ref; } } } } // Now, include assets foreach (explode(',', $params['assets']) as $a) { // Add the asset to the list if not already present, as a reference or as a simple asset $ref = null; if (isset($dependencies->{$params}['output'])) { foreach ($dependencies->{$params}['output']->references as $name => $file) { if ($file == $a) { $ref = $name; break; } } } if (array_search($a, $assets) === false && ($ref === null || array_search('@' . $ref, $assets) === false)) { $assets[] = $a; } } // Create the asset $asset = $factory->createAsset($assets, $filters, array($params['debug'])); $cache = new AssetCache($asset, new FilesystemCache($params['build_path'])); $writer->writeAsset($cache); } // If debug mode is active, we want to include assets separately if ($params['debug']) { $assetsUrls = array(); foreach ($asset as $a) { $cache = new AssetCache($a, new FilesystemCache($params['build_path'])); $writer->writeAsset($cache); $assetsUrls[] = $a->getTargetPath(); } // It's easier to fetch the array backwards, so we reverse it to insert assets in the right order $assetsUrls = array_reverse($assetsUrls); $count = count($assetsUrls); if (isset($config->site_url)) { $template->assign($params['asset_url'], $config->site_url . '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]); } else { $template->assign($params['asset_url'], '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]); } // Production mode, include an all-in-one asset } else { if (isset($config->site_url)) { $template->assign($params['asset_url'], $config->site_url . '/' . $params['build_path'] . '/' . $asset->getTargetPath()); } else { $template->assign($params['asset_url'], '/' . $params['build_path'] . '/' . $asset->getTargetPath()); } } // Closing tag } else { if (isset($content)) { // If debug mode is active, we want to include assets separately if ($params['debug']) { $count--; if ($count > 0) { if (isset($config->site_url)) { $template->assign($params['asset_url'], $config->site_url . '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]); } else { $template->assign($params['asset_url'], '/' . $params['build_path'] . '/' . $assetsUrls[$count - 1]); } } $repeat = $count > 0; } return $content; } } }
public function 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; }); } }
/** * @param Container $container */ public function register(Container $container) { $container['assetic.asset.root'] = ''; $container['assetic.asset.asset_root'] = ''; $container['assetic.asset.factory'] = function () use($container) { $assetFactory = new AssetFactory($container['assetic.asset.root']); $assetFactory->setDefaultOutput($container['assetic.asset.asset_root']); $assetFactory->setDebug(isset($container['debug']) ? $container['debug'] : false); $assetFactory->setFilterManager($container['assetic.filter_manager']); return $assetFactory; }; $container['assetic.filters.default'] = array('csscopyfile' => true, 'lessphp' => true, 'scssphp' => true, 'cssmin' => true, 'csscompress' => true, 'jsmin' => true); $container['assetic.filters'] = function () use($container) { return array(); }; $container['assetic.filterinstances'] = function () use($container) { $filterInstances = array(); $filterConfig = array_merge($container['assetic.filters.default'], $container['assetic.filters']); if ($filterConfig['csscopyfile']) { $filterInstances['csscopyfile'] = new CssCopyFileFilter($container['assetic.asset.asset_root']); } if ($filterConfig['lessphp'] && class_exists('\\lessc')) { $filterInstances['lessphp'] = new LessphpFilter(); } if ($filterConfig['scssphp'] && class_exists('\\scssc')) { $filterInstances['scssphp'] = new ScssphpFilter(); } if ($filterConfig['cssmin'] && class_exists('\\CssMin')) { $filterInstances['cssmin'] = new CssMinFilter(); } if ($filterConfig['csscompress'] && class_exists('\\Minify_CSS_Compressor')) { $filterInstances['csscompress'] = new MinifyCssCompressorFilter(); } if ($filterConfig['jsmin'] && class_exists('\\JSMin')) { $filterInstances['jsmin'] = new JSMinFilter(); } return $filterInstances; }; $container['assetic.filter_manager'] = function () use($container) { $filterManager = new FilterManager(); $filters = $container['assetic.filterinstances']; foreach ($filters as $alias => $filter) { $filterManager->set($alias, $filter); } return $filterManager; }; $container['assetic.asset.manager'] = function () use($container) { $assetManager = new LazyAssetManager($container['assetic.asset.factory']); $assetManager->setLoader('twig', new TwigFormulaLoader($container['twig'], $container['logger'])); return $assetManager; }; $container['assetic.asset.writer'] = function () use($container) { return new AssetWriter($container['assetic.asset.asset_root']); }; $container['assetic.asset.dumper'] = function () use($container) { return new Dumper($container['twig.loader.filesystem'], $container['assetic.asset.manager'], $container['assetic.asset.writer']); }; $container['twig'] = $container->extend('twig', function (\Twig_Environment $twig) use($container) { $twig->addExtension(new AsseticExtension($container['assetic.asset.factory'])); return $twig; }); if (isset($container['console.commands'])) { $container['console.commands'] = $container->extend('console.commands', function ($commands) use($container) { $commands[] = new AsseticDumpCommand(null, $container); return $commands; }); } }
/** * Render the Twig template with Assetic manager * * If Twig Loader method is string, we can render view as string template and * set the params, else there is no need to declare params or view in this method. * * @param string $view * @param array $params * @return void */ public function render($view = "", $params = array()) { $this->_ci->benchmark->mark('AttireRender_start'); # Autoload url helper (required) $this->_ci->load->helper('url'); # Set additional config functions/global vars inside Attire environment $this->set_config_globals(); $this->set_config_functions(); # Add default view path $this->add_path(VIEWPATH, 'VIEWPATH'); # Twig environment (master of puppets) $twig =& $this->_environment; $escaper = new Twig_Extension_Escaper('html'); $twig->addExtension($escaper); $twig->addFilter('var_dump', new Twig_Filter_Function('var_dump')); # Declare asset manager and add global paths $am = new AssetManager(); # Assets global paths if ($this->_bundle_path !== NULL) { $class = $this->_ci->router->fetch_class(); $method = $this->_ci->router->fetch_method(); $directory = $this->_ci->router->directory; $this->_bundle_path = rtrim($this->_bundle_path, '/') . '/'; $absolute_path = rtrim($this->_bundle_path . $directory . 'assets', '/'); $global_assets = array('module_js' => array('path' => "{$absolute_path}/js/{$class}/{$method}/*", 'type' => 'Assetic\\Asset\\GlobAsset'), 'module_css' => array('path' => "{$absolute_path}/css/{$class}/{$method}/*", 'type' => 'Assetic\\Asset\\GlobAsset'), 'global_css' => array('path' => "{$absolute_path}/css/{$class}/*", 'type' => 'Assetic\\Asset\\GlobAsset'), 'global_js' => array('path' => "{$absolute_path}/js/{$class}/*", 'type' => 'Assetic\\Asset\\GlobAsset')); foreach (array_merge($global_assets, $this->_assets) as $global => $params) { $class_name = $params['type']; $am->set($global, new $class_name($params['path'])); } } # Declare filters manager $fm = new FilterManager(); $fm->set('cssrewrite', new CssRewriteFilter()); $absolute_path = rtrim("{$this->_paths["theme"]}{$this->_theme}", '/') . '/assets'; # Declare assetic factory with filters and assets $factory = new AssetFactory($absolute_path); $factory->setAssetManager($am); $factory->setFilterManager($fm); $factory->setDebug($this->_debug); # Add assetic extension to factory $absolute_path = rtrim($this->_paths['assets'], '/'); $factory->setDefaultOutput($absolute_path); $twig->addExtension(new AsseticExtension($factory)); # This is too lazy, we need a lazy asset manager... $am = new LazyAssetManager($factory); $am->setLoader('twig', new TwigFormulaLoader($twig)); # Add the Twig resource (following the assetic documentation) $resource = new TwigResource($this->_loader, $this->_default_template . $this->_extension); $am->addResource($resource, 'twig'); # Write all assets files in the output directory in one or more files try { $writer = new AssetWriter($absolute_path); $writer->writeManagerAssets($am); } catch (\RuntimeException $e) { $this->_show_error($e->getMessage()); } # Set current lexer if (!empty($this->_current_lexer)) { $lexer = new Twig_Lexer($this->_environment, $this->_current_lexer); $twig->setLexer($lexer); } try { # Render all childs if (!empty($this->_childs)) { foreach ($this->_childs as $child => $params) { $this->_params['views'] = $this->_views; echo $twig->render($child, array_merge($params, $this->_params)); } # Remove childs after the use $this->_childs = array(); } elseif (strlen($view) <= 1 && $this->_loader instanceof Twig_Loader_String) { echo $twig->render($this->_default_template . $this->_extension, $params); } } catch (Twig_Error_Syntax $e) { $this->_show_error($e->getMessage()); } $this->_ci->benchmark->mark('AttireRender_end'); }