/** * @param array $options * @param string $name * @param Factory\AssetFactory $factory * * @return void */ public function prepareCollection($options, $name, Factory\AssetFactory $factory) { $assets = isset($options['assets']) ? $options['assets'] : []; $filters = isset($options['filters']) ? $options['filters'] : []; $options = isset($options['options']) ? $options['options'] : []; $options['output'] = isset($options['output']) ? $options['output'] : $name; $moveRaw = isset($options['move_raw']) && $options['move_raw']; $targetPath = !empty($options['targetPath']) ? $options['targetPath'] : ''; if (substr($targetPath, -1) != DIRECTORY_SEPARATOR) { $targetPath .= DIRECTORY_SEPARATOR; } $filters = $this->initFilters($filters); $asset = $factory->createAsset($assets, $filters, $options); // Allow to move all files 1:1 to new directory // its particularly useful when this assets are i.e. images. if ($moveRaw) { if (isset($options['disable_source_path'])) { $this->moveRaw($asset, $targetPath, $factory, $options['disable_source_path']); } else { $this->moveRaw($asset, $targetPath, $factory); } } else { $asset = $this->cacheAsset($asset); $this->assetManager->set($name, $asset); // Save asset on disk $this->writeAsset($asset, $factory); } }
protected function createAssetManager() { $asset = new FileAsset(__DIR__ . '/../../../tests/test.css'); $asset->setTargetPath('css/test.css'); $assetManager = new AssetManager(); $assetManager->set('test_css', $asset); return $assetManager; }
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(); }
public function build($collection_name) { $build_path_setting = Config::get("assetie::build_path"); $build_directory = public_path() . DIRECTORY_SEPARATOR . $build_path_setting; /** * the designated name of the build, i.e. base_123.js */ $build_name = $collection_name . "." . $this->buildExtension; $build_file = $build_directory . DIRECTORY_SEPARATOR . $build_name; $buildExists = file_exists($build_file); $build_url = URL::asset($build_path_setting . DIRECTORY_SEPARATOR . $build_name); $debugMode = Config::get("app.debug"); if (!$buildExists || $debugMode) { $files = \Collection::dump($collection_name)[$this->group]; $collection_hash = sha1(serialize($files)); $hash_in_cache = Cache::get("collection_" . $this->group . "_" . $collection_name); $collectionChanged = $collection_hash != $hash_in_cache; $src_dir = app_path() . DIRECTORY_SEPARATOR . Config::get("assetie::directories." . $this->group) . DIRECTORY_SEPARATOR; $forceRebuild = false; if ($collectionChanged) { $forceRebuild = true; } else { if ($buildExists) { /** * only recompile if no compiled build exists or when in debug mode and * build's source files or collections.php has been changed */ $forceRebuild = $this->checkModification($build_file, $files, $src_dir); } } if (!$buildExists || $forceRebuild) { $am = new AssetManager(); $assets = []; foreach ($files as $file) { $filters = $this->getFilters($file); $assets[] = new FileAsset($src_dir . $file, $filters); } $collection = new AssetCollection($assets); // , $filters $collection->setTargetPath($build_name); $am->set('collection', $collection); $writer = new AssetWriter($build_directory); $writer->writeManagerAssets($am); } // Cache::forever("collection_" . $collection_name, $collection_hash); $cache_key = "collection_" . $this->group . "_" . $collection_name; if (Cache::has($cache_key) && $collectionChanged) { Cache::forget($cache_key); } if ($collectionChanged) { Cache::put($cache_key, $collection_hash, 60); // 1 hour } } return $build_url; }
public function testDontFailIfNoTargetPathForReferenceAndNoUrl() { $asset = new PuliStringAsset('/css/style.css', 'body { background: blue; }'); $asset->setTargetPath('/css/style.css'); $asset->load(); $asset2 = new PuliStringAsset('/images/bg.png', null); $this->am->set('asset2', $asset2); $this->filter->filterLoad($asset); $this->filter->filterDump($asset); }
public function code_mirror_get_css_theme($parameters) { $am = new AssetManager(); $am->set('theme', new FileAsset($parameters['theme'])); $am->get('theme'); #var_dump($am, $am->get('theme'), $am->getNames()); die; if (isset($parameters['theme']) and $theme = $this->assetManager->getTheme($parameters['theme'])) { return $theme; } return false; }
public function testTwo() { $uglify = new UglifyJs2Filter("/usr/bin/uglifyjs", "/usr/bin/node"); $uglify->setCompress(true); $uglify->setMangle(true); $uglify->setCompress(true); $am = new AssetManager(); $am->set("app", new AssetCollection(array(new GlobAsset(__DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "assets/src/*", array($uglify))))); echo $am->get("app")->dump(); echo PHP_EOL; }
/** * @param array $options * @param string $name * @param Factory\AssetFactory $factory * @return void */ public function prepareCollection($options, $name, Factory\AssetFactory $factory) { $assets = isset($options['assets']) ? $options['assets'] : array(); $filters = isset($options['filters']) ? $options['filters'] : $this->configuration->getDefault()['filters']; $options = isset($options['options']) ? $options['options'] : array(); $options['output'] = isset($options['output']) ? $options['output'] : $name; $moveRaw = isset($options['move_raw']) && $options['move_raw']; $filters = $this->initFilters($filters); $asset = $factory->createAsset($assets, $filters, $options); // Allow to move all files 1:1 to new directory // its particularly useful when this assets are i.e. images. if ($moveRaw) { $this->moveRaw($asset); } else { $asset = $this->cacheAsset($asset); $this->assetManager->set($name, $asset); } }
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); } }
/** * @param $fileName * @return AssetManager */ public static function parseFromYaml($fileName) { $data = Yaml::parse($fileName); $am = new AssetManager(); foreach ($data as $k => $v) { if (isset($v['assets'])) { $assets = []; foreach ((array) $v['assets'] as $asset) { $source = isset($asset['source']) ? $asset['source'] : null; $type = null; if (isset($asset['type']) && in_array($asset['type'], self::$typeMap)) { $type = self::$typeMap[$asset['type']]; } else { $type = self::$typeMap['glob']; } $assets[] = new $type($source); } $assetCollection = new AssetCollection($assets); $am->set($k, $assetCollection); } } return $am; }
/** * Dump all assets */ public function all() { foreach ($this->getAssetsXMLFiles() as $path => $XMLFile) { $this->out(''); $this->out(sprintf('<info>Start dumping "%s" assets:</info>', $path)); $xml = new Xml(); $domDocument = $xml->build($XMLFile, ['return' => 'domdocument']); $xpath = new DOMXPath($domDocument); $assetsNodeList = $xpath->query('/assetic/assets/asset'); $assetManager = new AssetManager(); /** @var $assetNode DOMElement */ foreach ($assetsNodeList as $assetNode) { $source = strtr($assetNode->getElementsByTagName('source')->item(0)->nodeValue, $this->paths); $destination = strtr($assetNode->getElementsByTagName('destination')->item(0)->nodeValue, $this->paths); $assetManager->set($assetNode->getAttribute('name'), $fileAsset = new FileAsset($source)); $fileAsset->setTargetPath($destination); $this->out($source . ' <info> >>> </info> ' . WWW_ROOT . $destination); } $assetWriter = new AssetWriter(WWW_ROOT); $assetWriter->writeManagerAssets($assetManager); $this->dumpStaticFiles($domDocument); $this->out('<info>End</info>'); } }
public function testCreateAssetReference() { $reference = $this->getMock('Assetic\\Asset\\AssetInterface'); $am = new AssetManager(); $am->set('reference', $reference); $this->factory->setAssetManager($am); $asset = $this->factory->createAsset(array('@reference')); $asset->setCurrentDir('/webmozart/puli'); $assets = iterator_to_array($asset); /** @var AssetReference[] $assets */ $this->assertCount(1, $assets); $this->assertInstanceOf('Assetic\\Asset\\AssetReference', $assets[0]); }
/** * 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'); }
/** * Process files from specified group(s) with Assetic library * https://github.com/kriswallsmith/assetic * * @param string|int $group * * @return string */ public function minifyFiles($group) { $output = ''; $filenames = array(); $groupIds = array(); // Check if multiple groups are defined in group parameter // If so, combine all the files from specified groups $allGroups = explode(',', $group); foreach ($allGroups as $group) { $group = $this->getGroupId($group); $groupIds[] = $group; $filenames = array_merge($filenames, $this->getGroupFilenames($group)); } // Setting group key which is used for filename and logging if (count($groupIds) > 1) { $group = implode('_', $groupIds); } if (count($filenames)) { require_once $this->options['corePath'] . 'assetic/vendor/autoload.php'; $minifiedFiles = array(); $am = new AssetManager(); $writer = new AssetWriter($this->options['rootPath']); $allFiles = array(); $fileDates = array(); $updatedFiles = 0; $skipMinification = 0; foreach ($filenames as $file) { $filePath = $this->options['rootPath'] . $file; $fileExt = pathinfo($filePath, PATHINFO_EXTENSION); if (!$this->validateFile($filePath, $fileExt)) { // no valid files found in group (non-existent or not allowed extension) $this->log('File ' . $filePath . ' not valid.' . "\n\r", 'error'); continue; } else { $this->log('File ' . $filePath . ' successfully added to group.' . "\n\r"); } $fileFilter = array(); $minifyFilter = array(); if ($fileExt == 'js') { $minifyFilter = array(new JSMinFilter()); $filePrefix = 'scripts'; $fileSuffix = '.min.js'; } else { // if file is .scss, use the correct filter to parse scss to css if ($fileExt == 'scss') { $fileFilter = array(new ScssphpFilter()); } // if file is .less, use the correct filter to parse less to css if ($fileExt == 'less') { $fileFilter = array(new LessphpFilter()); } $minifyFilter = array(new CSSUriRewriteFilter(), new MinifyCssCompressorFilter()); $filePrefix = 'styles'; $fileSuffix = '.min.css'; } $fileDates[] = filemtime($filePath); $allFiles[] = new FileAsset($filePath, $fileFilter); } // endforeach $files if (count($fileDates) && count($allFiles)) { sort($fileDates); $lastEdited = end($fileDates); $minifyFilename = $filePrefix . '-' . $group . '-' . $lastEdited . $fileSuffix; // find the old minified files // if necessary, remove old and generate new, based on file modification time of minified file foreach (glob($this->options['cachePath'] . '/' . $filePrefix . '-' . $group . '-*' . $fileSuffix) as $current) { if (filemtime($current) > $lastEdited) { // current file is up to date $this->log('Minified file "' . basename($current) . '" up to date. Skipping group "' . $group . '" minification.' . "\n\r"); $minifyFilename = basename($current); $skip = 1; } else { unlink($current); $this->log('Removing current file ' . $current . "\n\r"); } } $updatedFiles++; $this->log("Writing " . $minifyFilename . "\n\r"); $collection = new AssetCollection($allFiles, $minifyFilter); $collection->setTargetPath($this->options['cacheUrl'] . '/' . $minifyFilename); $am->set($group, $collection); if ($updatedFiles > 0 && $skip == 0) { $writer->writeManagerAssets($am); } $output = $this->options['cacheUrl'] . '/' . $minifyFilename; } else { $this->log('No files parsed from group ' . $group . '. Check the log for more info.' . "\n\r", 'error'); } } else { // No files in specified group } return $output; }
use Assetic\Asset\FileAsset; use Assetic\Asset\GlobAsset; use Assetic\Asset\AssetCollection; use Assetic\AssetManager; use Assetic\Asset\AssetReference; use Assetic\Filter\JSMinPlusFilter; use Assetic\AssetWriter; use Assetic\Cache\FilesystemCache; use Assetic\Asset\AssetCache; // Define the locations for the asset and cache directories $assets = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'assets'; $cache = $assets . DIRECTORY_SEPARATOR . 'cache'; $am = new AssetManager(); // Create asset refrences to jQuery and all the other js files in the JS folder // Creating a refernce to jQuery will allow us to put it first in the file $am->set('jquery', new AssetCache(new FileAsset($assets . DIRECTORY_SEPARATOR . 'jquery' . DIRECTORY_SEPARATOR . 'jquery-1.11.1.min.js'), new FilesystemCache($cache))); $am->set('jquery_ui', new AssetCache(new FileAsset($assets . DIRECTORY_SEPARATOR . 'jquery' . DIRECTORY_SEPARATOR . 'jquery-ui-1.9.2.min.js'), new FilesystemCache($cache))); $am->set('otherjs', new AssetCache(new GlobAsset($assets . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . '*.js'), new FilesystemCache($cache))); //include guide.js if reffer is from guide.php //if (isset( $_SERVER['HTTP_REFERER'])) { // $lobjSplit = explode( '/', $_SERVER['HTTP_REFERER']); // if( strpos($lobjSplit[count($lobjSplit) - 1], 'guide.php') !== FALSE && $lobjSplit[count($lobjSplit) - 2] == 'guides' ) //{ $am->set('guidejs', new AssetCache(new GlobAsset($assets . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR . 'guides' . DIRECTORY_SEPARATOR . '*.js'), new FilesystemCache($cache))); // } //} else { } // Apply the JSMinPlus filter to all the files $jquery = new AssetCollection(array(new AssetReference($am, 'jquery'))); $jquery_ui = new AssetCollection(array(new AssetReference($am, 'jquery_ui'))); $other_js = $am->has('guidejs') ? new AssetCollection(array(new AssetReference($am, 'otherjs'), new AssetReference($am, 'guidejs'))) : new AssetCollection(array(new AssetReference($am, 'otherjs'))); // Place jQuery first in the final output
use Assetic\Asset\GlobAsset; use Assetic\Asset\AssetCollection; use Assetic\AssetManager; use Assetic\Asset\AssetReference; use Assetic\Filter\CSSMinFilter; use Assetic\AssetWriter; use Assetic\Cache\FilesystemCache; use Assetic\Asset\AssetCache; // Define the asset and cache directories $assets = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'assets'; $cache = $assets . DIRECTORY_SEPARATOR . 'cache'; // A new CSS file can be added by sticking it in the assets folder or in 3 steps you can add a file that needs to be called in a specific order. // Create references to specific files in the assest directory with the AssetManager $am = new AssetManager(); // Step 1. $am->set('pure', new AssetCache(new FileAsset($assets . '/css/shared/pure-min.css'), new FilesystemCache($cache))); $am->set('pure_grid', new AssetCache(new FileAsset($assets . '/css/shared/grids-responsive-min.css'), new FilesystemCache($cache))); $am->set('jqueryui', new AssetCache(new FileAsset($assets . '/css/shared/jquery-ui.css'), new FilesystemCache($cache))); $am->set('colorbox', new AssetCache(new FileAsset($assets . '/css/shared/colorbox.css'), new FilesystemCache($cache))); $am->set('admin_styles', new AssetCache(new FileAsset($assets . '/css/admin/admin_styles.css'), new FilesystemCache($cache))); $am->set('override', new AssetCache(new FileAsset($assets . '/css/admin/override.css'), new FilesystemCache($cache))); $am->set('font_awesome', new AssetCache(new FileAsset($assets . '/css/shared/font-awesome.min.css'), new FilesystemCache($cache))); // Glob all the rest of the CSS files together // $am->set('css', new AssetCache(new GlobAsset($assets . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . '*.css'), new FilesystemCache($cache))); // Step 2. // This is where the CSSMin filter will be applied eventually. $pure = new AssetCollection(array(new AssetReference($am, 'pure'))); $pure_grid = new AssetCollection(array(new AssetReference($am, 'pure_grid'))); $jqueryui = new AssetCollection(array(new AssetReference($am, 'jqueryui'))); $colorbox = new AssetCollection(array(new AssetReference($am, 'colorbox'))); $override = new AssetCollection(array(new AssetReference($am, 'override')));
/** * Add an asset reference to the asset manager * * @param string $name the name of the reference to be added * @param mixed $assets a string asset path, or an array of asset paths, * may include wildcard * @param string|array $filters either a comma separated list of known named filters * or an array of named filters and/or filter object * * @return boolean true if asset registers, false on error */ public function registerAssetReference($name, $assets, $filters = null) { $xoops = \Xoops::getInstance(); $assetArray = array(); $filterArray = array(); try { if (is_scalar($assets)) { $assets = array($assets); // just a single path name } foreach ($assets as $a) { // translate path if not a reference or absolute path if (substr_compare($a, '@', 0, 1) != 0 && substr_compare($a, '/', 0, 1) != 0) { $a = $xoops->path($a); } if (false === strpos($a, '*')) { $assetArray[] = new FileAsset($a); // single file } else { $assetArray[] = new GlobAsset($a); // wild card match } } if (!is_array($filters)) { if (empty($filters)) { $filters = array(); } else { $filters = explode(',', str_replace(' ', '', $filters)); } } foreach ($filters as $filter) { if (is_object($filter) && $filter instanceof $this->filterInterface) { $filterArray[] = $filter; } else { switch (ltrim($filter, '?')) { case 'cssembed': $filterArray[] = new Filter\PhpCssEmbedFilter(); break; case 'cssmin': $filterArray[] = new Filter\CssMinFilter(); break; case 'cssimport': $filterArray[] = new Filter\CssImportFilter(); break; case 'cssrewrite': $filterArray[] = new Filter\CssRewriteFilter(); break; case 'lessphp': $filterArray[] = new Filter\LessphpFilter(); break; case 'scssphp': $filterArray[] = new Filter\ScssphpFilter(); break; case 'jsmin': $filterArray[] = new Filter\JSMinFilter(); break; default: throw new \Exception(sprintf('%s filter not implemented.', $filter)); break; } } } $collection = new AssetCollection($assetArray, $filterArray); $this->assetManager->set($name, $collection); return true; } catch (\Exception $e) { $xoops->events()->triggerEvent('core.exception', $e); return false; } }
/** * Include and manage Assets into templates. * * Supported styles: * - CSS * - LESS via /vendor/leafo/LessphpFilter * - SCSS via /vendor/leafo/ScssphpFilter * * Supported scripts: * - JavaScript * - Coffee Script via Assetic\Filter\CoffeeScriptFilter * * @param array $options Assets source options. * @param Smarty_Internal_Template $template Smarty Template object. * * @uses Core\Config * @uses Core\Utils * @see Assetic * * @return string */ function smarty_function_assets(array $options, Smarty_Internal_Template $template) { $result = array(); if (isset($options['source'])) { $assetsPath = Core\Config()->paths('assets'); $optimization_enabled = Core\Config()->ASSETS['optimize']; $combination_enabled = Core\Config()->ASSETS['combine']; $caching_enabled = Core\Config()->ASSETS['cache']; $dist_path = $assetsPath['distribution']; $source_path = $assetsPath['source']; $dist_url = Core\Config()->urls('assets'); $media = isset($options['media']) ? $options['media'] : 'all'; $rel = isset($options['rel']) ? $options['rel'] : 'stylesheet'; $mimetype = isset($options['type']) ? $options['type'] : 'text/css'; $assets = is_array($options['source']) ? $options['source'] : array($options['source']); $assets_id = md5(implode(Core\Utils::arrayFlatten($assets))); $assets_to_process = array(); /* Format assets if needed */ if (!Core\Utils::arrayIsAssoc($options['source'])) { $formatted_assets = array(); foreach ($options['source'] as $file) { $file_extension = pathinfo($file, PATHINFO_EXTENSION); $formatted_assets[$file_extension][] = $file; $formatted_assets[$file_extension] = array_unique($formatted_assets[$file_extension]); } $assets = $formatted_assets; } if ($caching_enabled) { if ($combination_enabled) { if (array_intersect(array('css', 'less', 'scass'), array_keys($assets))) { $cached_asset = 'css' . DIRECTORY_SEPARATOR . $assets_id . '.css'; if (file_exists($dist_path . $cached_asset)) { $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset); $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media); } else { $assets_to_process = $assets; } } elseif (array_intersect(array('js'), array_keys($assets))) { $cached_asset = 'js' . DIRECTORY_SEPARATOR . $assets_id . '.js'; if (file_exists($dist_path . $cached_asset)) { $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset); $result[] = sprintf('<script src="%s"></script>', $dist_url . $target); } else { $assets_to_process = $assets; } } } else { foreach ($assets as $type => $files) { switch ($type) { case 'css': case 'less': case 'scass': foreach ($files as $file) { $filename = basename($file, '.css'); $filename = basename($filename, '.less'); $filename = basename($filename, '.scss'); $cached_asset = 'css' . DIRECTORY_SEPARATOR . $filename . '.css'; if (file_exists($dist_path . $cached_asset)) { $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset); $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media); } else { $assets_to_process[$type][] = $file; } } break; case 'js': case 'coffee': foreach ($files as $file) { $filename = basename($file, '.js'); $filename = basename($filename, '.coffee'); $cached_asset = 'js' . DIRECTORY_SEPARATOR . $filename . '.js'; if (file_exists($dist_path . $cached_asset)) { $target = str_replace(DIRECTORY_SEPARATOR, '/', $cached_asset); $result[] = sprintf('<script src="%s"></script>', $dist_url . $target); } else { $assets_to_process[$type][] = $file; } } break; } } } } if (!$caching_enabled || $assets_to_process) { $assets = $assets_to_process ? $assets_to_process : $assets; $writer = new AssetWriter($dist_path); $styles = new AssetCollection(array(), $optimization_enabled ? array(new CssMinFilter()) : array()); $scripts = new AssetCollection(array(), $optimization_enabled ? array(new JsMinFilter()) : array()); foreach ($assets as $type => $files) { switch ($type) { case 'js': foreach ($files as $file) { $scripts->add(new FileAsset($source_path . $file)); } break; case 'css': foreach ($files as $file) { $styles->add(new FileAsset($source_path . $file)); } break; case 'less': foreach ($files as $file) { $styles->add(new FileAsset($source_path . $file, array(new LessphpFilter()))); } break; case 'scss': foreach ($files as $file) { $styles->add(new FileAsset($source_path . $file, array(new ScssphpFilter()))); } break; case 'coffee': foreach ($files as $file) { $scripts->add(new FileAsset($source_path . $file), array(new CoffeeScriptFilter())); } break; } } if ($combination_enabled) { if ($styles->all()) { $am = new AssetManager($dist_path); $styles->setTargetPath('css' . DIRECTORY_SEPARATOR . $assets_id . '.css'); $am->set('styles', $styles); $writer->writeManagerAssets($am); $target = str_replace(DIRECTORY_SEPARATOR, '/', $styles->getTargetPath()); $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media); } if ($scripts->all()) { $am = new AssetManager($dist_path); $scripts->setTargetPath('js' . DIRECTORY_SEPARATOR . $assets_id . '.js'); $am->set('scripts', $scripts); $writer->writeManagerAssets($am); $target = str_replace(DIRECTORY_SEPARATOR, '/', $scripts->getTargetPath()); $result[] = sprintf('<script src="%s"></script>', $dist_url . $target); } } else { foreach ($styles->all() as $style) { $filename = basename($style->getSourcePath(), '.css'); $filename = basename($filename, '.less'); $filename = basename($filename, '.scss'); $style->setTargetPath('css' . DIRECTORY_SEPARATOR . $filename . '.css'); $writer->writeAsset($style); $target = str_replace(DIRECTORY_SEPARATOR, '/', $style->getTargetPath()); $result[] = sprintf('<link href="%s" rel="%s" type="%s" media="%s" />', $dist_url . $target, $rel, $mimetype, $media); } foreach ($scripts->all() as $script) { $filename = basename($script->getSourcePath(), '.js'); $filename = basename($filename, '.coffee'); $script->setTargetPath('js' . DIRECTORY_SEPARATOR . $filename . '.js'); $writer->writeAsset($script); $target = str_replace(DIRECTORY_SEPARATOR, '/', $script->getTargetPath()); $result[] = sprintf('<script src="%s"></script>', $dist_url . $target); } } } } return $result ? implode("\n\t", $result) : ''; }
if (APP_WEB_SITE_DIR) { $writer = new AssetWriter(APP_WEB_SITE_DIR . '/theme/default/img/'); $writer->writeManagerAssets($am); } if (APP_WEB_SINGLE_SITE_DIR) { $writer = new AssetWriter(APP_WEB_SINGLE_SITE_DIR . '/theme/default/img/'); $writer->writeManagerAssets($am); } } # Sysadmin if (APP_WEB_SYSADMIN_DIR || APP_WEB_SINGLE_SITE_DIR || APP_WEB_INDEX_DIR) { $am = new AssetManager(); foreach ($imgFiles['sysadmin'] as $nameonly => $filename) { $fa = new FileAsset($filename, $imgFilters); $fa->setTargetPath($nameonly); $am->set(str_replace('.', '_', $nameonly), $fa); } if (APP_WEB_SYSADMIN_DIR) { $writer = new AssetWriter(APP_WEB_SYSADMIN_DIR . '/theme/default/imgsysadmin/'); $writer->writeManagerAssets($am); } if (APP_WEB_SINGLE_SITE_DIR) { $writer = new AssetWriter(APP_WEB_SINGLE_SITE_DIR . '/theme/default/imgsysadmin/'); $writer->writeManagerAssets($am); } if (APP_WEB_INDEX_DIR) { $writer = new AssetWriter(APP_WEB_INDEX_DIR . '/theme/default/imgsysadmin/'); $writer->writeManagerAssets($am); } } }
protected function createAssetManager() { $manager = new AssetManager(); $config = Config::get($this->namespace . '::assets', array()); foreach ($config as $key => $refs) { if (!is_array($refs)) { $refs = array($refs); } $asset = array(); foreach ($refs as $ref) { $asset[] = $this->parseAssetDefinition($ref); } if (count($asset) > 0) { $manager->set($key, count($asset) > 1 ? new AssetCollection($asset) : $asset[0]); } } return $this->assets = $manager; }
/** * * @param array $assets * @param string $key * @param string $path * @return \Assetic\AssetManager $am Assetic\AssetManager */ protected function setAssetsCollection($assets, $key, $path) { $am = new AssetManager(); $collection = array(); foreach ($assets as $file) { $collection[] = new FileAsset(CON_ROOT_PATH . $path . $file); } $am->set($key, new AssetCollection($collection)); return $am; }
protected function assetic($files, $type) { $urls = []; foreach ($files as $key => $file) { $assetType = $this->parseInput($file); if ($assetType == 'http') { $urls[] = $file; unset($files[$key]); } } if (empty($files)) { return $urls; } $name = md5(implode(',', $files)) . '.' . $type; $cachePath = $this->config['paths']['pcache']; $cache = $this->config['paths']['cache']; $cachedFile = $this->config['locations']['cache'] . $name; $file = $cachePath . $name; $debug = $this->config['debug']; if (!$debug && file_exists($file)) { $urls[] = $cachedFile; return $urls; } $aw = new AssetWriter($cachePath); $am = new AssetManager(); // Create the collection $collection = new AssetCollection(); // Create the cache $cache = new FilesystemCache($cache); foreach ($files as $file) { $assetType = $this->parseInput($file); // Create the asset if ($assetType == 'file') { $asset = new FileAsset($file); } elseif ($assetType == 'glob') { $asset = new GlobAsset($file); } elseif ($assetType == 'http') { $asset = new HttpAsset($file); } elseif ($assetType == 'reference') { $asset = new AssetReference($am, substr($file, 1)); } $filters = $this->getFilters($file); if (!empty($filters)) { foreach ($filters as $filter) { // Add the filter $asset->ensureFilter($filter); } } // Cache the asset so we don't have to reapply filters on future page loads $cachedAsset = new AssetCache($asset, $cache); // Add the cached asset to the collection $collection->add($cachedAsset); } if (!file_exists($file) || $collection->getLastModified() > filemtime($file)) { $am->set($type, $collection); $am->get($type)->setTargetPath($name); $aw->writeManagerAssets($am); } $urls[] = $cachedFile; return $urls; }
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; }); } }
<?php //if(PHP_SAPI !== 'cli') die('Server side only.'); 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));
public function get($name) { if (!$this->loaded) { $this->load(); } if (!parent::has($name) && isset($this->formulae[$name])) { list($inputs, $filters, $options) = $this->formulae[$name]; $options['name'] = $name; parent::set($name, $this->factory->createAsset($inputs, $filters, $options)); } return parent::get($name); }
/** * @param string $name * @param AssetFactory $factory * @param null $details * * @return string */ public function asset($name = null, AssetFactoryInterface $factory = null, &$details = null) { /* * Get the necessary configuration from the config file. */ // if (is_null($name)) { // $root = $this->config->get("larattic::root"); // $assets = Collection::make($this->config->get("larattic::assets")); // $assetCache = Collection::make($this->config->get("larattic::assetCache")); // $filters = Collection::make($this->config->get("larattic::filters")); // $workers = Collection::make($this->config->get("larattic::workers")); // $options = Collection::make($this->config->get("larattic::options")); // $public_uri = $this->config->get("larattic::public_uri"); // } else { $root = $this->config->get("larattic::{$name}.root"); $assets = Collection::make($this->config->get("larattic::{$name}.assets")); $assetCache = Collection::make($this->config->get("larattic::{$name}.assetCache")); $filters = Collection::make($this->config->get("larattic::{$name}.filters")); $workers = Collection::make($this->config->get("larattic::{$name}.workers")); $options = Collection::make($this->config->get("larattic::{$name}.options")); $public_uri = $this->config->get("larattic::{$name}.public_uri"); // } $details['root'] = $root; $details['public_uri'] = $public_uri; /* * Check if a named lock file exists, if it does, skip the creation and return directly. */ if ($this->filesystem->exists($root . DIRECTORY_SEPARATOR . "{$name}.lock")) { $filepath = readlink($root . DIRECTORY_SEPARATOR . "{$name}.lock"); if ($this->filesystem->exists($filepath)) { $details['lock'] = $root . DIRECTORY_SEPARATOR . "{$name}.lock"; return asset($public_uri . basename($filepath)); } } //elseif (($filepath = \Cache::get("{$name}.manifest"))) { // if (file_exists($filepath)) { // return asset($public_uri.basename($filepath)); // } // } /* * If an AssetFactory was not injected, instantiate one. */ if (is_null($factory)) { $factory = $this->container->make('Assetic\\Factory\\AssetFactory', [$root]); } /* * If we want to use the assetCache, instantiate all caches and return the assetReferences. */ if ($assetCache) { $assets = $assets->map(function ($asset, $name) use(&$factory, &$assetCache) { $this->assetManager->set($name, $this->container->make($assetCache->get('assetcache'), [$factory->createAsset($asset), $this->container->make($assetCache->get('cache'), [$assetCache->get('storage_path')])])); return "@{$name}"; }); } /* * Instantiate all the filters. */ $filters->map(function ($filter, $name) use(&$factory) { $this->filterManager->set($name, $this->container->make($filter)); }); /* * Set the assetManager and filterManager on the factory. */ $factory->setAssetManager($this->assetManager); $factory->setFilterManager($this->filterManager); /* * Add workers if needed. */ $workers->each(function ($worker) use(&$factory) { $factory->addWorker($this->container->make($worker)); }); /* * Add the default CacheBustingWorker */ $factory->addWorker($this->container->make('Assetic\\Factory\\Worker\\CacheBustingWorker')); /* * Create all the assets with the createAsset method of the factory. */ $css = $factory->createAsset($assets->toArray(), $filters->keys(), $options->toArray()); $filepath = $css->getTargetPath(); $details['filepath'] = $filepath; /* * If the file that was returned by the factory already exists, we don't need to write it again. * CacheBustingWorker makes sure the filename is regenerated when the file changes. */ if (!file_exists($root . DIRECTORY_SEPARATOR . $filepath)) { $cssWriter = $this->container->make('Zae\\Larattic\\Adapters\\AsseticAssetWriterAdapter', [$root]); $cssWriter->writeAsset($css); // \Cache::put("{$name}.manifest", $root.DIRECTORY_SEPARATOR.$filepath, 60); } return asset($public_uri . basename($filepath)); }