AsseticTokenParser.php 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * This file is part of the Symfony framework.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Symfony\Bundle\AsseticBundle\Twig;
  11. use Assetic\Asset\AssetInterface;
  12. use Assetic\Extension\Twig\AsseticTokenParser as BaseAsseticTokenParser;
  13. use Symfony\Bundle\AsseticBundle\Exception\InvalidBundleException;
  14. use Symfony\Component\Templating\TemplateNameParserInterface;
  15. /**
  16. * Assetic token parser.
  17. *
  18. * @author Kris Wallsmith <kris@symfony.com>
  19. */
  20. class AsseticTokenParser extends BaseAsseticTokenParser
  21. {
  22. private $templateNameParser;
  23. private $enabledBundles;
  24. public function setTemplateNameParser(TemplateNameParserInterface $templateNameParser)
  25. {
  26. $this->templateNameParser = $templateNameParser;
  27. }
  28. public function setEnabledBundles(array $enabledBundles = null)
  29. {
  30. $this->enabledBundles = $enabledBundles;
  31. }
  32. public function parse(\Twig_Token $token)
  33. {
  34. if ($this->templateNameParser && is_array($this->enabledBundles)) {
  35. // check the bundle
  36. $templateRef = null;
  37. try {
  38. $templateRef = $this->templateNameParser->parse($this->parser->getStream()->getFilename());
  39. } catch (\RuntimeException $e) {
  40. // this happens when the filename isn't a Bundle:* url
  41. // and it contains ".."
  42. } catch (\InvalidArgumentException $e) {
  43. // this happens when the filename isn't a Bundle:* url
  44. // but an absolute path instead
  45. }
  46. $bundle = $templateRef ? $templateRef->get('bundle') : null;
  47. if ($bundle && !in_array($bundle, $this->enabledBundles)) {
  48. throw new InvalidBundleException($bundle, "the {% {$this->getTag()} %} tag", $templateRef->getLogicalName(), $this->enabledBundles);
  49. }
  50. }
  51. return parent::parse($token);
  52. }
  53. protected function createNode(AssetInterface $asset, \Twig_NodeInterface $body, array $inputs, array $filters, $name, array $attributes = array(), $lineno = 0, $tag = null)
  54. {
  55. return new AsseticNode($asset, $body, $inputs, $filters, $name, $attributes, $lineno, $tag);
  56. }
  57. }