2024-04-18 01:52:40 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services\Rebrickable;
|
|
|
|
|
2024-04-18 11:41:46 +02:00
|
|
|
use Illuminate\Support\Facades\Cache;
|
2024-04-18 01:52:40 +02:00
|
|
|
use Illuminate\Support\Facades\Http;
|
2024-04-18 11:41:46 +02:00
|
|
|
use Illuminate\Support\Str;
|
2024-04-18 01:52:40 +02:00
|
|
|
|
|
|
|
class RebrickableClient
|
|
|
|
{
|
2024-04-18 11:41:46 +02:00
|
|
|
protected static string $cachePrefix = 'rebrickable';
|
|
|
|
|
2024-04-18 01:52:40 +02:00
|
|
|
public function __construct(protected array $config)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Search for LEGO set Id, which will return a rebrickable set num
|
|
|
|
*/
|
|
|
|
public function searchSet(string $setId)
|
|
|
|
{
|
|
|
|
$response = $this->get(sprintf('sets/?search=%s', $setId));
|
|
|
|
$options = [];
|
|
|
|
|
|
|
|
foreach ($response['results'] as $result) {
|
2024-04-24 20:53:37 +02:00
|
|
|
$options[$result['set_num']] = sprintf('[%s] %s', $result['set_num'], $result['name']);
|
2024-04-18 01:52:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return $options;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get a specific set from its rebrickable ID
|
|
|
|
*/
|
|
|
|
public function getSet(string $setId)
|
|
|
|
{
|
2024-04-18 11:41:46 +02:00
|
|
|
return $this->get(sprintf('sets/%s/', $setId));
|
2024-04-18 01:52:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get a specific theme from its rebrickable ID
|
|
|
|
*/
|
|
|
|
public function getTheme(string $themeId)
|
|
|
|
{
|
2024-04-18 11:41:46 +02:00
|
|
|
return $this->get(sprintf('themes/%s/', $themeId));
|
|
|
|
}
|
2024-04-18 01:52:40 +02:00
|
|
|
|
2024-04-18 11:41:46 +02:00
|
|
|
/**
|
|
|
|
* Return minifigs associated to the set
|
|
|
|
*/
|
|
|
|
public function getMinifigs(string $setId)
|
|
|
|
{
|
|
|
|
return $this->get(sprintf('sets/%s/minifigs/', $setId))['results'];
|
2024-04-18 01:52:40 +02:00
|
|
|
}
|
|
|
|
|
2024-04-18 11:41:46 +02:00
|
|
|
/**
|
|
|
|
* Cache and return the result of a GET request
|
|
|
|
*/
|
2024-04-18 01:52:40 +02:00
|
|
|
private function get(string $url)
|
|
|
|
{
|
2024-04-18 11:41:46 +02:00
|
|
|
$key = $this->config['key'];
|
2024-04-21 16:27:09 +02:00
|
|
|
$baseUrl = $this->config['base_url'];
|
2024-04-18 11:41:46 +02:00
|
|
|
$cacheKey = sprintf('%s_%s', static::$cachePrefix, Str::slug($url));
|
|
|
|
|
|
|
|
if (Cache::has($cacheKey)) {
|
|
|
|
return Cache::get($cacheKey);
|
|
|
|
}
|
2024-04-18 01:52:40 +02:00
|
|
|
|
2024-04-18 11:41:46 +02:00
|
|
|
$response = Http::throw()
|
2024-04-18 01:52:40 +02:00
|
|
|
->withHeader('Authorization', sprintf('key %s', $key))
|
|
|
|
->get(sprintf('%s/%s', $baseUrl, $url))->json();
|
2024-04-18 11:41:46 +02:00
|
|
|
|
|
|
|
Cache::put($cacheKey, $response, now()->addDays(7));
|
|
|
|
|
|
|
|
return $response;
|
2024-04-18 01:52:40 +02:00
|
|
|
}
|
|
|
|
}
|