示例#1
0
 /**
  * Locates twig templates and adds their defined assets to the lazy asset manager
  */
 public function addTwigAssets()
 {
     if (!$this->twig instanceof \Twig_Environment) {
         throw new \LogicException('Twig environment not set');
     }
     $finder = new Finder();
     $viewfinder = $this->viewfinder;
     if (count($viewfinder->getPaths()) > 0) {
         $iterator = $finder->files()->in($viewfinder->getPaths());
         foreach ($iterator as $file) {
             $resource = new TwigResource($this->loader, $file->getRelativePathname());
             $this->lam->addResource($resource, 'twig');
         }
     }
 }
示例#2
0
 /**
  * Locates twig templates and adds their defined assets to the lazy asset manager
  */
 public function addTwigAssets()
 {
     if (!$this->twig instanceof \Twig_Environment) {
         throw new \LogicException('Twig environment not set');
     }
     $twigNamespaces = $this->loader->getNamespaces();
     foreach ($twigNamespaces as $ns) {
         if (count($this->loader->getPaths($ns)) > 0) {
             $iterator = Finder::create()->files()->in($this->loader->getPaths($ns));
             foreach ($iterator as $file) {
                 $resource = new TwigResource($this->loader, '@' . $ns . '/' . $file->getRelativePathname());
                 $this->lam->addResource($resource, 'twig');
             }
         }
     }
 }
示例#3
0
 /**
  * Writes an asset.
  *
  * If the application or asset is in debug mode, each leaf asset will be
  * dumped as well.
  *
  * @param string          $name   An asset name
  * @param OutputInterface $output The command output
  */
 private function dumpAsset($name, OutputInterface $output, array &$previously = array())
 {
     $formula = $this->am->getFormula($name);
     if ($this->debug) {
         if (isset($formula[2]['debug']) && !$formula[2]['debug'] && $this->am->isDebug()) {
             return;
         }
     }
     $asset = $this->am->get($name);
     // start by dumping the main asset
     $this->doDump($asset, $output);
     // dump each leaf if debug
     if (isset($formula[2]['debug']) ? $formula[2]['debug'] : $this->am->isDebug()) {
         foreach ($asset as $leaf) {
             $key = serialize($leaf);
             $mtime = $leaf->getLastModified();
             if (isset($previously[$key])) {
                 $changed = $previously[$key]['mtime'] != $mtime;
             } else {
                 $changed = true;
             }
             $previously[$key] = array('mtime' => $mtime);
             if ($changed) {
                 $this->doDump($leaf, $output);
             }
         }
     }
     if (!$this->debug) {
         // dump the main asset
         $this->doDump($asset, $output);
     }
 }
示例#4
0
 public function all()
 {
     if (!$this->fresh) {
         $this->loadCacheFiles();
     }
     return parent::all();
 }
