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