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; }
/** * @param $rootPath * @param $debug * @return AssetFactory */ private function getAssetFactory($rootPath, $debug) { $filterManager = new FilterManager(); $filterManager->set('yui_js', new JsCompressorFilter(dirname(__DIR__) . '/../optimizers/yuicompressor/yuicompressor-2.4.7.jar')); $assetFactory = new AssetFactory($rootPath, $debug); $assetFactory->setFilterManager($filterManager); $assetFactory->setAssetManager(new AssetManager()); return $assetFactory; }
protected function factoryAf() { $uglify = new UglifyJs2Filter("/usr/bin/uglifyjs", "/usr/bin/node"); $uglify->setCompress(true); $uglify->setMangle(true); $uglify->setCompress(true); $factory = new AssetFactory(__DIR__ . "/../"); $filterManager = new FilterManager(); $filterManager->set("uglify", $uglify); $factory->setFilterManager($filterManager); return $factory; }
/** * Builds the AssetFactory object * * @return \Assetic\Factory\AssetFactory */ public function build() { $assetManager = new AssetManager(); $filterManager = new FilterManager(); foreach ($this->filters as $filterName => $filter) { $filterManager->set($filterName, $filter); } $assetsFactory = new AssetFactory($this->configurationHandler->webDir()); $assetsFactory->setAssetManager($assetManager); $assetsFactory->setFilterManager($filterManager); return $assetsFactory; }
public function testFilterDumpWithFilterManager() { $filterManager = new FilterManager(); $filterManager->set('css_optimize', $this->filter); $expected = 'body{baz:foo;foo:new;too:me}div.other,div.test{border:1px solid black}'; $inputCss = 'body { foo:bar; too: me;} body { baz:foo; } body { foo: new } div.test { border: 1px solid black; } div.other { border: 1px solid black} '; $asset = new StringAsset($inputCss); $asset->ensureFilter($filterManager->get('css_optimize')); $result = $asset->dump(); $this->assertEquals($expected, $result); }
/** * {@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; }); }
public function all() { $filters = array(); foreach ($this->mappings as $name => $id) { $filters[$name] = $this->container->get($id); } return $filters + parent::all(); }
public function testFilterFunction() { $filter = $this->getMock('Assetic\\Filter\\FilterInterface'); $this->fm->expects($this->once())->method('get')->with('some_filter')->will($this->returnValue($filter)); $this->twig->addExtension(new AsseticExtension($this->factory, array('some_func' => array('filter' => 'some_filter', 'options' => array('output' => 'css/*.css'))))); $xml = $this->renderXml('function.twig'); $this->assertEquals(1, count($xml->asset)); $this->assertStringEndsWith('.css', (string) $xml->asset[0]['url']); }
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(); }
protected function restoreFormulaFilters(array $formula) { if (!$this->filterManager instanceof FilterManager) { return $formula; } if (!$formula[0] instanceof \Assetic\Asset\FileAsset) { return $formula; } if (!isset($formula[1]) || !is_array($formula[1]) || !count($formula[1])) { return $formula; } $filters = array(); foreach ($formula[1] as $filterName) { $filters[$filterName] = $this->filterManager->get($filterName); } $assetClass = get_class($formula[0]); $new = new $assetClass($formula[0]->getSourceRoot() . DIRECTORY_SEPARATOR . $formula[0]->getSourcePath(), $filters, $formula[0]->getSourceRoot(), $formula[0]->getSourcePath(), $formula[0]->getVars()); $new->setTargetPath($formula[0]->getTargetPath()); $formula[0] = $new; return $formula; }
/** * Get filters to apply against resource. * * @param ResourceInterface $resource Resource with filters. * @return array Collection of filters to apply on resource. */ private function getFilters(ResourceInterface $resource) { if (isset($resource->getOptions()['filters']) && count($resource->getOptions()['filters'])) { $result = []; foreach ($filters = $resource->getOptions()['filters'] as $filter) { if (strpos($filter, '?') !== 0 || strpos($filter, '?') === 0 && !$this->options['development']) { $result[$filter] = $this->filterManager->get(ltrim($filter, '?')); } } return $result; } else { return []; } }
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; }
/** * @param $alias * * @throws \InvalidArgumentException When cant retrieve filter from service manager. * * @return mixed */ public function get($alias) { if (parent::has($alias)) { return parent::get($alias); } $service = $this->serviceLocator; if (!$service->has($alias)) { throw new \InvalidArgumentException(sprintf('There is no "%s" filter in ZF2 service manager.', $alias)); } $filter = $service->get($alias); if (!$filter instanceof FilterInterface) { $givenType = is_object($filter) ? get_class($filter) : gettype($filter); $message = 'Retrieved filter "%s" is not instanceof "Assetic\\Filter\\FilterInterface", but type was given %s'; $message = sprintf($message, $alias, $givenType); throw new \InvalidArgumentException($message); } $this->set($alias, $filter); return $filter; }
/** * @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; }); } }
$ext = $assets[2]; if (in_array($type, ['less', 'scss', 'coffee'])) { array_push($filters, $type); } if ($ext == 'js') { $type = 'text/javascript; charset=UTF-8'; array_push($filters, '?js_min'); } elseif ($ext == 'css') { $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());
public function getNames() { return array_unique(array_merge(array_keys($this->mappings), parent::getNames())); }
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 */ }
/** * Decode the filters names, and initialize the Assetic FilterManager * * @param FilterManager $filterManager the Assetic filter manager * @param string $filters a comma separated list of filter names * @throws \InvalidArgumentException if a wrong filter is passed * @return array an array of filter names */ protected function decodeAsseticFilters(FilterManager $filterManager, $filters) { if (!empty($filters)) { $filter_list = explode(',', $filters); foreach ($filter_list as $filter_name) { $filter_name = trim($filter_name); foreach ($this->assetFilters as $filterIdentifier => $filterInstance) { if ($filterIdentifier == $filter_name) { $filterManager->set($filterIdentifier, $filterInstance); // No, goto is not evil. goto filterFound; } } throw new \InvalidArgumentException("Unsupported Assetic filter: '{$filter_name}'"); break; filterFound: } } else { $filter_list = array(); } return $filter_list; }
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; }); } }
/** * Decode the filters names, and initialize the Assetic FilterManager * * @param FilterManager $filterManager the Assetic filter manager * @param string $filters a comma separated list of filter names * @throws \InvalidArgumentException if a wrong filter is passed * @return array an array of filter names */ protected function decodeAsseticFilters(FilterManager $filterManager, $filters) { if (!empty($filters)) { $filter_list = explode(',', $filters); foreach ($filter_list as $filter_name) { $filter_name = trim($filter_name); switch ($filter_name) { case 'less': $filterManager->set('less', new Filter\LessphpFilter()); break; case 'sass': $filterManager->set('sass', new Filter\Sass\SassFilter()); break; case 'cssembed': $filterManager->set('cssembed', new Filter\PhpCssEmbedFilter()); break; case 'cssrewrite': $filterManager->set('cssrewrite', new Filter\CssRewriteFilter()); break; case 'cssimport': $filterManager->set('cssimport', new Filter\CssImportFilter()); break; case 'compass': $filterManager->set('compass', new Filter\CompassFilter()); break; default: throw new \InvalidArgumentException("Unsupported Assetic filter: '{$filter_name}'"); break; } } } else { $filter_list = array(); } return $filter_list; }
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config.php'; 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('.');
private function getCompilerPass($development = false) { $filterManager = new FilterManager(); $filterManager->set('mockup', new DummyFilter()); return new ProcessAssetsFiltersPass($filterManager, array('development' => $development, 'output_dir' => $this->outputDir)); }
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; } } }
protected function setupAssets() { // - Initialize `assets_urls`. $this->asset_urls = array('css' => array(), 'head_js' => array(), 'js' => array()); // - Alias. $conf = $this->asset_config; // - First, our `asset_manager`. $am = $this->asset_manager = new AssetManager(); // - Next, create our filter manager and all our named filters. Provide // configuration as needed. The manager doesn't need to be used by the // controller beyond the local scope. $fm = new FilterManager(); $fm->set('jsmin', new JsCompressorFilter()); $fm->set('cssmin', new CssCompressorFilter($conf['css_compressor'])); $fm->set('coffee', new CoffeeScriptFilter($conf['coffee'])); $fm->set('scss', new ScssFilter()); // - Also, create our `asset_writer` to write to disk. $aw = $this->asset_writer = new AssetWriter($this->paths['dist']); // - Also, create our `asset_cache` to work with instances of `AssetCache`. $ac = $this->asset_cache = new FilesystemCache($this->paths['cache']); // - Finally, create our `asset_factory` and provide the factory with our // managers, as well as a cache-buster if desired. $af = $this->asset_factory = new AssetFactory('', $this->debug); $af->setFilterManager($fm); $af->setAssetManager($am); if ($conf['cache_bust']) { $af->addWorker(new CacheBustingWorker()); } }
public function register(Application $app) { $app['assetic.options'] = []; /** * Asset Factory configuration happens here */ $app['assetic'] = $app->share(function () use($app) { $app['assetic.options'] = array_replace(array('debug' => false, 'formulae_cache_dir' => $app['paths.cache'] . '/assetic'), $app['assetic.options']); return $app['assetic.factory']; }); $app['paths.cache_assets'] = $app['paths.cache'] . '/assets'; /** * Asset manager * * @return \Assetic\AssetManager */ $app['assetic.asset_manager'] = $app->share(function () { return new AssetManager(); }); $app['assetic.filters.uglifyjs2'] = $app->share(function () { return new UglifyJs2Filter(); }); $app['assetic.filters.uglifycss'] = $app->share(function () { return new UglifyCssFilter(); }); $app['assetic.filters.compass'] = $app->share(function () use($app) { $filter = new CompassFilter(); $filter->setCacheLocation($app['paths.cache'] . '/compass'); $filter->addLoadPath($app['paths.sentient'] . '/Resource/scss'); return $filter; }); /** * Filter manager * * @return \Assetic\FilterManager */ $app['assetic.filter_manager'] = $app->share(function () use($app) { $manager = new FilterManager(); $manager->set('uglifyjs', $app['assetic.filters.uglifyjs2']); $manager->set('uglifycss', $app['assetic.filters.uglifycss']); $manager->set('compass', $app['assetic.filters.compass']); return $manager; }); /** * Asset writer, writes to the 'assetic.path_to_web' folder * * @return \Assetic\AssetWriter */ $app['assetic.asset_writer'] = $app->share(function () use($app) { return new AssetWriter($app['paths.cache_assets']); }); /** * Factory * * @return \Assetic\Factory\AssetFactory */ $app['assetic.factory'] = $app->share(function () use($app) { $factory = new AssetFactory($app['paths.resources'], false); $factory->setAssetManager($app['assetic.asset_manager']); $factory->setFilterManager($app['assetic.filter_manager']); $factory->addPath('sentient', $app['paths.templates'] . '/sentient'); $factory->addPath('sentient', $app['paths.sentient'] . '/Resource'); foreach ($app->getPluginNames() as $name) { $factory->addPath($name, $app['paths.resources'] . '/plugin/' . $name); $factory->addPath($name, $app->getPlugin($name)->getPath() . '/Resource'); } return $factory; }); /** * Asset controllers */ $app['assets.controllers'] = $app->share(function () use($app) { $controllers = $app['controllers_factory']; $controllers->match('/{filename}', function (Request $request) use($app) { return new AssetResponse($request->get('asset'), $app['assetic.asset_writer'], $app['paths.cache_assets']); })->assert('filename', '.+')->beforeMatch(function (array $attrs) use($app) { // @todo: A better way than looping through all loaded assets foreach ($app['assetic.asset_manager']->getNames() as $name) { $asset = $app['assetic.asset_manager']->get($name); if ($asset->getTargetPath() === $attrs['filename']) { $attrs['asset'] = $asset; return $attrs; } } return false; })->bind('asset'); return $controllers; }); $app['assets.register_js'] = $app->protect(function ($name, $scripts) use($app) { $asset = $app['assetic.factory']->createAsset((array) $scripts, ['uglifyjs'], ['output' => 'js/' . $name . '.js']); $app['assetic.asset_manager']->set('js_' . str_replace('/', '_', $name), $asset); return $asset; }); $app['assets.register_scss'] = $app->protect(function ($name, $stylesheets) use($app) { $asset = $app['assetic.factory']->createAsset((array) $stylesheets, ['compass', 'uglifycss'], ['output' => 'css/' . $name . '.css']); $app['assetic.asset_manager']->set('css_' . str_replace('/', '_', $name), $asset); return $asset; }); $app['asset_helper'] = $app->share(function () use($app) { return new AssetHelper($app['assetic.asset_manager'], $app['url_generator']); }); $app['twig'] = $app->share($app->extend('twig', function (\Twig_Environment $twig) use($app) { $twig->addExtension(new TwigAssetExtension($app['asset_helper'])); return $twig; })); $app['filesystem_controllers_factory'] = $app->protect(function ($basePath, $routeName = null) use($app) { $controllers = $app['controllers_factory']; $route = $controllers->match('/{filename}', function (Request $request) { $file = new FilesystemFile($request->get('path')); return new FileResponse($file); })->beforeMatch(function (array $attrs) use($basePath) { if (false !== strpos($attrs['filename'], '..')) { return false; } $attrs['path'] = $basePath . '/' . $attrs['filename']; if (!is_file($attrs['path'])) { return false; } return $attrs; })->assert('filename', '.+'); if ($routeName !== null) { $route->bind($routeName); } return $controllers; }); $app->mount('/assets', $app['assets.controllers']); }
/** * Creates the filter manager from the config file's filter array. * * @return FilterManager */ protected function createFilterManager() { $manager = new FilterManager(); $filters = Config::get($this->namespace . '::filters', array()); foreach ($filters as $name => $filter) { $manager->set($name, $this->createFilter($filter)); } return $this->filters = $manager; }
/** * 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'); }
/** * 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; } }
<?php /** * This script dumps assetic files */ require dirname(__FILE__) . "/../essentials.php"; use Assetic\AssetWriter; use Assetic\AssetManager; use Assetic\Factory\AssetFactory; use Assetic\FilterManager; use Assetic\Filter\UglifyCssFilter; $factory = new AssetFactory(PATH_APP . "/assets"); if (!MAIN_SERVER) { $factory->setDebug(true); } $am = new AssetManager(); $factory->setAssetManager($am); $fm = new FilterManager(); $fm->set('uglifycss', new UglifyCssFilter('/usr/local/bin/uglifycss')); $factory->setFilterManager($fm); $am->set('login', $factory->createAsset(array(PATH_APP . "/assets/css/logginn.css"), array('?uglifycss'), array('name' => 'login', 'output' => 'css/*'))); $am->set('default', $factory->createAsset(array(PATH_APP . "/assets/css/default/*.css"), array('?uglifycss'), array('name' => 'default', 'output' => 'css/*'))); $am->set('guest', $factory->createAsset(array(PATH_APP . "/assets/css/guest.css"), array('?uglifycss'), array('name' => 'guest', 'output' => 'css/*'))); $am->set('node', $factory->createAsset(array(PATH_APP . "/assets/css/node.css"), array('?uglifycss'), array('name' => 'node', 'output' => 'css/*'))); $am->set('doc', $factory->createAsset(array(PATH_APP . "/assets/css/doc.css"), array('?uglifycss'), array('name' => 'doc', 'output' => 'css/*'))); $writer = new AssetWriter(PATH_PUBLIC . "/assets"); $writer->writeManagerAssets($am);
/** * 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; } } }