TwigEngineTest.php 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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\Bundle\TwigBundle\Tests;
  11. use Symfony\Bundle\TwigBundle\TwigEngine;
  12. use Symfony\Component\DependencyInjection\Container;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Session;
  15. use Symfony\Component\HttpFoundation\SessionStorage\ArraySessionStorage;
  16. use Symfony\Component\Templating\TemplateNameParser;
  17. use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables;
  18. class TwigEngineTest extends TestCase
  19. {
  20. public function testEvaluateAddsAppGlobal()
  21. {
  22. $environment = $this->getTwigEnvironment();
  23. $container = $this->getContainer();
  24. $engine = new TwigEngine($environment, new TemplateNameParser(), $app = new GlobalVariables($container));
  25. $template = $this->getMock('\Twig_TemplateInterface');
  26. $environment->expects($this->once())
  27. ->method('loadTemplate')
  28. ->will($this->returnValue($template));
  29. $engine->render('name');
  30. $request = $container->get('request');
  31. $globals = $environment->getGlobals();
  32. $this->assertSame($app, $globals['app']);
  33. }
  34. public function testEvaluateWithoutAvailableRequest()
  35. {
  36. $environment = $this->getTwigEnvironment();
  37. $container = new Container();
  38. $engine = new TwigEngine($environment, new TemplateNameParser(), new GlobalVariables($container));
  39. $template = $this->getMock('\Twig_TemplateInterface');
  40. $environment->expects($this->once())
  41. ->method('loadTemplate')
  42. ->will($this->returnValue($template));
  43. $container->set('request', null);
  44. $engine->render('name');
  45. $globals = $environment->getGlobals();
  46. $this->assertEmpty($globals['app']->getRequest());
  47. }
  48. /**
  49. * Creates a Container with a Session-containing Request service.
  50. *
  51. * @return Container
  52. */
  53. protected function getContainer()
  54. {
  55. $container = new Container();
  56. $request = new Request();
  57. $session = new Session(new ArraySessionStorage());
  58. $request->setSession($session);
  59. $container->set('request', $request);
  60. return $container;
  61. }
  62. /**
  63. * Creates a mock Twig_Environment object.
  64. *
  65. * @return \Twig_Environment
  66. */
  67. protected function getTwigEnvironment()
  68. {
  69. return $this
  70. ->getMockBuilder('\Twig_Environment')
  71. ->setMethods(array('loadTemplate'))
  72. ->getMock();
  73. }
  74. }