coveo-1.0.0-alpha1/src/Controller/SearchTokenRefresh.php
src/Controller/SearchTokenRefresh.php
<?php
declare(strict_types=1);
namespace Drupal\coveo\Controller;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Logger\LoggerChannelTrait;
use Drupal\coveo\Entity\CoveoSearchComponent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Search token refresh controller.
*/
class SearchTokenRefresh extends ControllerBase {
use LoggerChannelTrait;
public function __construct(ConfigFactoryInterface $configFactory) {
$this->configFactory = $configFactory;
}
/**
* {@inheritDoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory'),
);
}
/**
* Controller callback for refreshing a search token for a user.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* Current request.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* Response containing new search token for a user.
*/
public function getNewToken(Request $request): JsonResponse {
if (!$request->query->has('search')) {
throw new NotFoundHttpException();
}
else {
$search = CoveoSearchComponent::load($request->get('search'));
if (!$search) {
throw new NotFoundHttpException();
}
}
// @todo limit token generation to certain backends?
$token = $search->getToken($request, $this->currentUser());
if ($token) {
return new JsonResponse(['token' => $token]);
}
return new JsonResponse('Problem communicating with search', 500);
}
}
