1
0
cms11/app/Services/BundleUpdaters/Updaters/LegoUpdater.php
2024-04-26 12:50:38 +02:00

114 lines
3.5 KiB
PHP

<?php
namespace App\Services\BundleUpdaters\Updaters;
use App\Classes\AttachmentsManager;
use App\Classes\Bundle;
use App\Services\Rebrickable\RebrickableClient;
use function Laravel\Prompts\select;
class LegoUpdater extends BaseUpdater
{
/**
* Return a boolean value indicating if the updater can actually make the
* update using known data.
*/
public function canUpdateBundle(): bool
{
return !empty($this->bundle->metadata()->get('rebrickableId'));
}
/**
* Return an array describing what kind of data the updater needs in
* addition to the one it already has
*/
public function formSpecs(): ?array
{
$specs = [];
if (empty($this->bundle->metadata()->get('rebrickableId'))) {
$productId = basename($this->bundle->getPath());
$specs['rebrickableId'] = fn () => select(
'Rebrickable Set ID',
app()->make(RebrickableClient::class)->searchSet($productId)
);
}
return $specs;
}
/**
* Updates bundle's extended metadata
*/
public function update()
{
$productId = basename($this->bundle->getPath());
$rebrickable = app()->make(RebrickableClient::class);
$setData = $rebrickable->getSet($this->bundle->metadata()->get('rebrickableId'));
$theme = $rebrickable->getTheme($setData['theme_id']);
$minifigs = $rebrickable->getMinifigs($this->bundle->metadata()->get('rebrickableId'));
$this->bundle->metadata()->setMany([
'title' => $setData['name'],
'productId' => $productId,
]);
$this->bundle->metadata('metadata')->setMany([
'Détails' => [
'Identifiant' => $productId,
'Date de sortie' => $setData['year'],
'Nombre de pièces' => $setData['num_parts'],
],
'Thème' => [
$theme['name'],
],
]);
$this->bundle->metadata('rebrickable/set')->setMany($setData);
$this->bundle->metadata('rebrickable/theme')->setMany($theme);
$this->bundle->metadata('rebrickable/minifigs')->setMany($minifigs);
if (!empty($setData['set_img_url'])) {
$ref = $this->bundle->attachments(AttachmentsManager::Images)->add([
'url' => $setData['set_img_url'],
'attribution' => '&copy; [Rebrickable](https://rebrickable.com/)',
]);
$this->bundle->metadata()->set('cover', $ref);
}
if (!empty($minifigs)) {
foreach ($minifigs as $minifig) {
if (empty($minifig['set_img_url'])) {
continue;
}
$this->bundle->attachments(AttachmentsManager::Images)->add([
'url' => $minifig['set_img_url'],
'attribution' => '&copy; [Rebrickable](https://rebrickable.com/)',
]);
}
}
$this->bundle->save();
$this->bundle->repair();
}
/**
* Return a boolean value indicating if this updater in particular can
* update specified bundle
*/
public static function handles(Bundle $bundle): bool
{
$parts = preg_split('#/#', $bundle->getPath(), -1, PREG_SPLIT_NO_EMPTY);
if ($parts[0] !== 'collections' || $parts[1] !== 'lego' || count($parts) !== 4) {
return false;
}
return true;
}
}