ContextualController.php in Drupal 10
File
core/modules/contextual/src/ContextualController.php
View source
<?php
namespace Drupal\contextual;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Site\Settings;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class ContextualController implements ContainerInjectionInterface {
protected $renderer;
public function __construct(RendererInterface $renderer) {
$this->renderer = $renderer;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('renderer'));
}
public function render(Request $request) {
if (!$request->request
->has('ids')) {
throw new BadRequestHttpException('No contextual ids specified.');
}
$ids = $request->request
->all('ids');
if (!$request->request
->has('tokens')) {
throw new BadRequestHttpException('No contextual ID tokens specified.');
}
$tokens = $request->request
->all('tokens');
$rendered = [];
foreach ($ids as $key => $id) {
if (!isset($tokens[$key]) || !hash_equals($tokens[$key], Crypt::hmacBase64($id, Settings::getHashSalt() . \Drupal::service('private_key')
->get()))) {
throw new BadRequestHttpException('Invalid contextual ID specified.');
}
$element = [
'#type' => 'contextual_links',
'#contextual_links' => _contextual_id_to_links($id),
];
$rendered[$id] = $this->renderer
->renderRoot($element);
}
return new JsonResponse($rendered);
}
}