From 7fe34ad6c4da72f59d2e8d00ed8a363d57e7f19c Mon Sep 17 00:00:00 2001 From: Aaron Gerig Date: Wed, 29 May 2019 09:28:28 +0200 Subject: [PATCH] implement imprint API --- src/Api/ImprintApi/ImprintApi.php | 68 ++++++++++++++++++ src/Api/ImprintApi/ImprintApiCached.php | 84 ++++++++++++++++++++++ src/Api/ImprintApi/ImprintApiInterface.php | 29 ++++++++ src/Resources/config/services.yml | 12 ++++ 4 files changed, 193 insertions(+) create mode 100644 src/Api/ImprintApi/ImprintApi.php create mode 100644 src/Api/ImprintApi/ImprintApiCached.php create mode 100644 src/Api/ImprintApi/ImprintApiInterface.php diff --git a/src/Api/ImprintApi/ImprintApi.php b/src/Api/ImprintApi/ImprintApi.php new file mode 100644 index 0000000..1341b98 --- /dev/null +++ b/src/Api/ImprintApi/ImprintApi.php @@ -0,0 +1,68 @@ + $this->baseUri, + 'headers' => ['ACCEPT' => 'application/json'], + ]); + + $uri = '/api/internal/imprint'; + + if (!empty($addresses)) { + $uri .= sprintf('/%s', implode('/', $addresses)); + } + + $response = $client->get($uri); + + return $this->parseResponse($response); + } + + /** + * Parses the API JSON response + * + * @param ResponseInterface $response + * @return array|null + */ + private function parseResponse(ResponseInterface $response): ?array + { + if ($response->getStatusCode() < 300) { + $result = (string) $response->getBody(); + $data = json_decode($result, true); + + if (json_last_error() !== JSON_ERROR_NONE) { + throw new BadRequestHttpException('Invalid json body: ' . json_last_error_msg()); + } + + return is_array($data) ? $data : []; + } + + return null; + } +} diff --git a/src/Api/ImprintApi/ImprintApiCached.php b/src/Api/ImprintApi/ImprintApiCached.php new file mode 100644 index 0000000..91edf9c --- /dev/null +++ b/src/Api/ImprintApi/ImprintApiCached.php @@ -0,0 +1,84 @@ +cacheHelper = $cacheHelper; + $this->decorated = $decorated; + } + + /** + * {@inheritdoc} + */ + public function getData(array $addresses = []): ?array + { + $cacheKey = $this->getCacheKey($addresses); + + if (!$result = $this->cacheHelper->load($cacheKey)) { + $result = $this->decorated->getData($addresses); + + $this->cacheHelper->save( + $cacheKey, + $result, + [static::CACHE_KEY], + $this->cacheLifetime + ); + } + + return $result; + } + + /** + * Assembles a unique key for caching + * + * @param array $addresses + * @return string + */ + private function getCacheKey(array $addresses = []): string + { + return empty($addresses) + ? static::CACHE_KEY + : sprintf('%s_%s', static::CACHE_KEY, implode('_', $addresses)); + } +} diff --git a/src/Api/ImprintApi/ImprintApiInterface.php b/src/Api/ImprintApi/ImprintApiInterface.php new file mode 100644 index 0000000..079741b --- /dev/null +++ b/src/Api/ImprintApi/ImprintApiInterface.php @@ -0,0 +1,29 @@ +