manifest/web/modules/custom/etherpad_api/src/Controller/EtherpadApiController.php

52 lines
1.5 KiB
PHP

<?php
namespace Drupal\etherpad_api\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ClientException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Returns responses for Etherpad API routes.
*/
class EtherpadApiController extends ControllerBase {
protected $httpClient;
protected $config;
public function __construct(ClientInterface $http_client, ConfigFactoryInterface $config_factory) {
$this->httpClient = $http_client;
$this->configFactory = $config_factory;
}
public static function create(ContainerInterface $container) {
return new static($container->get('http_client'), $container->get('config.factory'));
}
/**
* Builds the response.
*/
public function build($components, Request $request) {
$baseUrl = $this->config('etherpad_api.settings')->get('url');
$apiKey = $this->config('etherpad_api.settings')->get('key');
$params = $request->getQueryString();
if ($params) {
$params .= "&apikey=$apiKey";
} else {
$params = "apikey=$apiKey";
}
$uri = $baseUrl . str_replace(':', '/', $components) . "?$params";
$method = $request->getMethod();
try {
return $this->httpClient->request($method, $uri);
} catch (ClientException $exception) {
return new Response($exception->getMessage(), $exception->getCode());
}
}
}