Files
HickLab3D_Dashboard/app/Services/Bambuddy.php
T
HickmeisterandClaude Sonnet 5.5 2fe4fbd91e
Deploy HickLab3D Dashboard / Deploy to production (push) Successful in 28s
Cache integration API reads and refresh them on a schedule
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 19:01:32 +01:00

57 lines
1.9 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Throwable;
class Bambuddy
{
public function __construct(private IntegrationSettings $settings, private IntegrationCache $cache) {}
public function url(): string
{
return (string) ($this->settings->for('bambuddy')['url'] ?? '');
}
public function configured(): bool
{
return filled($this->url()) && filled($this->settings->for('bambuddy')['api_key'] ?? null);
}
public function printers(): array
{
if (! $this->configured()) {
throw new RuntimeException('BamBuddy API key is not configured.');
}
return $this->cache->remember('bambuddy.printers.'.md5($this->url()), 45, fn (): array => $this->fetchPrinters());
}
private function fetchPrinters(): array
{
$url = rtrim($this->url(), '/').'/api/v1/printers';
$apiKey = $this->settings->for('bambuddy')['api_key'];
$printers = Http::withHeaders(['X-API-Key' => $apiKey])
->acceptJson()->connectTimeout(3)->timeout(8)->get($url)->throw()->json() ?? [];
return collect($printers)->filter(fn ($printer) => is_array($printer) && isset($printer['id']))
->take(20)->map(function (array $printer) use ($apiKey): array {
try {
$status = Http::withHeaders(['X-API-Key' => $apiKey])
->acceptJson()->connectTimeout(3)->timeout(5)
->get(rtrim($this->url(), '/').'/api/v1/printers/'.(int) $printer['id'].'/status')
->throw()->json() ?? [];
return $printer + ['live' => $status];
} catch (Throwable $exception) {
report($exception);
return $printer + ['live' => []];
}
})->values()->all();
}
}