HttpFoundationExtension.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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\Extension;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\UrlHelper;
  13. use Twig\Extension\AbstractExtension;
  14. use Twig\TwigFunction;
  15. /**
  16. * Twig extension for the Symfony HttpFoundation component.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. final class HttpFoundationExtension extends AbstractExtension
  21. {
  22. private $urlHelper;
  23. public function __construct(UrlHelper $urlHelper)
  24. {
  25. $this->urlHelper = $urlHelper;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function getFunctions(): array
  31. {
  32. return [
  33. new TwigFunction('absolute_url', [$this, 'generateAbsoluteUrl']),
  34. new TwigFunction('relative_path', [$this, 'generateRelativePath']),
  35. ];
  36. }
  37. /**
  38. * Returns the absolute URL for the given absolute or relative path.
  39. *
  40. * This method returns the path unchanged if no request is available.
  41. *
  42. * @see Request::getUriForPath()
  43. */
  44. public function generateAbsoluteUrl(string $path): string
  45. {
  46. return $this->urlHelper->getAbsoluteUrl($path);
  47. }
  48. /**
  49. * Returns a relative path based on the current Request.
  50. *
  51. * This method returns the path unchanged if no request is available.
  52. *
  53. * @see Request::getRelativeUriForPath()
  54. */
  55. public function generateRelativePath(string $path): string
  56. {
  57. return $this->urlHelper->getRelativePath($path);
  58. }
  59. }