示例#5
0
 /**
  * Render a single file from a template to an output path
  *
  * @param string $templateName Name of the template for Twig
  * @param string $outputPath Relative path to render to
  * @param array $context Twig context
  */
 public function renderFile($templateName, $outputPath, array $context)
 {
     $template = $this->twig->loadTemplate($templateName);
     $this->manager->addResource(new TwigResource($this->twig->getLoader(), $templateName), 'twig');
     $event = new RenderEvent($this, $template, $context);
     $this->dispatcher->dispatch(BrancherEvents::RENDER, $event);
     $rendered = $template->render($event->context);
     $this->filesystem->dumpFile("{$this->outputDir}/{$outputPath}", $rendered);
 }
 /**
  *
  * @param  Application $app
  */
 function register(Application $app)
 {
     $app['assetic.asset.root'] = '';
     $app['assetic.asset.output_root'] = '';
     $app['assetic.debug'] = false;
     $app['assetic.filter'] = array();
     $app['assetic.filter.default'] = array('cssmin' => '\\Assetic\\Filter\\CssMinFilter', 'cssrewrite' => '\\Assetic\\Filter\\CssRewriteFilter');
     $app['assetic.filter_manager'] = $app->share(function ($app) {
         $filterManager = new FilterManager();
         return $filterManager;
     });
     $app['assetic.asset_manager'] = $app->share(function ($app) {
         $assetManager = new AssetManager();
         return $assetManager;
     });
     $app['assetic.asset_factory'] = $app->share(function ($app) {
         $assetFactory = new AssetFactory($app['assetic.asset.root']);
         $assetFactory->setDefaultOutput($app['assetic.asset.output_root']);
         $assetFactory->setFilterManager($app['assetic.filter_manager']);
         $assetFactory->setAssetManager($app['assetic.asset_manager']);
         $assetFactory->setDebug($app['assetic.debug']);
         return $assetFactory;
     });
     $app['assetic.lazy_asset_manager'] = $app->share(function ($app) {
         $lazyAssetManager = new LazyAssetManager($app['assetic.asset_factory']);
         $lazyAssetManager->setLoader('twig', new TwigAsseticIntegrationFormulaLoader($app['twig'], null, $app));
         return $lazyAssetManager;
     });
     $app['assetic.asset_writer'] = $app->share(function ($app) {
         $assetWriter = new AssetWriter($app['assetic.asset.output_root']);
         return $assetWriter;
     });
     /*
      * Twig
      *
      */
     // Replace Twig loader
     $app['twig.loader.filesystem'] = $app->share(function ($app) {
         return new \Wake\Twig_AsseticLoader_Filesystem($app['twig.path']);
     });
     $app['twig.loader'] = $app->share(function ($app) {
         return new \Wake\Twig_AsseticLoader_Chain(array($app['twig.loader.array'], $app['twig.loader.filesystem']));
     });
 }
 /**
  * Registers services on the given app.
  *
  * This method should only be used to configure services and parameters.
  * It should not get services.
  *
  * @param Application $app
  */
 public function register(Application $app)
 {
     $app['assetic.read_from'] = '';
     $app['assetic.write_to'] = '';
     $app['assetic.cache_dir'] = '';
     $app['assetic.debug'] = false;
     $app['assetic.factory_workers'] = $app->share(function () use($app) {
         return ['cache_busting' => $app->share(function () {
             return new CacheBustingWorker();
         })];
     });
     $app['assetic.filters'] = $app->share(function () use($app) {
         return [];
     });
     $app['assetic.formula_loaders'] = $app->share(function () use($app) {
         return [];
     });
     $app['assetic.filter_manager'] = $app->share(function () use($app) {
         return new FilterManager($app, $app['assetic.filters']);
     });
     $app['assetic.asset_manager'] = $app->share(function () use($app) {
         $manager = new LazyAssetManager($app['assetic.asset_factory']);
         foreach ($app['assetic.formula_loaders'] as $alias => $loader) {
             $manager->setLoader($alias, is_callable($loader) ? $loader($app) : $loader);
         }
         return $manager;
     });
     $app['assetic.asset_cache'] = $app->share(function () use($app) {
         return new FilesystemCache($app['assetic.cache_dir']);
     });
     $app['assetic.asset_factory'] = $app->share(function () use($app) {
         $factory = new AssetFactory($app, $app['assetic.read_from'], $app['assetic.debug']);
         foreach ($app['assetic.factory_workers'] as $worker) {
             $factory->addWorker($worker($app));
         }
         return $factory;
     });
     $app['assetic.collect_twig_resources_listener'] = $app->share(function () use($app) {
         return new CollectTwigResourcesEventListener($app['assetic.asset_manager'], $app['twig']);
     });
     $app['assetic.dump_listener'] = $app->share(function () use($app) {
         return new DumpEventListener($app['assetic.asset_factory'], $app['assetic.asset_cache'], $app['assetic.write_to']);
     });
 }
 public function dump()
 {
     $finder = new Finder();
     $twigNamespaces = $this->loader->getNamespaces();
     foreach ($twigNamespaces as $ns) {
         if (count($this->loader->getPaths($ns)) > 0) {
             $iterator = $finder->files()->in($this->loader->getPaths($ns));
             foreach ($iterator as $file) {
                 /** @var SplFileInfo $file */
                 $resource = new TwigResource($this->loader, '@' . $ns . '/' . $file->getRelativePathname());
                 $this->lam->addResource($resource, 'twig');
             }
         }
     }
     foreach ($this->lam->getNames() as $name) {
         $asset = $this->lam->get($name);
         $formula = $this->lam->getFormula($name);
         $debug = isset($formula[2]['debug']) ? $formula[2]['debug'] : $this->lam->isDebug();
         $combine = isset($formula[2]['combine']) ? $formula[2]['combine'] : null;
         if (null !== $combine ? !$combine : $debug) {
             foreach ($asset as $leaf) {
                 $this->aw->writeAsset($leaf);
             }
         } else {
             $this->aw->writeAsset($asset);
         }
     }
 }
