2015-08-17 17:00:26 -07:00
< ? php
namespace Drupal\contextual ;
2018-11-23 12:29:20 +00:00
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 ;
2015-08-17 17:00:26 -07:00
use Symfony\Component\HttpFoundation\JsonResponse ;
use Symfony\Component\HttpFoundation\Request ;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException ;
/**
* Returns responses for Contextual module routes .
*/
2018-11-23 12:29:20 +00:00
class ContextualController implements ContainerInjectionInterface {
2015-08-17 17:00:26 -07:00
2018-11-23 12:29:20 +00:00
/**
* The renderer .
*
* @ var \Drupal\Core\Render\RendererInterface
*/
protected $renderer ;
/**
* Constructors a new ContextualController .
*
* @ param \Drupal\Core\Render\RendererInterface $renderer
* The renderer .
*/
public function __construct ( RendererInterface $renderer ) {
$this -> renderer = $renderer ;
}
/**
* { @ inheritdoc }
*/
public static function create ( ContainerInterface $container ) {
return new static (
$container -> get ( 'renderer' )
);
}
2015-08-17 17:00:26 -07:00
/**
* Returns the requested rendered contextual links .
*
* Given a list of contextual links IDs , render them . Hence this must be
* robust to handle arbitrary input .
*
2018-11-23 12:29:20 +00:00
* @ param \Symfony\Component\HttpFoundation\Request $request
* The Symfony request object .
2015-08-17 17:00:26 -07:00
*
* @ return \Symfony\Component\HttpFoundation\JsonResponse
* The JSON response .
2018-11-23 12:29:20 +00:00
*
* @ throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* Thrown when the request contains no ids .
*
* @ see contextual_preprocess ()
2015-08-17 17:00:26 -07:00
*/
public function render ( Request $request ) {
$ids = $request -> request -> get ( 'ids' );
if ( ! isset ( $ids )) {
throw new BadRequestHttpException ( t ( 'No contextual ids specified.' ));
}
2018-11-23 12:29:20 +00:00
$tokens = $request -> request -> get ( 'tokens' );
if ( ! isset ( $tokens )) {
throw new BadRequestHttpException ( t ( 'No contextual ID tokens specified.' ));
}
2017-04-13 15:53:35 +01:00
$rendered = [];
2018-11-23 12:29:20 +00:00
foreach ( $ids as $key => $id ) {
if ( ! isset ( $tokens [ $key ]) || ! Crypt :: hashEquals ( $tokens [ $key ], Crypt :: hmacBase64 ( $id , Settings :: getHashSalt () . \Drupal :: service ( 'private_key' ) -> get ()))) {
throw new BadRequestHttpException ( 'Invalid contextual ID specified.' );
}
2017-04-13 15:53:35 +01:00
$element = [
2015-08-17 17:00:26 -07:00
'#type' => 'contextual_links' ,
'#contextual_links' => _contextual_id_to_links ( $id ),
2017-04-13 15:53:35 +01:00
];
2018-11-23 12:29:20 +00:00
$rendered [ $id ] = $this -> renderer -> renderRoot ( $element );
2015-08-17 17:00:26 -07:00
}
return new JsonResponse ( $rendered );
}
}