Files
myep/src/Service/CmsDataProvider.php
T

130 lines
3.9 KiB
PHP

<?php
namespace App\Service;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class CmsDataProvider
{
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly CacheInterface $cache,
private readonly string $apiKey,
) {
}
/**
* Fetches only the hotel images from the CMS.
*
* @return array<string, mixed>|null The images array or null if unavailable
*/
public function getProductImages(string $productCode, ?string $hotelCode = null): ?array
{
$result = $this->getProductDetails($productCode, $hotelCode);
if (true === isset($result['success']) && false === $result['success']) {
return null;
}
return $result['hotel']['images'] ?? null;
}
/**
* @return array<string, mixed>|null
*/
public function getHotelImages(string $hotelCode): ?array
{
$result = $this->getHotelDetails($hotelCode);
if (true === isset($result['success']) && false === $result['success']) {
return null;
}
return $result['images'] ?? null;
}
/** @return array<string, mixed> */
public function getHotelDetails(string $hotelCode): array
{
return $this->cache->get(
sprintf('cms_hotel_%s', $hotelCode),
function (ItemInterface $item) use ($hotelCode): array {
$item->expiresAfter(3600);
try {
$request = $this->httpClient->request('GET', 'api/hotel', [
'query' => [
'hotel' => $hotelCode,
'key' => $this->apiKey,
],
]);
} catch (ExceptionInterface $e) {
$item->expiresAfter(0);
return [
'success' => false,
'message' => $e->getMessage(),
];
}
try {
$data = $request->toArray();
} catch (ExceptionInterface $e) {
$item->expiresAfter(0);
return [
'success' => false,
'message' => $e->getMessage(),
];
}
return $data;
}
);
}
/** @return array<string, mixed> */
public function getProductDetails(string $productCode, ?string $hotelCode = null): array
{
return $this->cache->get(
sprintf('cms_product_%s_%s', $productCode, $hotelCode ?? ''),
function (ItemInterface $item) use ($productCode, $hotelCode): array {
$item->expiresAfter(3600);
try {
$request = $this->httpClient->request('GET', 'api/product', [
'query' => [
'product' => $productCode,
'hotel' => $hotelCode,
'key' => $this->apiKey,
],
]);
} catch (ExceptionInterface $e) {
$item->expiresAfter(0);
return [
'success' => false,
'message' => $e->getMessage(),
];
}
try {
$data = $request->toArray();
} catch (ExceptionInterface $e) {
$item->expiresAfter(0);
return [
'success' => false,
'message' => $e->getMessage(),
];
}
return $data;
}
);
}
}