1
0
cms11/app/Services/Rebrickable/RebrickableClient.php

78 lines
1.9 KiB
PHP
Raw Normal View History

2024-04-18 01:52:40 +02:00
<?php
namespace App\Services\Rebrickable;
use Illuminate\Support\Facades\Cache;
2024-04-18 01:52:40 +02:00
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
2024-04-18 01:52:40 +02:00
class RebrickableClient
{
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) {
$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)
{
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)
{
return $this->get(sprintf('themes/%s/', $themeId));
}
2024-04-18 01:52:40 +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
}
/**
* Cache and return the result of a GET request
*/
2024-04-18 01:52:40 +02:00
private function get(string $url)
{
$key = $this->config['key'];
2024-04-21 16:27:09 +02:00
$baseUrl = $this->config['base_url'];
$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
$response = Http::throw()
2024-04-18 01:52:40 +02:00
->withHeader('Authorization', sprintf('key %s', $key))
->get(sprintf('%s/%s', $baseUrl, $url))->json();
Cache::put($cacheKey, $response, now()->addDays(7));
return $response;
2024-04-18 01:52:40 +02:00
}
}