ContextualController.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Drupal\contextual;
  3. use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
  4. use Drupal\Core\Render\RendererInterface;
  5. use Symfony\Component\DependencyInjection\ContainerInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  9. /**
  10. * Returns responses for Contextual module routes.
  11. */
  12. class ContextualController implements ContainerInjectionInterface {
  13. /**
  14. * The renderer.
  15. * @var \Drupal\Core\Render\RendererInterface
  16. */
  17. protected $render;
  18. /**
  19. * Constructors a new ContextualController
  20. *
  21. * @param \Drupal\Core\Render\RendererInterface $renderer
  22. * The renderer.
  23. */
  24. public function __construct(RendererInterface $renderer) {
  25. $this->renderer = $renderer;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public static function create(ContainerInterface $container) {
  31. return new static(
  32. $container->get('renderer')
  33. );
  34. }
  35. /**
  36. * Returns the requested rendered contextual links.
  37. *
  38. * Given a list of contextual links IDs, render them. Hence this must be
  39. * robust to handle arbitrary input.
  40. *
  41. * @see contextual_preprocess()
  42. *
  43. * @return \Symfony\Component\HttpFoundation\JsonResponse
  44. * The JSON response.
  45. */
  46. public function render(Request $request) {
  47. $ids = $request->request->get('ids');
  48. if (!isset($ids)) {
  49. throw new BadRequestHttpException(t('No contextual ids specified.'));
  50. }
  51. $rendered = [];
  52. foreach ($ids as $id) {
  53. $element = [
  54. '#type' => 'contextual_links',
  55. '#contextual_links' => _contextual_id_to_links($id),
  56. ];
  57. $rendered[$id] = $this->renderer->renderRoot($element);
  58. }
  59. return new JsonResponse($rendered);
  60. }
  61. }