protected function configureAssetTools() { $fm = new FilterManager(); $fm->set('less', new LessphpFilter()); $fm->set('cssrewrite', new AssetCssUriRewriteFilter()); $fm->set('cssmin', new CssMinFilter()); $fm->set('jscompile', new CompilerApiFilter()); //$fm->set('jscompilejar', new CompilerJarFilter(storage_path('jar/compiler.jar'))); $factory = new AssetFactory(Config::get('asset-manager::asset.paths.asset_path')); $factory->setFilterManager($fm); $factory->setDebug(Config::get('app.debug')); $this->assetFactory = $factory; }
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); }
/** * * @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'])); }); }
/** * @param array $configuration * @return Factory\AssetFactory */ public function createAssetFactory(array $configuration) { $factory = new Factory\AssetFactory($configuration['root_path']); $factory->setAssetManager($this->getAssetManager()); $factory->setFilterManager($this->getFilterManager()); // Cache buster should be add only if cache is enabled and if is available. if ($this->configuration->getCacheEnabled()) { $worker = $this->getCacheBusterStrategy(); if ($worker instanceof WorkerInterface) { $factory->addWorker($worker); } } $factory->setDebug($this->configuration->isDebug()); return $factory; }
/** * @param array $configuration * * @return Factory\AssetFactory */ public function createAssetFactory(array $configuration) { $factory = new Factory\AssetFactory($configuration['root_path']); $factory->setAssetManager($this->getAssetManager()); $factory->setFilterManager($this->getFilterManager()); $worker = $this->getCacheBusterStrategy(); if ($worker instanceof WorkerInterface) { $factory->addWorker($worker); } $factory->setDebug($this->configuration->isDebug()); return $factory; }
/** * 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; } }
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); } }
$type = 'text/css; charset=UTF-8'; array_push($filters, 'embed'); array_push($filters, '?css_min'); } else { App: abort(404); } $fm = new FilterManager(app_path() . '/assets/'); $fm->set('less', new LessphpFilter()); $fm->set('scss', new ScssphpFilter()); $fm->set('embed', new PhpCssEmbedFilter()); $fm->set('coffee', new CoffeeScriptFilter()); $fm->set('css_min', new CssMinFilter()); $fm->set('js_min', new CompilerApiFilter()); $factory = new AssetFactory(app_path() . '/assets/'); $factory->setFilterManager($fm); $factory->setDebug(App::environment() == 'local' ? true : false); $content = $factory->createAsset($files, array_filter($filters)); if (App::environment() != 'local') { if (!File::isDirectory(dirname($putLocation))) { File::makeDirectory(dirname($putLocation), 0777, true); } File::put($putLocation, $content->dump()); return Redirect::to($args); } else { File::deleteDirectory(public_path() . '/assets'); } $response = Response::make($content->dump()); $response->header('content-type', $type); return $response; }])->where('args', 'assets/(.*)');
use Assetic\AssetManager; use Assetic\AssetWriter; use Assetic\Extension\Twig\AsseticExtension; use Assetic\Extension\Twig\TwigFormulaLoader; use Assetic\Extension\Twig\TwigResource; use Assetic\Factory\AssetFactory; use Assetic\Factory\LazyAssetManager; use Assetic\Filter\LessFilter; use Assetic\FilterManager; use Symfony\Component\Finder\Finder; $loader = new Twig_Loader_Filesystem(VIEWS_PATH); $options = ['cache' => DEBUG_APP ? false : 'cache']; $twig = new Twig_Environment($loader, $options); $assetManager = new AssetManager(); $filterManager = new FilterManager(); $filterManager->set('less', new LessFilter(NODE_PATH, [NODE_MODULE_PATH])); $assetFactory = new AssetFactory('assets/'); $assetFactory->setDebug(false); $assetFactory->setAssetManager($assetManager); $assetFactory->setFilterManager($filterManager); $twig->addExtension(new AsseticExtension($assetFactory)); $lazyAssetManager = new LazyAssetManager($assetFactory); $lazyAssetManager->setLoader('twig', new TwigFormulaLoader($twig)); $finder = new Finder(); $finder->files()->in('assets')->exclude('css')->exclude('js')->exclude('images')->name("*.twig"); foreach ($finder as $template) { $resource = new TwigResource($loader, $template->getFileName()); $lazyAssetManager->addResource($resource, 'twig'); } $writer = new AssetWriter('.'); $writer->writeManagerAssets($lazyAssetManager);
require '../vendor/autoload.php'; use Assetic\AssetManager; 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);
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; }); } }
public function __construct() { $this->request = Request::createFromGlobals(); $this->container = Container::getInstance(); /* Parse params file - Begin */ $params = $this->parseYamlFile(APP_DIR . DS . 'configs' . DS . 'params.yml'); $isDev = $params['environment'] === 'development'; if ($isDev) { Debug::enable(E_STRICT); } date_default_timezone_set($params['timezone']); /* Parse params file - End */ /* Parse routes file - Begin */ $routes = $this->parseYamlFile(APP_DIR . DS . 'configs' . DS . 'routes.yml'); $collection = new RouteCollection(); foreach ($routes as $name => $options) { $parts = explode(':', $options['defaults']['_controller']); $options['defaults'] = array('_controller' => "{$parts[0]}\\Controllers\\{$parts[1]}Controller::{$parts[2]}Action"); $route = new Route($options['path']); $route->setDefaults($options['defaults']); $route->setRequirements(isset($options['requirements']) ? $options['requirements'] : array()); $route->setOptions(isset($options['options']) ? $options['options'] : array()); $route->setHost(isset($options['host']) ? $options['host'] : ''); $route->setSchemes(isset($options['schemes']) ? $options['schemes'] : array()); $route->setMethods(isset($options['methods']) ? $options['methods'] : array()); $route->setCondition(isset($options['condition']) ? $options['condition'] : ''); $collection->add($name, $route); } $this->container->setParameter('routes', $collection); /* Parse routes file - End */ /* Composer ClassLoader - Begin */ $composer_loader = new ClassLoader(); $composer_loader->addPsr4('Application\\Controllers\\', APP_DIR . DS . 'layers' . DS . 'controllers'); $composer_loader->addPsr4('Application\\Models\\', APP_DIR . DS . 'layers' . DS . 'models'); $composer_loader->register(); /* Composer ClassLoader - End */ /* Set error controller - Begin */ $namespace = $isDev ? 'Hideks\\Controller\\' : 'Application\\Controllers\\'; $this->container->setParameter('exception.controller', $namespace . 'ErrorController::exceptionAction'); /* Set error controller - End */ /* Assetic configuration setup - Begin */ $filter_manager = new FilterManager(); $filter_manager->set('css_min', new CssMinFilter()); $filter_manager->set('lessphp', new LessphpFilter()); $filter_manager->set('js_min', new JSMinFilter()); $asset_factory = new AssetFactory(APP_DIR . DS . 'assets' . DS); $asset_factory->setDebug($isDev); $asset_factory->setFilterManager($filter_manager); $asset_factory->addWorker(new CacheBustingWorker()); $this->container->setParameter('assetic.factory', $asset_factory); /* Assetic configuration setup - End */ /* Twig configuration setup - Begin */ $this->container->setParameter('twig.debug', $isDev); $this->container->setParameter('twig.cache', $isDev ? false : APP_DIR . DS . 'cache' . DS . 'twig'); $twig_loader = $this->container->get('twig.loader'); $twig_loader->addPath(APP_DIR . DS . 'layers' . DS . 'views'); /* Twig configuration setup - End */ /* Active Record configuration setup - Begin */ $active_record = \ActiveRecord\Config::instance(); $active_record->set_model_directory(APP_DIR . DS . 'layers' . DS . 'models'); $active_record->set_connections($params['connections']); $active_record->set_default_connection($params['environment']); /* Active Record configuration setup - End */ }
protected function _render($assets = array(), $filters = array()) { // Setup AssetFactory $factory = new AssetFactory($this->_get_asset_path()); $factory->setAssetManager($this->_get_am()); $factory->setFilterManager($this->_get_fm()); $config = $this->_get_config(); $factory->setDebug($config['debug']); return $factory->createAsset($assets, $filters)->dump(); }
/** * @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; }); } }
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; } } }
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(); }
/** * 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'); }