Esempio n. 1
0
 public function writeAssets()
 {
     $storage = $this->app['config']->get('theme::config.storage_folder');
     $writer = new AssetWriter(app_path() . '/' . $storage);
     $writer->writeManagerAssets($this->am);
     return $this;
 }
Esempio n. 2
0
 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 dumpAction()
 {
     $appConfig = $this->locate('Configuration');
     $writer = new AssetWriter($appConfig['zf2_assetic']['assetDumpPath']);
     $writer->writeManagerAssets($this->assetManager);
     $httpRouter = $this->locate('httpRouter');
     $assetManifest = array('assets' => array());
     foreach ($this->assetManager->getNames() as $name) {
         $asset = $this->assetManager->get($name);
         $url = $httpRouter->assemble(array('resourcePath' => $asset->getTargetPath()), array('name' => $appConfig['zf2_assetic']['controllerRouteName']));
         $assetManifest['assets'][$name] = $url;
     }
     $manifestDir = dirname($appConfig['zf2_assetic']['assetManifestPath']);
     if (!is_dir($manifestDir)) {
         mkdir($manifestDir, 755, true);
     }
     if (false === file_put_contents($appConfig['zf2_assetic']['assetManifestPath'], json_encode($assetManifest))) {
         throw new \Exception('Unable to write asset manifest');
     }
 }
Esempio n. 4
0
 /**
  * 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>');
     }
 }
Esempio n. 5
0
 /**
  * Build the site
  */
 public function build()
 {
     $that = $this;
     $this->root = realpath($this->root);
     // First, clean up non-existent files
     if (file_exists($this->outputDir)) {
         $deleteFinder = new Finder();
         $deleteFinder->in($this->outputDir)->filter(function (SplFileInfo $dstFile) {
             // Filter out entries where the source does not exist, or is not the same type
             $srcFile = new SplFileInfo("{$this->root}/{$dstFile->getRelativePathname()}", $dstFile->getRelativePath(), $dstFile->getRelativePathname());
             $old = $dstFile->isDir() && !$srcFile->isDir() || $dstFile->isFile() && !$srcFile->isFile();
             $event = new OldFileEvent($this, $srcFile, $dstFile, $old);
             $this->dispatcher->dispatch(BrancherEvents::OLDFILE, $event);
             return $event->isOld();
         });
         $this->filesystem->remove($deleteFinder);
     }
     // Find all files in root directory
     $renderFinder = new Finder();
     $renderFinder->files()->in(realpath($this->root))->ignoreDotFiles(false);
     array_map([$renderFinder, 'notPath'], array_filter(array_map(function ($exclude) use($that) {
         return $this->filesystem->makePathRelative(realpath($exclude), $that->root);
     }, array_merge($this->excludes, [$this->outputDir]))));
     $this->dispatcher->dispatch(BrancherEvents::SETUP, new SetupEvent($this, $renderFinder));
     // Render every file and dump to output
     $directoryVisited = [];
     /** @var \Symfony\Component\Finder\SplFileInfo $fileInfo */
     foreach ($renderFinder as $fileInfo) {
         $path = $fileInfo->getRelativePath();
         if (!isset($directoryVisited[$path])) {
             $pathObj = new SplFileInfo($fileInfo->getPath(), basename($fileInfo->getRelativePath()), $fileInfo->getRelativePath());
             $event = new DirectoryEnterEvent($this, $pathObj, $this->getSpecialConfig($fileInfo->getPath()));
             $this->dispatcher->dispatch(BrancherEvents::DIRECTORY_ENTER, $event);
             $directoryVisited[$path] = !$event->isShouldSkip();
         }
         if ($directoryVisited[$fileInfo->getRelativePath()] === false) {
             continue;
         }
         if ($fileInfo->getFilename() === $this->specialFile) {
             continue;
         }
         if (substr($this->finfo->file($fileInfo->getPathname()), 0, 4) === 'text') {
             $this->renderFile($fileInfo->getRelativePathname(), $fileInfo->getRelativePathname(), ['path' => $fileInfo->getRelativePathname()]);
         } else {
             // Dump binary files verbatim into output directory
             $this->filesystem->copy($fileInfo->getPathname(), "{$this->outputDir}/{$fileInfo->getRelativePathname()}");
         }
     }
     // Finally, we need to add all remaining templates as resources to Assetic
     // so it will dump the proper files
     /** @var \Twig_Loader_Filesystem $loader */
     $loader = $this->twig->getLoader();
     if ($loader instanceof \Twig_Loader_Filesystem) {
         $resourceFinder = new Finder();
         foreach ($loader->getNamespaces() as $ns) {
             $resourceFinder->in($loader->getPaths($ns));
         }
         /** @var \Symfony\Component\Finder\SplFileInfo $template */
         foreach ($resourceFinder as $template) {
             $this->manager->addResource(new TwigResource($loader, $template->getRelativePathname()), 'twig');
         }
     }
     $this->writer->writeManagerAssets($this->manager);
     $this->dispatcher->dispatch(BrancherEvents::TEARDOWN, new TeardownEvent($this));
 }
