StopwatchExtensionTest.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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\Tests\Extension;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Bridge\Twig\Extension\StopwatchExtension;
  13. use Twig\Environment;
  14. use Twig\Error\RuntimeError;
  15. use Twig\Loader\ArrayLoader;
  16. class StopwatchExtensionTest extends TestCase
  17. {
  18. /**
  19. * @expectedException \Twig\Error\SyntaxError
  20. */
  21. public function testFailIfStoppingWrongEvent()
  22. {
  23. $this->testTiming('{% stopwatch "foo" %}{% endstopwatch "bar" %}', array());
  24. }
  25. /**
  26. * @dataProvider getTimingTemplates
  27. */
  28. public function testTiming($template, $events)
  29. {
  30. $twig = new Environment(new ArrayLoader(array('template' => $template)), array('debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0));
  31. $twig->addExtension(new StopwatchExtension($this->getStopwatch($events)));
  32. try {
  33. $nodes = $twig->render('template');
  34. } catch (RuntimeError $e) {
  35. throw $e->getPrevious();
  36. }
  37. }
  38. public function getTimingTemplates()
  39. {
  40. return array(
  41. array('{% stopwatch "foo" %}something{% endstopwatch %}', 'foo'),
  42. array('{% stopwatch "foo" %}symfony is fun{% endstopwatch %}{% stopwatch "bar" %}something{% endstopwatch %}', array('foo', 'bar')),
  43. array('{% set foo = "foo" %}{% stopwatch foo %}something{% endstopwatch %}', 'foo'),
  44. array('{% set foo = "foo" %}{% stopwatch foo %}something {% set foo = "bar" %}{% endstopwatch %}', 'foo'),
  45. array('{% stopwatch "foo.bar" %}something{% endstopwatch %}', 'foo.bar'),
  46. array('{% stopwatch "foo" %}something{% endstopwatch %}{% stopwatch "foo" %}something else{% endstopwatch %}', array('foo', 'foo')),
  47. );
  48. }
  49. protected function getStopwatch($events = array())
  50. {
  51. $events = is_array($events) ? $events : array($events);
  52. $stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')->getMock();
  53. $i = -1;
  54. foreach ($events as $eventName) {
  55. $stopwatch->expects($this->at(++$i))
  56. ->method('start')
  57. ->with($this->equalTo($eventName), 'template')
  58. ;
  59. $stopwatch->expects($this->at(++$i))
  60. ->method('stop')
  61. ->with($this->equalTo($eventName))
  62. ;
  63. }
  64. return $stopwatch;
  65. }
  66. }