示例#9
0
 /**
  *
  * @param string $name
  * @param array  $formula 
  * 
  * @return void
  */
 public function setFormula($name, array $formula)
 {
     $formulas = $this->getCache()->has('assetic') ? unserialize($this->getCache()->get('assetic')) : array();
     if (!is_array($formulas)) {
         $formulas = array();
     }
     if (array_key_exists($name, $formulas)) {
         return;
     }
     $formulas[$name] = $this->makeFormulaSerializable($formula);
     $this->getCache()->set('assetic', serialize($formulas));
     return parent::setFormula($name, $formula);
 }
 /**
  * Writes an asset.
  *
  * If the application or asset is in debug mode, each leaf asset will be
  * dumped as well.
  *
  * @param string          $name   An asset name
  * @param OutputInterface $output The command output
  */
 private function dumpAsset($name, OutputInterface $output)
 {
     $asset = $this->am->get($name);
     $formula = $this->am->getFormula($name);
     if ($this->getConfig()->getEnv() != 'dev') {
         $this->doDump($asset, $output);
     }
     // dump each leaf if debug
     if (isset($formula[2]['debug']) ? $formula[2]['debug'] : $this->am->isDebug()) {
         foreach ($asset as $leaf) {
             $this->doDump($leaf, $output);
         }
     }
 }
 /**
  * Analyze resources and collect nodes of OroAsseticNode
  *
  * @return OroAsseticNode[]
  */
 protected function loadAssets()
 {
     $result = array();
     foreach ($this->am->getResources() as $resources) {
         if (!$resources instanceof IteratorResourceInterface) {
             $resources = array($resources);
         }
         /**@var $resource FileResource */
         foreach ($resources as $resource) {
             $tokens = $this->twig->tokenize($resource->getContent(), (string) $resource);
             $nodes = $this->twig->parse($tokens);
             $result += $this->loadNode($nodes);
         }
     }
     return $result;
 }
 /**
  * Collect asset resources defined in twig templates
  *
  * @param FilterResponseEvent $event
  */
 public function onKernelResponse(FilterResponseEvent $event)
 {
     if (count($this->templates) === 0) {
         // Automatically find templates only if loader compatible
         if ($this->loader instanceof \Twig_Loader_Filesystem) {
             $twigNamespaces = $this->loader->getNamespaces();
             foreach ($twigNamespaces as $ns) {
                 if (count($this->loader->getPaths($ns)) > 0) {
                     $iterator = Finder::create()->files()->in($this->loader->getPaths($ns));
                     /* @var $file \Symfony\Component\Finder\SplFileInfo */
                     foreach ($iterator as $file) {
                         $resource = new TwigResource($this->loader, '@' . $ns . '/' . $file->getRelativePathname());
                         $this->manager->addResource($resource, 'twig');
                     }
                 }
             }
         }
     } else {
         foreach ($this->templates as $template) {
             $resource = new TwigResource($this->loader, $template);
             $this->manager->addResource($resource, 'twig');
         }
     }
 }
 /**
  * @param Container $container
  */
 public function register(Container $container)
 {
     $container['assetic.asset.root'] = '';
     $container['assetic.asset.asset_root'] = '';
     $container['assetic.asset.factory'] = function () use($container) {
         $assetFactory = new AssetFactory($container['assetic.asset.root']);
         $assetFactory->setDefaultOutput($container['assetic.asset.asset_root']);
         $assetFactory->setDebug(isset($container['debug']) ? $container['debug'] : false);
         $assetFactory->setFilterManager($container['assetic.filter_manager']);
         return $assetFactory;
     };
     $container['assetic.filters.default'] = array('csscopyfile' => true, 'lessphp' => true, 'scssphp' => true, 'cssmin' => true, 'csscompress' => true, 'jsmin' => true);
     $container['assetic.filters'] = function () use($container) {
         return array();
     };
     $container['assetic.filterinstances'] = function () use($container) {
         $filterInstances = array();
         $filterConfig = array_merge($container['assetic.filters.default'], $container['assetic.filters']);
         if ($filterConfig['csscopyfile']) {
             $filterInstances['csscopyfile'] = new CssCopyFileFilter($container['assetic.asset.asset_root']);
         }
         if ($filterConfig['lessphp'] && class_exists('\\lessc')) {
             $filterInstances['lessphp'] = new LessphpFilter();
         }
         if ($filterConfig['scssphp'] && class_exists('\\scssc')) {
             $filterInstances['scssphp'] = new ScssphpFilter();
         }
         if ($filterConfig['cssmin'] && class_exists('\\CssMin')) {
             $filterInstances['cssmin'] = new CssMinFilter();
         }
         if ($filterConfig['csscompress'] && class_exists('\\Minify_CSS_Compressor')) {
             $filterInstances['csscompress'] = new MinifyCssCompressorFilter();
         }
         if ($filterConfig['jsmin'] && class_exists('\\JSMin')) {
             $filterInstances['jsmin'] = new JSMinFilter();
         }
         return $filterInstances;
     };
     $container['assetic.filter_manager'] = function () use($container) {
         $filterManager = new FilterManager();
         $filters = $container['assetic.filterinstances'];
         foreach ($filters as $alias => $filter) {
             $filterManager->set($alias, $filter);
         }
         return $filterManager;
     };
     $container['assetic.asset.manager'] = function () use($container) {
         $assetManager = new LazyAssetManager($container['assetic.asset.factory']);
         $assetManager->setLoader('twig', new TwigFormulaLoader($container['twig'], $container['logger']));
         return $assetManager;
     };
     $container['assetic.asset.writer'] = function () use($container) {
         return new AssetWriter($container['assetic.asset.asset_root']);
     };
     $container['assetic.asset.dumper'] = function () use($container) {
         return new Dumper($container['twig.loader.filesystem'], $container['assetic.asset.manager'], $container['assetic.asset.writer']);
     };
     $container['twig'] = $container->extend('twig', function (\Twig_Environment $twig) use($container) {
         $twig->addExtension(new AsseticExtension($container['assetic.asset.factory']));
         return $twig;
     });
     if (isset($container['console.commands'])) {
         $container['console.commands'] = $container->extend('console.commands', function ($commands) use($container) {
             $commands[] = new AsseticDumpCommand(null, $container);
             return $commands;
         });
     }
 }