Esempio n. 6
0
 public function renderThemeAssets()
 {
     $conf = (array) $this->getThemeAssets();
     $factory = new Factory\AssetFactory($conf['root_path']);
     $factory->setAssetManager($this->getAssetManager());
     $factory->setFilterManager($this->getFilterManager());
     $factory->setDebug($this->configuration->isDebug());
     $mobileDetect = $this->serviceManager->get('dxMobileDetect');
     $isTablet = $mobileDetect->isTablet();
     $assetName = 'assets';
     $filterName = 'filters';
     $optionName = 'options';
     $outputName = 'output';
     if ($mobileDetect->isMobile()) {
         $assetName = $assetName . 'Mobile';
         $filterName = $filterName . 'Mobile';
         $optionName = $optionName . 'Mobile';
         $outputName = $outputName . 'Mobile';
     }
     if ($mobileDetect->isTablet()) {
         $assetName = $assetName . 'Tablet';
         $filterName = $filterName . 'Tablet';
         $optionName = $optionName . 'Tablet';
         $outputName = $outputName . 'Mobile';
     }
     $collections = (array) $conf['collections'];
     foreach ($collections as $name => $options) {
         $assets = isset($options[$assetName]) ? $options[$assetName] : isset($options['assets']) ? $options['assets'] : array();
         $filtersx = isset($options[$filterName]) ? $options[$filterName] : isset($options['filters']) ? $options['filters'] : array();
         $options = isset($options[$optionName]) ? $options[$optionName] : isset($options['options']) ? $options['options'] : array();
         $options['output'] = isset($options[$outputName]) ? $options[$outputName] : isset($options['output']) ? $options['output'] : $name;
         $filters = $this->initFilters($filtersx);
         /** @var $asset \Assetic\Asset\AssetCollection */
         $asset = $factory->createAsset($assets, $filters, $options);
         # allow to move all files 1:1 to new directory
         # its particulary usefull when this assets are images.
         if (isset($options['move_raw']) && $options['move_raw']) {
             foreach ($asset as $key => $value) {
                 $name = md5($value->getSourceRoot() . $value->getSourcePath());
                 $value->setTargetPath($value->getSourcePath());
                 $value = $this->cache($value);
                 $this->assetManager->set($name, $value);
             }
         } else {
             $asset = $this->cache($asset);
             $this->assetManager->set($name, $asset);
         }
     }
     $writer = new AssetWriter($this->configuration->getWebPath());
     $writer->writeManagerAssets($this->assetManager);
 }
