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 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; }
/** * getUrlToAssets * * Create an asset file from a list of assets * * @param string $type type of asset, css or js * @param array $assets list of source files to process * @param string|array $filters either a comma separated list of known namsed filters * or an array of named filters and/or filter object * @param string $target target path, will default to assets directory * * @return string URL to asset file */ public function getUrlToAssets($type, $assets, $filters = 'default', $target = null) { if (is_scalar($assets)) { $assets = array($assets); // just a single path name } if ($filters == 'default') { if (isset($this->default_filters[$type])) { $filters = $this->default_filters[$type]; } else { $filters = ''; } } if (!is_array($filters)) { if (empty($filters)) { $filters = array(); } else { $filters = explode(',', str_replace(' ', '', $filters)); } } if (isset($this->default_output[$type])) { $output = $this->default_output[$type]; } else { $output = ''; } $xoops = \Xoops::getInstance(); if (isset($target)) { $target_path = $target; } else { $target_path = $xoops->path('assets'); } try { $am = $this->assetManager; $fm = new FilterManager(); foreach ($filters as $filter) { if (is_object($filter) && $filter instanceof $this->filterInterface) { $filterArray[] = $filter; } else { switch (ltrim($filter, '?')) { case 'cssembed': $fm->set('cssembed', new Filter\PhpCssEmbedFilter()); break; case 'cssmin': $fm->set('cssmin', new Filter\CssMinFilter()); break; case 'cssimport': $fm->set('cssimport', new Filter\CssImportFilter()); break; case 'cssrewrite': $fm->set('cssrewrite', new Filter\CssRewriteFilter()); break; case 'lessphp': $fm->set('lessphp', new Filter\LessphpFilter()); break; case 'scssphp': $fm->set('scssphp', new Filter\ScssphpFilter()); break; case 'jsmin': $fm->set('jsmin', new Filter\JSMinFilter()); break; default: throw new \Exception(sprintf('%s filter not implemented.', $filter)); break; } } } // Factory setup $factory = new AssetFactory($target_path); $factory->setAssetManager($am); $factory->setFilterManager($fm); $factory->setDefaultOutput($output); $factory->setDebug($this->debug); $factory->addWorker(new CacheBustingWorker()); // Prepare the assets writer $writer = new AssetWriter($target_path); // Translate asset paths, remove duplicates $translated_assets = array(); foreach ($assets as $k => $v) { // translate path if not a reference or absolute path if (0 == preg_match("/^\\/|^\\\\|^[a-zA-Z]:|^@/", $v)) { $v = $xoops->path($v); } if (!in_array($v, $translated_assets)) { $translated_assets[] = $v; } } // Create the asset $asset = $factory->createAsset($translated_assets, $filters); $asset_path = $asset->getTargetPath(); if (!is_readable($target_path . $asset_path)) { $xoops->events()->triggerEvent('debug.timer.start', array('writeAsset', $asset_path)); $oldumask = umask(02); $writer->writeAsset($asset); umask($oldumask); $xoops->events()->triggerEvent('debug.timer.stop', 'writeAsset'); } return $xoops->url('assets/' . $asset_path); } catch (\Exception $e) { $xoops->events()->triggerEvent('core.exception', $e); return null; } }
function smarty_block_assetic($params, $content, $template, &$repeat) { // In debug mode, we have to be able to loop a certain number of times, so we use a static counter static $count; static $assetsUrls; $realpath = realpath($params['config_path']); $root = mb_substr($realpath, 0, mb_strlen($realpath) - mb_strlen($params['config_path'])); // Read config file if (isset($params['config_path'])) { $base_path = $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 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(); $cssEmbedFilter = new Filter\CssEmbedFilter($root . $config->cssembed_path, $config->java_path); $cssEmbedFilter->setRoot($root); $fm->set('yui_js', new Filter\Yui\JsCompressorFilter($root . $config->yuicompressor_path, $config->java_path)); $fm->set('yui_css', new Filter\Yui\CssCompressorFilter($root . $config->yuicompressor_path, $config->java_path)); $fm->set('less', new Filter\LessphpFilter()); $fm->set('sass', new Filter\Sass\SassFilter()); $fm->set('cssembed', $cssEmbedFilter); $fm->set('cssabsolute', new Filter\CssAbsoluteFilter($config->site_url)); $fm->set('closure_api', new Filter\GoogleClosure\CompilerApiFilter()); $fm->set('closure_jar', new Filter\GoogleClosure\CompilerJarFilter($root . $config->closurejar_path, $config->java_path)); // Factory setup $factory = new AssetFactory($root); $factory->setAssetManager($am); $factory->setFilterManager($fm); $factory->setDefaultOutput('assetic/*.' . $params['output']); $factory->setDebug($params['debug']); $factory->addWorker(new CacheBustingWorker(CacheBustingWorker::STRATEGY_MODIFICATION)); 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'], '/' . $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; } } }
/** * Adds a factory worker. * * @param WorkerInterface $worker A worker */ public function addWorker(WorkerInterface $worker) { $this->assetFactory->addWorker($worker); }
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 */ }
/** * Build styles collection add filter return link to web recource * * @param array $assets file collection * @param string $key collection name * @param string $path path to assets recources * @param string $web path to web resource */ public function styleAssets($collection, $key, $path, $web) { if (true === $collection['debug']) { $this->debugWriteAssets(CON_ROOT_PATH, DOCUMENT_ROOT, $web, $collection); return true; } $am = $this->setAssetsCollection($collection['assets'], $key, $path); $this->fm = null; $factory = new AssetFactory(DOCUMENT_ROOT . $web, $collection['debug']); $factory->setAssetManager($am); $filters = array(); if (false === $collection['debug']) { if (isset($collection['includes'])) { $this->includeResources($collection['includes']); } if (isset($collection['filters'])) { foreach ($collection['filters'] as $alias => $filter) { $filters[] = '?' . $alias; $this->getFm()->set($alias, new $filter()); } $factory->setFilterManager($this->getFm()); $factory->addWorker(new CacheBustingWorker()); } } $css = $factory->createAsset(array('@' . $key), $filters); $css->setTargetPath($key . '.css'); $this->writeAssets($css, self::ASSETS_LASTMODIFIED . $key, DOCUMENT_ROOT . $web, '/' . $key . '.css'); $this->setStylesheets($this->linkStylesheet($web . '/' . $key . '.css', $collection['attr'])); return true; }
/** * Register the service provider. * * @return void */ public function register() { $app = $this->app; /** * Asset Factory configuration happens here */ $app['assetic'] = $app->share(function () use($app) { $app['assetic.path_to_web'] = $app['config']->get('laravel-assetic::config.path_to_web'); if ($app['config']->has('laravel-assetic::config.path_to_source')) { $app['assetic.path_to_source'] = $app['config']->get('laravel-assetic::config.path_to_source'); } $app['assetic.options'] = $app['config']->get('laravel-assetic::config.options'); // initializing lazy asset manager if (isset($app['assetic.formulae']) && !is_array($app['assetic.formulae']) && !empty($app['assetic.formulae'])) { $app['assetic.lazy_asset_manager']; } return $app['assetic.factory']; }); /** * Factory * * @return \Assetic\Factory\AssetFactory */ $app['assetic.factory'] = $app->share(function () use($app) { $root = isset($app['assetic.path_to_source']) ? $app['assetic.path_to_source'] : $app['assetic.path_to_web']; $factory = new AssetFactory($root, $app['assetic.options']['debug']); $factory->setAssetManager($app['assetic.asset_manager']); $factory->setFilterManager($app['assetic.filter_manager']); if ($app['config']->get('laravel-assetic::config.cachebusting') and !$app['assetic.options']['debug']) { $factory->addWorker(new CacheBustingWorker()); } return $factory; }); /** * Asset writer, writes to the 'assetic.path_to_web' folder * * @return \Assetic\AssetWriter */ $app['assetic.asset_writer'] = $app->share(function () use($app) { return new CheckedAssetWriter($app['assetic.path_to_web']); }); /** * Asset manager * * @return \Assetic\AssetManager */ $app['assetic.asset_manager'] = $app->share(function () use($app) { $am = new AssetManager(); if ($app['config']->has('laravel-assetic::config.asset_manager')) { $callback = $app['config']->get('laravel-assetic::config.asset_manager'); if (is_callable($callback)) { $callback($am); } } return $am; }); /** * Filter manager * * @return \Assetic\FilterManager */ $app['assetic.filter_manager'] = $app->share(function () use($app) { $fm = new FilterManager(); if ($app['config']->has('laravel-assetic::config.filter_manager')) { $callback = $app['config']->get('laravel-assetic::config.filter_manager'); if (is_callable($callback)) { $callback($fm); } } return $fm; }); /** * Lazy asset manager for loading assets from $app['assetic.formulae'] * (will be later maybe removed) */ $app['assetic.lazy_asset_manager'] = $app->share(function () use($app) { $formulae = isset($app['assetic.formulae']) ? $app['assetic.formulae'] : array(); $options = $app['assetic.options']; $lazy = new LazyAssetmanager($app['assetic.factory']); if (empty($formulae)) { return $lazy; } foreach ($formulae as $name => $formula) { $lazy->setFormula($name, $formula); } if ($options['formulae_cache_dir'] !== null && $options['debug'] !== true) { foreach ($lazy->getNames() as $name) { $lazy->set($name, new AssetCache($lazy->get($name), new FilesystemCache($options['formulae_cache_dir']))); } } return $lazy; }); $app['assetic.dumper'] = $app->share(function () use($app) { return new Dumper($app['assetic.asset_manager'], $app['assetic.lazy_asset_manager'], $app['assetic.asset_writer'], $app['view']->getFinder()); }); $app['command.assetic.build'] = $app->share(function ($app) { return new Console\AsseticBuildCommand(); }); $this->commands('command.assetic.build'); }