ExpressionLanguageProviderTest.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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\Component\Routing\Tests\Matcher;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\DependencyInjection\ServiceLocator;
  13. use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
  14. use Symfony\Component\Routing\Matcher\ExpressionLanguageProvider;
  15. use Symfony\Component\Routing\RequestContext;
  16. class ExpressionLanguageProviderTest extends TestCase
  17. {
  18. private $context;
  19. private $expressionLanguage;
  20. protected function setUp(): void
  21. {
  22. $functionProvider = new ServiceLocator([
  23. 'env' => function () {
  24. // function with one arg
  25. return function (string $arg) {
  26. return [
  27. 'APP_ENV' => 'test',
  28. 'PHP_VERSION' => '7.2',
  29. ][$arg] ?? null;
  30. };
  31. },
  32. 'sum' => function () {
  33. // function with multiple args
  34. return function ($a, $b) { return $a + $b; };
  35. },
  36. 'foo' => function () {
  37. // function with no arg
  38. return function () { return 'bar'; };
  39. },
  40. ]);
  41. $this->context = new RequestContext();
  42. $this->context->setParameter('_functions', $functionProvider);
  43. $this->expressionLanguage = new ExpressionLanguage();
  44. $this->expressionLanguage->registerProvider(new ExpressionLanguageProvider($functionProvider));
  45. }
  46. /**
  47. * @dataProvider compileProvider
  48. */
  49. public function testCompile(string $expression, string $expected)
  50. {
  51. $this->assertSame($expected, $this->expressionLanguage->compile($expression));
  52. }
  53. public static function compileProvider(): iterable
  54. {
  55. return [
  56. ['env("APP_ENV")', '($context->getParameter(\'_functions\')->get(\'env\')("APP_ENV"))'],
  57. ['sum(1, 2)', '($context->getParameter(\'_functions\')->get(\'sum\')(1, 2))'],
  58. ['foo()', '($context->getParameter(\'_functions\')->get(\'foo\')())'],
  59. ];
  60. }
  61. /**
  62. * @dataProvider evaluateProvider
  63. */
  64. public function testEvaluate(string $expression, $expected)
  65. {
  66. $this->assertSame($expected, $this->expressionLanguage->evaluate($expression, ['context' => $this->context]));
  67. }
  68. public static function evaluateProvider(): iterable
  69. {
  70. return [
  71. ['env("APP_ENV")', 'test'],
  72. ['env("PHP_VERSION")', '7.2'],
  73. ['env("unknown_env_variable")', null],
  74. ['sum(1, 2)', 3],
  75. ['foo()', 'bar'],
  76. ];
  77. }
  78. }