RoutableFragmentRenderer.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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\HttpKernel\Fragment;
  11. use Symfony\Component\HttpKernel\Controller\ControllerReference;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpKernel\EventListener\FragmentListener;
  14. /**
  15. * Adds the possibility to generate a fragment URI for a given Controller.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. abstract class RoutableFragmentRenderer implements FragmentRendererInterface
  20. {
  21. private $fragmentPath = '/_fragment';
  22. /**
  23. * Sets the fragment path that triggers the fragment listener.
  24. *
  25. * @param string $path The path
  26. *
  27. * @see FragmentListener
  28. */
  29. public function setFragmentPath($path)
  30. {
  31. $this->fragmentPath = $path;
  32. }
  33. /**
  34. * Generates a fragment URI for a given controller.
  35. *
  36. * @param ControllerReference $reference A ControllerReference instance
  37. * @param Request $request A Request instance
  38. * @param Boolean $absolute Whether to generate an absolute URL or not
  39. *
  40. * @return string A fragment URI
  41. */
  42. protected function generateFragmentUri(ControllerReference $reference, Request $request, $absolute = false)
  43. {
  44. // We need to forward the current _format and _locale values as we don't have
  45. // a proper routing pattern to do the job for us.
  46. // This makes things inconsistent if you switch from rendering a controller
  47. // to rendering a route if the route pattern does not contain the special
  48. // _format and _locale placeholders.
  49. if (!isset($reference->attributes['_format'])) {
  50. $reference->attributes['_format'] = $request->getRequestFormat();
  51. }
  52. if (!isset($reference->attributes['_locale'])) {
  53. $reference->attributes['_locale'] = $request->getLocale();
  54. }
  55. $reference->attributes['_controller'] = $reference->controller;
  56. $reference->query['_path'] = http_build_query($reference->attributes, '', '&');
  57. $path = $this->fragmentPath.'?'.http_build_query($reference->query, '', '&');
  58. if ($absolute) {
  59. return $request->getUriForPath($path);
  60. }
  61. return $request->getBaseUrl().$path;
  62. }
  63. }