Esempio n. 7
0
 /**
  * Set Writer for css
  *
  * @author Kondratenko Alexander (Xander)
  */
 public function writeStaticCssLinks()
 {
     $writer = new AssetWriter(assets_server_path('static'));
     $writer->writeManagerAssets($this->am_css);
 }
        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);
        }
    }
}
Esempio n. 9
0
/**
 * 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) : '';
}
Esempio n. 10
0
 /**
  * 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;
 }
Esempio n. 11
0
 /**
  * Compile Less Themes that are defined in a twig file with lessphp filter
  *
  * @param mixed  $themes  An array of Theme entities or a string of the template with following syntax:
  *                        'ClarolineCoreBundle:less:bootstrap-default/theme.html.twig'
  * @param string $webPath
  *
  * @todo Find something better for web path
  */
 public function compileTheme($themes, $webPath = '.')
 {
     $assetManager = $this->container->get('assetic.asset_manager');
     $twigEnvironment = $this->container->get('twig');
     $twigLoader = $this->container->get('twig.loader');
     // enable loading assets from twig templates
     $assetManager->setLoader('twig', new TwigFormulaLoader($twigEnvironment));
     $lessGenerated = array();
     if (is_array($themes)) {
         foreach ($themes as $theme) {
             if ($theme->getPath() === 'less-generated') {
                 $lessGenerated[] = $theme->getName();
             } else {
                 $resource = new TwigResource($twigLoader, $theme->getPath());
                 $assetManager->addResource($resource, 'twig');
             }
         }
     } elseif (is_object($themes) and $themes->getPath() === 'less-generated') {
         $lessGenerated[] = $themes->getName();
     } else {
         $resource = new TwigResource($twigLoader, $themes);
         $assetManager->addResource($resource, 'twig');
     }
     $this->compileRaw($lessGenerated);
     $writer = new AssetWriter($webPath);
     $writer->writeManagerAssets($assetManager);
 }
Esempio n. 12
0
use Assetic\AssetWriter;
use Assetic\Extension\Twig\AsseticExtension;
use Assetic\Extension\Twig\TwigFormulaLoader;
use Assetic\Extension\Twig\TwigResource;
use Assetic\Factory\AssetFactory;
use Assetic\Factory\LazyAssetManager;
use Assetic\Filter\LessFilter;
use Assetic\FilterManager;
use Symfony\Component\Finder\Finder;
$loader = new Twig_Loader_Filesystem(VIEWS_PATH);
$options = ['cache' => DEBUG_APP ? false : 'cache'];
$twig = new Twig_Environment($loader, $options);
$assetManager = new AssetManager();
$filterManager = new FilterManager();
$filterManager->set('less', new LessFilter(NODE_PATH, [NODE_MODULE_PATH]));
$assetFactory = new AssetFactory('assets/');
$assetFactory->setDebug(false);
$assetFactory->setAssetManager($assetManager);
$assetFactory->setFilterManager($filterManager);
$twig->addExtension(new AsseticExtension($assetFactory));
$lazyAssetManager = new LazyAssetManager($assetFactory);
$lazyAssetManager->setLoader('twig', new TwigFormulaLoader($twig));
$finder = new Finder();
$finder->files()->in('assets')->exclude('css')->exclude('js')->exclude('images')->name("*.twig");
foreach ($finder as $template) {
    $resource = new TwigResource($loader, $template->getFileName());
    $lazyAssetManager->addResource($resource, 'twig');
}
$writer = new AssetWriter('.');
$writer->writeManagerAssets($lazyAssetManager);
Esempio n. 13
0
 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;
 }
Esempio n. 14
0
 protected function writer()
 {
     $writer = new AssetWriter('public' . $this->_uri);
     $writer->writeManagerAssets($this->_am);
 }
 public function testFoor()
 {
     $am = $this->factoryAm();
     $writer = new AssetWriter(__DIR__ . "/../assets/build");
     $writer->writeManagerAssets($am);
 }
Esempio n. 16
0
 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);
     }
 }
Esempio n. 17
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');
 }