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

78 lines
1.9 KiB
PHP

<?php
namespace App\Services\Rebrickable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
class RebrickableClient
{
protected static string $cachePrefix = 'rebrickable';
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']);
}
return $options;
}
/**
* Get a specific set from its rebrickable ID
*/
public function getSet(string $setId)
{
return $this->get(sprintf('sets/%s/', $setId));
}
/**
* Get a specific theme from its rebrickable ID
*/
public function getTheme(string $themeId)
{
return $this->get(sprintf('themes/%s/', $themeId));
}
/**
* Return minifigs associated to the set
*/
public function getMinifigs(string $setId)
{
return $this->get(sprintf('sets/%s/minifigs/', $setId))['results'];
}
/**
* Cache and return the result of a GET request
*/
private function get(string $url)
{
$key = $this->config['key'];
$baseUrl = $this->config['base_url'];
$cacheKey = sprintf('%s_%s', static::$cachePrefix, Str::slug($url));
if (Cache::has($cacheKey)) {
return Cache::get($cacheKey);
}
$response = Http::throw()
->withHeader('Authorization', sprintf('key %s', $key))
->get(sprintf('%s/%s', $baseUrl, $url))->json();
Cache::put($cacheKey, $response, now()->addDays(7));
return $response;
}
}