示例#14
0
    /**
     * Checks if an asset should be dumped.
     *
     * @param LazyAssetManager $am          The asset manager
     * @param string           $name        The asset name
     * @param array            &$previously An array of previous visits
     *
     * @return AssetInterface|Boolean The asset if it should be dumped
     */
    protected function checkAsset(LazyAssetManager $am, $name, array &$previously)
    {
        $formula = $am->hasFormula($name) ? serialize($am->getFormula($name)) : null;
        $asset = $am->get($name);
        $mtime = $asset->getLastModified();

        if (isset($previously[$name])) {
            $changed = $previously[$name]['mtime'] != $mtime || $previously[$name]['formula'] != $formula;
        } else {
            $changed = true;
        }

        $previously[$name] = array('mtime' => $mtime, 'formula' => $formula);

        return $changed ? $asset : false;
    }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $app = $this->getSilexApp();
     $twig = $app->getTwig();
     $factory = $app->getAssets();
     $assetManager = new LazyAssetManager($factory);
     $assetManager->setLoader('twig', new TwigFormulaLoader($twig));
     if ($input->getOption('ignore-folders')) {
         $output->writeln('<comment>' . date('H:i:s') . '</comment> <info>Skipping folders...</info>');
     } else {
         foreach ($app['assets.folders'] as $folder) {
             $source = $folder['source'];
             $target = $folder['target'];
             if (!is_dir($target)) {
                 $output->writeln('<comment>' . date('H:i:s') . '</comment> <info>[dir+]</info> ' . $this->getAbsolutePath($target));
                 if (false === @mkdir($target, 0777, true)) {
                     throw new \RuntimeException('Unable to create directory ' . $target);
                 }
             }
             $directoryIterator = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS);
             $iterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::SELF_FIRST);
             foreach ($iterator as $file) {
                 $path = $target . DIRECTORY_SEPARATOR . $iterator->getSubPathName();
                 if ($file->isDir()) {
                     if (is_dir($path)) {
                         continue;
                     }
                     $output->writeln('<comment>' . date('H:i:s') . '</comment> <info>[dir+]</info> ' . $this->getAbsolutePath($path));
                     if (false === @mkdir($path, 0777, true)) {
                         throw new \RuntimeException('Unable to create directory ' . $path);
                     }
                 } else {
                     if (is_file($path) && md5_file($path) == md5_file($file)) {
                         continue;
                     }
                     $output->writeln('<comment>' . date('H:i:s') . '</comment> <info>[file+]</info> ' . $this->getAbsolutePath($path));
                     if (false === @file_put_contents($path, file_get_contents($file))) {
                         throw new \RuntimeException('Unable to write file ' . $path);
                     }
                 }
             }
         }
     }
     $directoryIterator = new RecursiveDirectoryIterator($app['twig.path']);
     $iterator = new RecursiveIteratorIterator($directoryIterator);
     $templates = new RegexIterator($iterator, '/^.+\\.twig$/i', RegexIterator::GET_MATCH);
     foreach ($templates as $file) {
         $file = str_replace(rtrim($app['twig.path'], '/') . '/', null, $file[0]);
         $resource = new TwigResource($twig->getLoader(), $file);
         $assetManager->addResource($resource, 'twig');
     }
     foreach ($app['twig.templates'] as $name => $file) {
         $resource = new TwigResource($twig->getLoader(), $name);
         $assetManager->addResource($resource, 'twig');
     }
     $writer = new AssetWriter($app['assets.output_path']);
     foreach ($assetManager->getNames() as $name) {
         $asset = $assetManager->get($name);
         foreach (VarUtils::getCombinations($asset->getVars(), []) as $combination) {
             $asset->setValues($combination);
             $path = $app['assets.output_path'] . '/' . VarUtils::resolve($asset->getTargetPath(), $asset->getVars(), $asset->getValues());
             if (!is_dir($dir = dirname($path))) {
                 $output->writeln('<comment>' . date('H:i:s') . '</comment> <info>[dir+]</info> ' . $this->getAbsolutePath($dir));
                 if (false === @mkdir($dir, 0777, true)) {
                     throw new \RuntimeException('Unable to create directory ' . $dir);
                 }
             }
             $output->writeln('<comment>' . date('H:i:s') . '</comment> <info>[file+]</info> ' . $this->getAbsolutePath($path));
             if (false === @file_put_contents($path, $asset->dump())) {
                 throw new \RuntimeException('Unable to write file ' . $path);
             }
         }
     }
 }
