Skip to content

Instantly share code, notes, and snippets.

@kevinquillen
Last active January 30, 2018 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinquillen/e5bb410c88ef64b24b14394423e9b211 to your computer and use it in GitHub Desktop.
Save kevinquillen/e5bb410c88ef64b24b14394423e9b211 to your computer and use it in GitHub Desktop.
Creating a route that makes a call from the server to an external service which is firewalled, with data sent back to the caller (like a ReactJS component)
<?php
namespace Drupal\harlib_search\Controller;
use Drupal\Core\Controller\ControllerBase;
use GuzzleHttp\Client;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use GuzzleHttp\Exception\RequestException;
use Symfony\Component\HttpFoundation\Response;
/**
* Class SearchController.
*
* @package Drupal\harlib_search\Controller
*/
class SearchController extends ControllerBase {
/**
* The base url to do searches against.
*
* @var string
*/
protected $baseSearchUrl = "http://YOUR_ENDPOINT_HERE";
/**
* Symfony\Component\HttpFoundation\RequestStack definition.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* GuzzleHttp\Client definition.
*
* @var \GuzzleHttp\Client
*/
protected $httpClient;
/**
* Psr\Log\LoggerInterface definition.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* Constructor for our class.
*/
public function __construct(RequestStack $request_stack, Client $http_client, LoggerInterface $logger) {
$this->requestStack = $request_stack;
$this->httpClient = $http_client;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('request_stack'),
$container->get('http_client'),
$container->get('logger.factory')->get('harlib_search')
);
}
/**
* Controller action. Show the ReactJS component.
*/
public function index() {
return [
'#theme' => 'harlib_search',
];
}
/**
* Fetch results from Hollis.
*
* @return \Symfony\Component\HttpFoundation\Response
* A Symfony response object.
*/
public function results() {
$data = '';
$uri = $this->baseSearchUrl . $this->requestStack->getCurrentRequest()->getQueryString();
try {
$response = $this->httpClient->get($uri, ['headers' => ['Accept' => 'text/xml']]);
$data = (string) $response->getBody();
}
catch (RequestException $e) {
$this->logger->error("Error returned from HOLLIS search, error was @error", ['@error' => $e->getMessage()]);
}
return new Response($data, 200);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment