TitleResolver.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Drupal\Core\Controller;
  3. use Drupal\Core\StringTranslation\StringTranslationTrait;
  4. use Drupal\Core\StringTranslation\TranslationInterface;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\Routing\Route;
  7. /**
  8. * Provides the default implementation of the title resolver interface.
  9. */
  10. class TitleResolver implements TitleResolverInterface {
  11. use StringTranslationTrait;
  12. /**
  13. * The controller resolver.
  14. *
  15. * @var \Drupal\Core\Controller\ControllerResolverInterface
  16. */
  17. protected $controllerResolver;
  18. /**
  19. * Constructs a TitleResolver instance.
  20. *
  21. * @param \Drupal\Core\Controller\ControllerResolverInterface $controller_resolver
  22. * The controller resolver.
  23. * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
  24. * The translation manager.
  25. */
  26. public function __construct(ControllerResolverInterface $controller_resolver, TranslationInterface $string_translation) {
  27. $this->controllerResolver = $controller_resolver;
  28. $this->stringTranslation = $string_translation;
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function getTitle(Request $request, Route $route) {
  34. $route_title = NULL;
  35. // A dynamic title takes priority. Route::getDefault() returns NULL if the
  36. // named default is not set. By testing the value directly, we also avoid
  37. // trying to use empty values.
  38. if ($callback = $route->getDefault('_title_callback')) {
  39. $callable = $this->controllerResolver->getControllerFromDefinition($callback);
  40. $arguments = $this->controllerResolver->getArguments($request, $callable);
  41. $route_title = call_user_func_array($callable, $arguments);
  42. }
  43. elseif ($title = $route->getDefault('_title')) {
  44. $options = [];
  45. if ($context = $route->getDefault('_title_context')) {
  46. $options['context'] = $context;
  47. }
  48. $args = [];
  49. if (($raw_parameters = $request->attributes->get('_raw_variables'))) {
  50. foreach ($raw_parameters->all() as $key => $value) {
  51. $args['@' . $key] = $value;
  52. $args['%' . $key] = $value;
  53. }
  54. }
  55. if ($title_arguments = $route->getDefault('_title_arguments')) {
  56. $args = array_merge($args, (array) $title_arguments);
  57. }
  58. // Fall back to a static string from the route.
  59. $route_title = $this->t($title, $args, $options);
  60. }
  61. return $route_title;
  62. }
  63. }