示例#16
0
文件: Manager.php 项目: lalop/aphet
 public function computeAsset($relative_path, $name = null)
 {
     $paths = is_array($relative_path) ? $relative_path : array($relative_path);
     if (count($paths) > 1 && null === $name) {
         throw new Exception('You have to define a name for asset collection');
     }
     $am = new LazyAssetManager(new AssetFactory(''));
     $assets = array();
     $asset_collection = new AssetCollection();
     if ($this->settings['modes'] & Modes::CONCAT) {
         $assets[] = $asset_collection;
     }
     foreach ($paths as $p) {
         $file = $this->loader->fromAppPath($p);
         $asset = $file->asset(['compass' => $this->settings['modes'] & Modes::COMPASS]);
         $ext = str_replace(array('sass', 'scss'), 'css', File::getExt($p));
         $filename = substr($p, 0, strrpos($p, '.'));
         if ($this->settings['modes'] & Modes::CONCAT) {
             $asset_collection->add($asset);
             if (null === $name) {
                 $name = $filename . $ext;
             }
             $asset_collection->setTargetPath($name);
         } else {
             $asset->setTargetPath($filename . $ext);
             $assets[] = $asset;
         }
     }
     foreach ($assets as $asset) {
         // add the timestamp
         $target_path = explode('/', $asset->getTargetPath());
         $file_name = array_pop($target_path);
         $target_path[] = $am->getLastModified($asset) . '-' . $file_name;
         $web_path = implode('/', $target_path);
         $asset->setTargetPath($web_path);
         if (!file_exists($this->settings['public_path'] . '/' . $this->settings['compiled_dir'] . '/' . $asset->getTargetPath())) {
             if ($this->settings['modes'] & Modes::MINIFY) {
                 switch ($ext) {
                     case '.css':
                         $asset->ensureFilter(new \Assetic\Filter\CssMinFilter());
                         break;
                     case '.js':
                         $asset->ensureFilter(new \Assetic\Filter\JSMinFilter());
                         break;
                 }
             }
             $writer = new AssetWriter($this->settings['public_path'] . '/' . $this->settings['compiled_dir']);
             $writer->writeAsset($asset);
         }
     }
     return $assets[0];
 }
 /**
  * Registers services on the given container.
  *
  * This method should only be used to configure services and parameters.
  * It should not get services.
  *
  * @param Container $pimple An Container instance
  */
 public function register(Container $pimple)
 {
     /*
      * Default configuration.
      */
     $pimple['assetic.debug'] = false;
     $pimple['assetic.assets'] = array();
     $pimple['assetic.variables'] = array();
     $pimple['assetic.register_functions'] = true;
     $pimple['assetic.java.bin'] = '/usr/bin/java';
     $pimple['assetic.node.bin'] = '/usr/bin/node';
     $pimple['assetic.node.paths'] = array();
     $pimple['assetic.ruby.bin'] = '/usr/bin/ruby';
     $pimple['assetic.sass.bin'] = '/usr/bin/sass';
     /*
      * Finds IDs of all Asset Manager services.
      */
     $pimple['assetic.asset_managers'] = $pimple->factory(function (Container $c) {
         $ids = preg_grep(self::ASSET_MANAGER_MATCH, $c->keys());
         return $ids;
     });
     /*
      * Asset Factory configuration happens here
      *
      * @param Container $c
      * @return mixed
      */
     $pimple['assetic'] = function (Container $c) {
         // initializing lazy asset manager
         if (isset($c['assetic.assets']) && is_array($c['assetic.assets']) && !empty($c['assetic.assets'])) {
             $c['assetic.lazy_asset_manager'];
         }
         return $c['assetic.factory'];
     };
     /*
      * Factory
      *
      * @param Container $c
      * @return AssetFactory
      */
     $pimple['assetic.factory'] = function (Container $c) {
         $root = isset($c['assetic.read_from']) ? $c['assetic.read_from'] : $c['assetic.write_to'];
         $factory = new AssetFactory($root, $c['assetic.debug']);
         $factory->setAssetManager($c['assetic.asset_manager']);
         $factory->setFilterManager($c['assetic.filter_manager']);
         // Optionally enable the global asset functions.
         if ($c['assetic.register_functions']) {
             assetic_init($factory);
         }
         return $factory;
     };
     /*
      * Asset writer, writes to the 'assetic.write_to' folder
      *
      * @param Container $c
      * @return AssetWriter
      */
     $pimple['assetic.asset_writer'] = function (Container $c) {
         return new AssetWriter($c['assetic.write_to']);
     };
     /*
      * Asset manager
      *
      * @return AssetManager
      */
     $pimple['assetic.asset_manager'] = function () {
         return new AssetManager();
     };
     /*
      * Filter manager
      *
      * @return FilterManager
      */
     $pimple['assetic.filter_manager'] = function () {
         return new FilterManager();
     };
     /*
      * Lazy asset manager for loading assets from $pimple['assetic.assets']
      *
      * @param Container $c
      * @return \Assetic\Factory\LazyAssetManager
      */
     $pimple['assetic.lazy.asset_manager'] = function (Container $c) {
         $lazy = new LazyAssetManager($c['assetic.factory']);
         foreach ($c['assetic.assets'] as $name => $formula) {
             $lazy->setFormula($name, $formula);
         }
         return $lazy;
     };
 }
 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;
         });
     }
 }
