StopwatchTokenParser.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Twig\TokenParser;
  11. use Symfony\Bridge\Twig\Node\StopwatchNode;
  12. use Twig\Node\Expression\AssignNameExpression;
  13. use Twig\Node\Node;
  14. use Twig\Token;
  15. use Twig\TokenParser\AbstractTokenParser;
  16. /**
  17. * Token Parser for the stopwatch tag.
  18. *
  19. * @author Wouter J <wouter@wouterj.nl>
  20. */
  21. final class StopwatchTokenParser extends AbstractTokenParser
  22. {
  23. protected $stopwatchIsAvailable;
  24. public function __construct(bool $stopwatchIsAvailable)
  25. {
  26. $this->stopwatchIsAvailable = $stopwatchIsAvailable;
  27. }
  28. public function parse(Token $token): Node
  29. {
  30. $lineno = $token->getLine();
  31. $stream = $this->parser->getStream();
  32. // {% stopwatch 'bar' %}
  33. $name = $this->parser->getExpressionParser()->parseExpression();
  34. $stream->expect(Token::BLOCK_END_TYPE);
  35. // {% endstopwatch %}
  36. $body = $this->parser->subparse([$this, 'decideStopwatchEnd'], true);
  37. $stream->expect(Token::BLOCK_END_TYPE);
  38. if ($this->stopwatchIsAvailable) {
  39. return new StopwatchNode($name, $body, new AssignNameExpression($this->parser->getVarName(), $token->getLine()), $lineno, $this->getTag());
  40. }
  41. return $body;
  42. }
  43. public function decideStopwatchEnd(Token $token): bool
  44. {
  45. return $token->test('endstopwatch');
  46. }
  47. public function getTag(): string
  48. {
  49. return 'stopwatch';
  50. }
  51. }