-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathForwarder.php
More file actions
203 lines (185 loc) · 6.24 KB
/
Forwarder.php
File metadata and controls
203 lines (185 loc) · 6.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
<?php
namespace Drupal\quanthub_sdmx_proxy\Controller;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\quanthub_core\UserInfo;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\ServerException;
use Symfony\Bridge\PsrHttpMessage\HttpFoundationFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Main controller to forward requests.
*/
final class Forwarder extends ControllerBase {
/**
* The user info service.
*
* @var \Drupal\quanthub_core\UserInfo
*/
protected $userInfo;
/**
* The HTTP client.
*
* @var \GuzzleHttp\ClientInterface
*/
private $client;
/**
* The logger factory.
*
* @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
*/
protected $loggerFactory;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactory
*/
protected $configFactory;
/**
* Translates between Symfony and PRS objects.
*
* @var \Symfony\Bridge\PsrHttpMessage\HttpFoundationFactoryInterface
*/
private $foundationFactory;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('http_client'),
$container->get('psr7.http_foundation_factory'),
$container->get('logger.factory'),
$container->get('config.factory'),
$container->get('user_info')
);
}
/**
* {@inheritdoc}
*/
public function __construct(
ClientInterface $client,
HttpFoundationFactoryInterface $foundation_factory,
LoggerChannelFactoryInterface $logger_factory,
ConfigFactory $config_factory,
UserInfo $user_info,
) {
$this->client = $client;
$this->foundationFactory = $foundation_factory;
$this->loggerFactory = $logger_factory;
$this->configFactory = $config_factory;
$this->userInfo = $user_info;
}
/**
* Forwards incoming requests to the connected API.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The incoming request.
*
* @return \Symfony\Component\HttpFoundation\Response
* The response object.
*/
public function forward(Request $request): Response {
return $this->forwardInternal($request, getenv('SDMX_API_URL'));
}
/**
* Forwards incoming requests to the connected Download API.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The incoming request.
*
* @return \Symfony\Component\HttpFoundation\Response
* The response object.
*/
public function forwardDownload(Request $request): Response {
$response = $this->forwardInternal(
$request,
getenv('SDMX_DOWNLOAD_API_URL')
);
// Force set BOM due to absense of BOM management on Sigma API since v2.
$uri = $request->getRequestUri() ?? '';
if (
str_contains($uri, '/engine/data/sync/ott/')
&& str_contains($response->headers->get('content-disposition'), 'csv')
) {
$content = $response->getContent();
// Add UTF-8 BOM if not present (Excel compatibility).
if (strncmp($content, "\xEF\xBB\xBF", 3) !== 0) {
$content = "\xEF\xBB\xBF" . $content;
}
$response->setContent($content);
$response->headers->set('Content-Type', 'text/csv; charset=UTF-8');
return $response;
}
$content = $response->getContent();
if (!is_string($content) || $content === '') {
return $response;
}
return $response;
}
/**
* Forwards incoming requests to the connected API.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The incoming request.
* @param string $api_url
* API URL.
*
* @return \Symfony\Component\HttpFoundation\Response
* The response object.
*/
private function forwardInternal(Request $request, $api_url): Response {
$headers = [];
foreach ($request->headers->keys() as $key) {
if (($key == 'content-type') || str_starts_with($key, 'accept') || str_starts_with($key, 'quanthub')) {
$headers[$key] = $request->headers->get($key);
}
}
$headers['authorization'] = 'Bearer ' . $this->userInfo->getToken();
$options = [
'headers' => $headers,
];
if ($body = $request->getContent()) {
$options['body'] = $body;
}
try {
$uri = $request->query->get('uri');
$psr7_response = $this->client->request($request->getMethod(), $api_url . $uri, $options);
$response = $this->foundationFactory->createResponse($psr7_response);
// Force change the 'X-Frame-Options' to allow file downloads via iframe.
$response->headers->set('X-Frame-Options', 'SAMEORIGIN');
return $response;
}
catch (GuzzleException $exception) {
// Get the original response.
// Connection timeout error has no getResponse method.
// @todo . Make another catch expression to handle this type of errors.
$response = method_exists($exception, 'getResponse') ? $exception->getResponse() : NULL;
if (!is_null($response) && !is_null($response->getBody())) {
// Get the info returned from the remote server.
$response_info = $response->getBody()->getContents();
// Using FormattableMarkup allows for the use of <pre/> tags,
// giving a more readable log item.
$message = new FormattableMarkup('API connection error. Error details are as follows:<pre>@response</pre>', ['@response' => print_r(json_decode($response_info), TRUE)]);
// Log the error.
$this->loggerFactory->get('quanthub_sdmx_proxy')->warning($message);
return $this->foundationFactory->createResponse($exception->getResponse());
}
else {
$this->loggerFactory->get('quanthub_sdmx_proxy')->warning($exception->getMessage());
throw $exception;
}
}
catch (ClientException $exception) {
return $this->foundationFactory->createResponse($exception->getResponse());
}
catch (ServerException $exception) {
return $this->foundationFactory->createResponse($exception->getResponse());
}
}
}