4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel\Fragment;
14 use Symfony\Component\HttpKernel\Controller\ControllerReference;
15 use Symfony\Component\HttpFoundation\Request;
16 use Symfony\Component\HttpKernel\EventListener\FragmentListener;
19 * Adds the possibility to generate a fragment URI for a given Controller.
21 * @author Fabien Potencier <fabien@symfony.com>
23 abstract class RoutableFragmentRenderer implements FragmentRendererInterface
25 private $fragmentPath = '/_fragment';
28 * Sets the fragment path that triggers the fragment listener.
30 * @param string $path The path
32 * @see FragmentListener
34 public function setFragmentPath($path)
36 $this->fragmentPath = $path;
40 * Generates a fragment URI for a given controller.
42 * @param ControllerReference $reference A ControllerReference instance
43 * @param Request $request A Request instance
44 * @param bool $absolute Whether to generate an absolute URL or not
45 * @param bool $strict Whether to allow non-scalar attributes or not
47 * @return string A fragment URI
49 protected function generateFragmentUri(ControllerReference $reference, Request $request, $absolute = false, $strict = true)
52 $this->checkNonScalar($reference->attributes);
55 // We need to forward the current _format and _locale values as we don't have
56 // a proper routing pattern to do the job for us.
57 // This makes things inconsistent if you switch from rendering a controller
58 // to rendering a route if the route pattern does not contain the special
59 // _format and _locale placeholders.
60 if (!isset($reference->attributes['_format'])) {
61 $reference->attributes['_format'] = $request->getRequestFormat();
63 if (!isset($reference->attributes['_locale'])) {
64 $reference->attributes['_locale'] = $request->getLocale();
67 $reference->attributes['_controller'] = $reference->controller;
69 $reference->query['_path'] = http_build_query($reference->attributes, '', '&');
71 $path = $this->fragmentPath.'?'.http_build_query($reference->query, '', '&');
74 return $request->getUriForPath($path);
77 return $request->getBaseUrl().$path;
80 private function checkNonScalar($values)
82 foreach ($values as $key => $value) {
83 if (is_array($value)) {
84 $this->checkNonScalar($value);
85 } elseif (!is_scalar($value) && null !== $value) {
86 throw new \LogicException(sprintf('Controller attributes cannot contain non-scalar/non-null values (value for key "%s" is not a scalar or null).', $key));