示例#19
0
 /**
  * @{inheritDoc}
  */
 public function load($name, LazyAssetManager $mng)
 {
     $resource = new TwigResource($this->loader, $name);
     $mng->addResource($resource, 'twig');
 }
示例#20
0
use Assetic\AssetManager;
use Assetic\AssetWriter;
use Assetic\Extension\Twig\AsseticExtension;
use Assetic\Extension\Twig\TwigFormulaLoader;
use Assetic\Extension\Twig\TwigResource;
use Assetic\Factory\AssetFactory;
use Assetic\Factory\LazyAssetManager;
use Assetic\Filter\LessFilter;
use Assetic\FilterManager;
use Symfony\Component\Finder\Finder;
$loader = new Twig_Loader_Filesystem(VIEWS_PATH);
$options = ['cache' => DEBUG_APP ? false : 'cache'];
$twig = new Twig_Environment($loader, $options);
$assetManager = new AssetManager();
$filterManager = new FilterManager();
$filterManager->set('less', new LessFilter(NODE_PATH, [NODE_MODULE_PATH]));
$assetFactory = new AssetFactory('assets/');
$assetFactory->setDebug(false);
$assetFactory->setAssetManager($assetManager);
$assetFactory->setFilterManager($filterManager);
$twig->addExtension(new AsseticExtension($assetFactory));
$lazyAssetManager = new LazyAssetManager($assetFactory);
$lazyAssetManager->setLoader('twig', new TwigFormulaLoader($twig));
$finder = new Finder();
$finder->files()->in('assets')->exclude('css')->exclude('js')->exclude('images')->name("*.twig");
foreach ($finder as $template) {
    $resource = new TwigResource($loader, $template->getFileName());
    $lazyAssetManager->addResource($resource, 'twig');
}
$writer = new AssetWriter('.');
$writer->writeManagerAssets($lazyAssetManager);
示例#21
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');
 }