-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCallService.php
More file actions
888 lines (744 loc) · 36.7 KB
/
CallService.php
File metadata and controls
888 lines (744 loc) · 36.7 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
<?php
namespace CommonGateway\CoreBundle\Service;
use App\Entity\Gateway as Source;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Psr7\Response;
use Psr\Log\LoggerInterface;
use Safe\Exceptions\JsonException;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\YamlEncoder;
/**
* Service to call external sources.
*
* This service provides a guzzle wrapper to work with sources in the common gateway.
*
* @Author Ruben van der Linde <ruben@conduction.nl>, Robert Zondervan <robert@conduction.nl>, Sarai Misidjan <sarai@conduction.nl>, Barry Brands <barry@conduction.nl>, Wilco Louwerse <wilco@conduction.nl>
*
* @license EUPL <https://github.com/ConductionNL/contactcatalogus/blob/master/LICENSE.md>
*
* @category Service
*/
class CallService
{
/**
* @var AuthenticationService $authenticationService
*/
private AuthenticationService $authenticationService;
/**
* @var Client $client
*/
private Client $client;
/**
* @var EntityManagerInterface $entityManager
*/
private EntityManagerInterface $entityManager;
/**
* @var FileService $fileService
*/
private FileService $fileService;
/**
* @var MappingService $mappingService
*/
private MappingService $mappingService;
/**
* @var SessionInterface $session
*/
private SessionInterface $session;
/**
* @var LoggerInterface $callLogger
*/
private LoggerInterface $callLogger;
/**
* The source currently used for doing calls.
*
* @var Source
*/
private Source $source;
/**
* The constructor sets al needed variables.
*
* @param AuthenticationService $authenticationService The authentication service
* @param EntityManagerInterface $entityManager The entity manager
* @param FileService $fileService The file service
* @param MappingService $mappingService The mapping service
* @param SessionInterface $session The current session.
* @param LoggerInterface $callLogger The logger for the call channel.
*/
public function __construct(
AuthenticationService $authenticationService,
EntityManagerInterface $entityManager,
FileService $fileService,
MappingService $mappingService,
SessionInterface $session,
LoggerInterface $callLogger
) {
$this->authenticationService = $authenticationService;
$this->client = new Client([]);
$this->entityManager = $entityManager;
$this->fileService = $fileService;
$this->mappingService = $mappingService;
$this->session = $session;
$this->callLogger = $callLogger;
}//end __construct()
/**
* Writes the certificate and ssl keys to disk, returns the filenames.
*
* @param array $config The configuration as stored in the source
*
* @return void
*/
public function getCertificate(array &$config)
{
if (isset($config['cert']) === true) {
if (is_array($config['cert']) === true) {
$config['cert'][0] = $this->fileService->writeFile('certificate', $config['cert'][0]);
} else if (is_string($config['cert'])) {
$config['cert'] = $this->fileService->writeFile('certificate', $config['cert']);
}
}
if (isset($config['ssl_key']) === true) {
if (is_array($config['ssl_key']) === true) {
$config['ssl_key'][0] = $this->fileService->writeFile('privateKey', $config['ssl_key'][0]);
} else if (is_string($config['ssl_key']) === true) {
$config['ssl_key'] = $this->fileService->writeFile('privateKey', $config['ssl_key']);
}
}
if (isset($config['verify']) === true && is_string($config['verify']) === true) {
$config['verify'] = $this->fileService->writeFile('verify', $config['verify']);
}
}//end getCertificate()
/**
* Removes certificates and private keys from disk if they are not necessary anymore.
*
* @param array $config The configuration with filenames
*
* @return void
*/
public function removeFiles(array $config): void
{
if (isset($config['cert']) === true) {
$filename = is_array($config['cert']) === true ? $config['cert'][0] : $config['cert'];
$this->fileService->removeFile($filename);
}
if (isset($config['ssl_key']) === true) {
$filename = is_array($config['ssl_key']) === true ? $config['ssl_key'][0] : $config['ssl_key'];
$this->fileService->removeFile($filename);
}
if (isset($config['verify']) === true && is_string($config['verify']) === true) {
$this->fileService->removeFile($config['verify']);
}
}//end removeFiles()
/**
* Removes empty headers and sets array to string values.
*
* @param array $headers Http headers
*
* @return array|null
*/
private function removeEmptyHeaders(array $headers): ?array
{
foreach ($headers as $key => $header) {
if (is_array($header) === true && count($header) < 2) {
if (empty($header[0]) === false) {
$headers[$key] = $header[0];
continue;
}
unset($headers[$key]);
}
}//end foreach
return $headers;
}//end removeEmptyHeaders()
/**
* Handles the exception if the call triggered one.
*
* @param ServerException|ClientException|RequestException|Exception $exception
* @param string $endpoint
*
* @throws Exception
*
* @return Response $this->handleEndpointsConfigIn()
*/
private function handleCallException($exception, string $endpoint): Response
{
if (method_exists(get_class($exception), 'getResponse') === true
&& $exception->getResponse() !== null
) {
$responseContent = $exception->getResponse()->getBody()->getContents();
}
$this->callLogger->error('Request failed with error '.$exception->getMessage().' and body '.($responseContent ?? null));
return $this->handleEndpointsConfigIn($endpoint, null, $exception, ($responseContent ?? null));
}//end handleCallException()
/**
* Calls a source according to given configuration.
*
* @param Source $source The source to call.
* @param string $endpoint The endpoint on the source to call.
* @param string $method The method on which to call the source.
* @param array $config The additional configuration to call the source.
* @param bool $asynchronous Whether or not to call the source asynchronously.
* @param bool $createCertificates Whether or not to create certificates for this source.
*
* @throws Exception
*
* @return Response
*/
public function call(
Source $source,
string $endpoint = '',
string $method = 'GET',
array $config = [],
bool $asynchronous = false,
bool $createCertificates = true,
bool $overruleAuth = false
) {
$this->source = $source;
$this->session->set('source', $this->source->getId()->toString());
$this->callLogger->info('Calling source '.$this->source->getName());
if ($this->source->getIsEnabled() === null || $this->source->getIsEnabled() === false) {
throw new HttpException('409', "This source is not enabled: {$this->source->getName()}");
}
if (empty($this->source->getLocation()) === true) {
throw new HttpException('409', "This source has no location: {$this->source->getName()}");
}
if (isset($config['headers']['Content-Type']) === true) {
$overwriteContentType = $config['headers']['Content-Type'];
}
if (isset($config['headers']['content-type']) === true) {
$overwriteContentType = $config['headers']['content-type'];
}
if (empty($this->source->getConfiguration()) === false) {
$config = array_merge_recursive($config, $this->source->getConfiguration());
}
if (isset($config['headers']) === false) {
$config['headers'] = [];
}
$url = $this->source->getLocation().$endpoint;
// Set authentication if needed.
$createCertificates && $this->getCertificate($config);
$requestInfo = [
'url' => $url,
'method' => $method,
];
if ($overruleAuth === false) {
$config = array_merge_recursive($this->getAuthentication($config, $requestInfo), $config);
}
// Backwards compatible, $this->source->getHeaders = deprecated.
$config['headers'] = array_merge(($this->source->getHeaders() ?? []), $config['headers']);
if (isset($overwriteContentType) === true) {
$config['headers']['Content-Type'] = $overwriteContentType;
}
// Make sure we do not have an array of accept headers
if (isset($config['headers']['accept']) === true && is_array($config['headers']['accept']) === true) {
$config['headers']['accept'] = $config['headers']['accept'][0];
}
$parsedUrl = parse_url($this->source->getLocation());
$config['headers']['host'] = $parsedUrl['host'];
$config['headers'] = $this->removeEmptyHeaders($config['headers']);
$config = $this->handleEndpointsConfigOut($endpoint, $config);
// Guzzle sets the Content-Type self when using multipart.
if (isset($config['multipart']) === true && isset($config['headers']['Content-Type']) === true) {
unset($config['headers']['Content-Type']);
}
// Guzzle sets the Content-Type self when using multipart.
if (isset($config['multipart']) === true && isset($config['headers']['content-type']) === true) {
unset($config['headers']['content-type']);
}
$this->callLogger->info('Calling url '.$url);
$this->callLogger->debug('Call configuration: ', $config);
// Let's make the call.
$this->source->setLastCall(new \DateTime());
// The $this->source here gets persisted but the flush needs be executed in a Service where this ->call() function has been executed.
// Because we don't want to flush/update the Source each time this ->call() function gets executed for performance reasons.
$this->entityManager->persist($this->source);
try {
if ($asynchronous === false) {
$response = $this->client->request($method, $url, $config);
} else {
return $this->client->requestAsync($method, $url, $config);
}
$this->source->setStatus($response->getStatusCode());
$this->entityManager->persist($this->source);
$this->callLogger->info("Request to $url successful");
$this->callLogger->notice(
"$method Request to $url returned {$response->getStatusCode()}",
[
'sourceCall' => $this->sourceCallLogData(['method' => $method, 'url' => $url, 'response' => $response], $config),
]
);
} catch (ServerException | ClientException | RequestException | Exception $exception) {
$this->callLogger->error(
'Request failed with error '.$exception,
[
'sourceCall' => $this->sourceCallLogData(['method' => $method, 'url' => $url, 'response' => ($response ?? null)], $config),
]
);
if (empty($response) === false) {
$this->source->setStatus($response->getStatusCode());
}
if (empty($response) === true) {
$this->source->setStatus(500);
}
$this->entityManager->persist($this->source);
return $this->handleCallException($exception, $endpoint);
} catch (GuzzleException $exception) {
$this->callLogger->error(
'Request failed with error '.$exception,
[
'sourceCall' => $this->sourceCallLogData(['method' => $method, 'url' => $url, 'response' => $response ?? null], $config),
],
);
if (empty($response) === false) {
$this->source->setStatus($response->getStatusCode());
}
if (empty($response) === true) {
$this->source->setStatus(500);
}
$this->entityManager->persist($this->source);
return $this->handleEndpointsConfigIn($endpoint, null, $exception, null);
}//end try
$createCertificates && $this->removeFiles($config);
return $this->handleEndpointsConfigIn($endpoint, $response, null, null);
}//end call()
/**
* Uses input parameters to create array with data used for creating a log after any call to a Source.
* If the source->loggingConfig allows logging.
*
* @param array $requestInfo The info of the current request call done on a source, can contain: 'method' of the call, 'url' of the call & 'response' that the call returned.
* @param array $config The additional configuration used to call the source.
*
* @return array The array with data to use for creating a log.
*/
private function sourceCallLogData(array $requestInfo, array $config): array
{
$loggingConfig = $this->source->getLoggingConfig();
$sourceCallData = [];
if (empty($loggingConfig['callMethod']) === false) {
$sourceCallData['callMethod'] = $requestInfo['method'];
}
if (empty($loggingConfig['callUrl']) === false) {
$sourceCallData['callUrl'] = $requestInfo['url'];
}
if (empty($loggingConfig['callQuery']) === false) {
$sourceCallData['callQuery'] = ($config['query'] ?? '');
}
if (empty($loggingConfig['callContentType']) === false) {
$sourceCallData['callContentType'] = ($config['headers']['Content-Type'] ?? $config['headers']['content-type'] ?? '');
}
if (empty($loggingConfig['callBody']) === false) {
$sourceCallData['callBody'] = ($config['body'] ?? '');
}
if (empty($loggingConfig['responseStatusCode']) === false) {
$sourceCallData['responseStatusCode'] = $requestInfo['response'] !== null ? $requestInfo['response']->getStatusCode() : '';
}
if (empty($loggingConfig['responseContentType']) === false) {
$sourceCallData['responseContentType'] = $requestInfo['response'] !== null && method_exists($requestInfo['response'], 'getContentType') === true ? $requestInfo['response']->getContentType() : '';
}
if (empty($loggingConfig['responseBody']) === false) {
$sourceCallData['responseBody'] = '';
if ($requestInfo['response'] !== null && $requestInfo['response']->getBody() !== null) {
$sourceCallData['responseBody'] = $requestInfo['response']->getBody()->getContents();
// Make sure we can use ->getBody()->getContent() again after this^.
$requestInfo['response']->getBody()->rewind();
}
}
$sourceCallData['maxCharCountBody'] = ($loggingConfig['maxCharCountBody'] ?? 500);
$sourceCallData['maxCharCountErrorBody'] = ($loggingConfig['maxCharCountErrorBody'] ?? 2000);
return $sourceCallData;
}//end sourceCallLogData()
/**
* Handles the endpointsConfig of a Source before we do an api-call.
*
* @param string $endpoint The endpoint used to do an api-call on the source.
* @param array $config The configuration for an api-call we might want to change.
*
* @return array The configuration array.
*/
private function handleEndpointsConfigOut(string $endpoint, array $config): array
{
$this->callLogger->info('Handling outgoing configuration for endpoints');
$endpointsConfig = $this->source->getEndpointsConfig();
if (empty($endpointsConfig) === true) {
return $config;
}
// Let's check if the endpoint used on this source has "out" configuration in the EndpointsConfig of the source.
if (array_key_exists($endpoint, $endpointsConfig) === true && array_key_exists('out', $endpointsConfig[$endpoint]) === true) {
$endpointConfigOut = $endpointsConfig[$endpoint]['out'];
} else if (array_key_exists('global', $endpointsConfig) === true && array_key_exists('out', $endpointsConfig['global']) === true) {
$endpointConfigOut = $endpointsConfig['global']['out'];
}
if (isset($endpointConfigOut) === true) {
$config = $this->handleEndpointConfigOut($config, $endpointConfigOut, 'query');
$config = $this->handleEndpointConfigOut($config, $endpointConfigOut, 'headers');
$config = $this->handleEndpointConfigOut($config, $endpointConfigOut, 'body');
}
return $config;
}//end handleEndpointsConfigOut()
/**
* Handles endpointConfig for a specific endpoint on a source and a specific configuration key like: 'query' or 'headers'.
* Before we do an api-call.
*
* @param array $config The configuration for an api-call we might want to change.
* @param array $endpointConfigOut The endpointConfig 'out' of a specific endpoint and source.
* @param string $configKey The specific configuration key to check if its data needs to be changed and if so, change the data for.
*
* @return array The configuration array.
*/
private function handleEndpointConfigOut(array $config, array $endpointConfigOut, string $configKey): array
{
$this->callLogger->info('Handling outgoing configuration for endpoint');
if (array_key_exists($configKey, $config) === false || array_key_exists($configKey, $endpointConfigOut) === false) {
return $config;
}
if (array_key_exists('mapping', $endpointConfigOut[$configKey])) {
$mapping = $this->entityManager->getRepository('App:Mapping')->findOneBy(['reference' => $endpointConfigOut[$configKey]['mapping']]);
if ($mapping === null) {
$this->callLogger->error("Could not find mapping with reference {$endpointConfigOut[$configKey]['mapping']} while handling $configKey EndpointConfigOut for a Source");
return $config;
}//end if
if (is_string($config[$configKey]) === true) {
try {
$body = \Safe\json_decode($config[$configKey]);
} catch (JsonException $exception) {
$xmlEncoder = new XmlEncoder([]);
$body = $xmlEncoder->decode($config[$configKey], 'xml');
} catch (Exception $exception) {
$this->callLogger->error("Could not map with mapping {$endpointConfigOut[$configKey]['mapping']} while handling $configKey EndpointConfigOut for a Source. Body could not be decoded. ".$exception->getMessage());
}
try {
$body = $this->mappingService->mapping($mapping, $body);
$config[$configKey] = \Safe\json_encode($body);
unset($config['headers']['Content-Type'], $config['headers']['Accept'], $config['headers']['accept'], $config['headers']['content-type']);
$config['headers']['content-type'] = 'application/json';
} catch (Exception | LoaderError | SyntaxError $exception) {
$this->callLogger->error("Could not map with mapping {$endpointConfigOut[$configKey]['mapping']} while handling $configKey EndpointConfigOut for a Source. ".$exception->getMessage());
}
}//end if
if (is_array($config[$configKey]) === true) {
try {
$config[$configKey] = $this->mappingService->mapping($mapping, $config[$configKey]);
} catch (Exception | LoaderError | SyntaxError $exception) {
$this->callLogger->error("Could not map with mapping {$endpointConfigOut[$configKey]['mapping']} while handling $configKey EndpointConfigOut for a Source. ".$exception->getMessage());
}
}//end if
}//end if
return $config;
}//end handleEndpointConfigOut()
/**
* Handles the endpointsConfig of a Source after we did an api-call.
* See FileSystemService->handleEndpointsConfigIn() for how we handle this on FileSystem sources.
*
* @param string $endpoint The endpoint used to do an api-call on the source.
* @param Response|null $response The response of an api-call we might want to change.
* @param Exception|null $exception The Exception thrown as response of an api-call that we might want to change.
* @param string|null $responseContent The response content of an api-call that threw an Exception that we might want to change.
*
* @throws Exception
*
* @return Response The response.
*/
private function handleEndpointsConfigIn(string $endpoint, ?Response $response, ?Exception $exception = null, ?string $responseContent = null): Response
{
$this->callLogger->info('Handling incoming configuration for endpoints');
$endpointsConfig = $this->source->getEndpointsConfig();
if (empty($endpointsConfig)) {
if ($response !== null) {
return $response;
}
if ($exception !== null) {
throw $exception;
}
}
if (array_key_exists($endpoint, $endpointsConfig) === true
&& array_key_exists('in', $endpointsConfig[$endpoint]) === false
|| array_key_exists('global', $endpointsConfig) === true
&& array_key_exists('in', $endpointsConfig['global']) === false
) {
if ($response !== null) {
return $response;
}
if ($exception !== null) {
throw $exception;
}
}//end if
// Let's check if the endpoint used on this source has "in" configuration in the EndpointsConfig of the source.
if (array_key_exists($endpoint, $endpointsConfig) === true && array_key_exists('in', $endpointsConfig[$endpoint])) {
$endpointConfigIn = $endpointsConfig[$endpoint]['in'];
} else if (array_key_exists('global', $endpointsConfig) === true && array_key_exists('in', $endpointsConfig['global'])) {
$endpointConfigIn = $endpointsConfig['global']['in'];
}
// Let's check if we are dealing with an Exception and not a Response.
if (isset($endpointConfigIn) === true && $response === null && $exception !== null) {
return $this->handleEndpointConfigInEx($endpointConfigIn, $exception, $responseContent);
}
// Handle endpointConfigIn for a Response.
if (isset($endpointConfigIn) === true && $response !== null) {
$headers = $this->handleEndpointConfigIn($response->getHeaders(), $endpointConfigIn, 'headers');
$body = $this->handleEndpointConfigIn($response->getBody(), $endpointConfigIn, 'body');
// Todo: handle content-type.
is_array($body) === true && $body = json_encode($body);
return new Response($response->getStatusCode(), $headers, $body, $response->getProtocolVersion());
}
return $response;
}//end handleEndpointsConfigIn()
/**
* Will check if we have to handle EndpointConfigIn on an Exception response.
*
* @param array $endpointConfigIn The endpointConfig 'in' of a specific endpoint and source.
* @param Exception $exception The Exception thrown as response of an api-call that we might want to change.
* @param string|null $responseContent The response content of an api-call that threw an Exception that we might want to change.
*
* @throws Exception
*
* @return Response The Response.
*/
private function handleEndpointConfigInEx(array $endpointConfigIn, Exception $exception, ?string $responseContent): Response
{
// Check if error is set and the exception has a getResponse() otherwise just throw the exception.
if (array_key_exists('error', $endpointConfigIn) === false
|| method_exists(get_class($exception), 'getResponse') === false
|| $exception->getResponse() === null
) {
throw $exception;
}
$body = json_decode($responseContent, true);
// Create exception array.
$exceptionArray = [
'statusCode' => $exception->getResponse()->getStatusCode(),
'headers' => $exception->getResponse()->getHeaders(),
'body' => ($body ?? $exception->getResponse()->getBody()->getContents()),
'message' => $exception->getMessage(),
];
$headers = $this->handleEndpointConfigIn($exception->getResponse()->getHeaders(), $endpointConfigIn, 'headers');
$error = $this->handleEndpointConfigIn($exceptionArray, $endpointConfigIn, 'error');
if (array_key_exists('statusCode', $error)) {
$statusCode = $error['statusCode'];
unset($error['statusCode']);
}
$error = json_encode($error);
return new Response(($statusCode ?? $exception->getCode()), $headers, $error, $exception->getResponse()->getProtocolVersion());
}//end handleEndpointConfigInEx()
/**
* Handles endpointConfig for a specific endpoint on a source and a specific response property like: 'headers' or 'body'.
* After we did an api-call.
* See FileSystemService->handleEndpointConfigIn() for how we handle this on FileSystem sources.
*
* @param mixed $responseData Some specific data from the response we might want to change. This data should match with the correct $responseProperty.
* @param array $endpointConfigIn The endpointConfig 'in' of a specific endpoint and source.
* @param string $responseProperty The specific response property to check if its data needs to be changed and if so, change the data for.
*
* @return array The configuration array.
*/
private function handleEndpointConfigIn($responseData, array $endpointConfigIn, string $responseProperty): array
{
$this->callLogger->info('Handling incoming configuration for endpoint');
if (empty($responseData) === true || array_key_exists($responseProperty, $endpointConfigIn) === false) {
return $responseData;
}
if (array_key_exists('mapping', $endpointConfigIn[$responseProperty]) === true) {
$mapping = $this->entityManager->getRepository('App:Mapping')->findOneBy(['reference' => $endpointConfigIn[$responseProperty]['mapping']]);
if ($mapping === null) {
$this->callLogger->error("Could not find mapping with reference {$endpointConfigIn[$responseProperty]['mapping']} while handling $responseProperty EndpointConfigIn for a Source.");
return $responseData;
}
if (is_array($responseData) === false) {
$responseData = json_decode($responseData->getContents(), true);
}
try {
$responseData = $this->mappingService->mapping($mapping, $responseData);
} catch (Exception | LoaderError | SyntaxError $exception) {
$this->callLogger->error("Could not map with mapping {$endpointConfigIn[$responseProperty]['mapping']} while handling $responseProperty EndpointConfigIn for a Source. ".$exception->getMessage());
}
}//end if
return $responseData;
}//end handleEndpointConfigIn()
/**
* Determine the content type of response.
*
* @param Response $response The response to determine the content type for
*
* @return string The (assumed) content type of the response
*/
private function getContentType(Response $response): string
{
$this->callLogger->debug('Determine content type of response');
// Switch voor obejct.
if (isset($response->getHeader('content-type')[0]) === true) {
$contentType = $response->getHeader('content-type')[0];
}
if (isset($contentType) === false || empty($contentType) === true) {
$contentType = $this->source->getAccept();
if ($contentType === null) {
$this->callLogger->warning('Accept of the Source '.$this->source->getReference().' === null');
return 'application/json';
}
}
return $contentType;
}//end getContentType()
/**
* Decodes a response based on the source it belongs to.
*
* @param Source $source The source that has been called
* @param Response $response The response to decode
*
* @throws Exception Thrown if the response does not fit any supported content type
*
* @return array|string The decoded response
*/
public function decodeResponse(
Source $source,
Response $response,
?string $contentType = 'application/json'
) {
$this->source = $source;
$this->callLogger->info('Decoding response content');
// resultaat omzetten.
// als geen content-type header dan content-type header is accept header.
$responseBody = $response->getBody()->getContents();
if (isset($responseBody) === false || empty($responseBody) === true) {
if ($response->getStatusCode() === 204) {
$this->callLogger->info('Responses with status code 204 have no response body.');
return [];
}
if (in_array($response->getStatusCode(), [200, 201]) === true) {
$this->callLogger->warning('Cannot decode an empty response body (status = 200 or 201).');
return [];
}
$this->callLogger->error('Cannot decode an empty response body.');
return [];
}
// This if is statement prevents binary code from being used a string.
if (in_array(
$contentType,
[
'application/pdf',
'application/pdf; charset=utf-8',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf-8',
'application/msword',
'image/jpeg',
'image/png',
]
) === false
) {
$this->callLogger->debug('Response content: '.$responseBody);
}
$xmlEncoder = new XmlEncoder(['xml_root_node_name' => ($this->configuration['apiSource']['location']['xmlRootNodeName'] ?? 'response')]);
$yamlEncoder = new YamlEncoder();
// This if statement is so that any given $contentType other than json doesn't get overwritten here.
if ($contentType === 'application/json') {
$contentType = ($this->getContentType($response) ?? $contentType);
}
switch ($contentType) {
case 'text/plain':
return $responseBody;
case 'text/yaml':
case 'text/x-yaml':
case 'text/yaml; charset=utf-8':
return $yamlEncoder->decode($responseBody, 'yaml');
case 'text/xml':
case 'text/xml; charset=utf-8':
case 'application/pdf':
case 'application/pdf; charset=utf-8':
case 'application/msword':
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf-8':
case 'image/jpeg':
case 'image/png':
$this->callLogger->debug('Response content: binary code..');
return base64_encode($responseBody);
case 'application/xml':
case 'application/xml; charset=utf-8':
return $xmlEncoder->decode($responseBody, 'xml');
case 'application/json':
case 'application/json; charset=utf-8':
default:
$result = json_decode($responseBody, true);
}//end switch
if (isset($result) === true) {
return $result;
}
// Fallback: if the json_decode didn't work, try to decode XML, if that doesn't work an error is thrown.
try {
$result = $xmlEncoder->decode($responseBody, 'xml');
return $result;
} catch (Exception $exception) {
$this->callLogger->error('Could not decode body, content type could not be determined');
throw new Exception('Could not decode body, content type could not be determined');
}//end try
}//end decodeResponse()
/**
* Determines the authentication procedure based upon a source.
*
* @param array|null $config The optional, updated Source configuration array.
* @param array|null $requestInfo The optional, given request info.
*
* @return array The config parameters needed to authenticate on the source
*/
private function getAuthentication(?array $config = null, ?array $requestInfo = []): array
{
return $this->authenticationService->getAuthentication($this->source, $config, $requestInfo);
}//end getAuthentication()
/**
* Fetches all pages for a source and merges the result arrays to one array.
*
* @TODO: This is based on some assumptions
*
* @param Source $source The source to call
* @param string $endpoint The endpoint on the source to call
* @param array $config The additional configuration to call the source
*
* @return array The array of results
*/
public function getAllResults(Source $source, string $endpoint = '', array $config = []): array
{
$this->source = $source;
$this->callLogger->info('Fetch all data from source and combine the results into one array');
$errorCount = 0;
$pageCount = 1;
$results = [];
$previousResult = [];
while ($errorCount < 5) {
try {
$config['query']['page'] = $pageCount;
$pageCount++;
$response = $this->call($source, $endpoint, 'GET', $config);
$decodedResponse = $this->decodeResponse($source, $response);
if ($decodedResponse === []
|| isset($decodedResponse['data']) === true && $decodedResponse['data'] === []
|| isset($decodedResponse['results']) === true && $decodedResponse['results'] === []
|| isset($decodedResponse['items']) === true && $decodedResponse['items'] === []
|| isset($decodedResponse['result']['instance']['rows']) === true && $decodedResponse['result']['instance']['rows'] === []
|| isset($decodedResponse['page']) === true && $decodedResponse['page'] !== ($pageCount - 1)
|| $decodedResponse == $previousResult
) {
break;
}
$previousResult = $decodedResponse;
} catch (Exception $exception) {
$errorCount++;
$this->callLogger->error($exception->getMessage());
}//end try
if (isset($decodedResponse['results']) === true) {
$results = array_merge($decodedResponse['results'], $results);
} else if (isset($decodedResponse['items']) === true) {
$results = array_merge($decodedResponse['items'], $results);
} else if (isset($decodedResponse['data']) === true) {
$results = array_merge($decodedResponse['data'], $results);
} else if (isset($decodedResponse['result']['instance']['rows']) === true) {
$results = array_merge($decodedResponse['result']['instance']['rows'], $results);
} else if (isset($decodedResponse[0]) === true) {
$results = array_merge($decodedResponse, $results);
}
}//end while
return $results;
}//end getAllResults()
}//end class