pelican-panel-mirror/app/Services/Eggs/Sharing/EggImporterService.php
Charles 02d24b8a36
Fix the egg variable disaster... (#331)
* Migrations to update existing eggs in db

* Update stock eggs

* Update Eggs on import

* Also update updated versions of eggs that are uploaded

* Redo this..

Tests passed locally.

* Pint & Update replace

* Squash Migrations, simplify logic

* Maybe this way...

* Swap them over to single call

---------

Co-authored-by: Lance Pioch <git@lance.sh>
2024-06-07 16:23:25 -04:00

50 lines
1.4 KiB
PHP

<?php
namespace App\Services\Eggs\Sharing;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Arr;
use App\Models\Egg;
use Illuminate\Http\UploadedFile;
use App\Models\EggVariable;
use Illuminate\Database\ConnectionInterface;
use App\Services\Eggs\EggParserService;
class EggImporterService
{
public function __construct(protected ConnectionInterface $connection, protected EggParserService $parser)
{
}
/**
* Take an uploaded JSON file and parse it into a new egg.
*
* @throws \App\Exceptions\Service\InvalidFileUploadException|\Throwable
*/
public function handle(UploadedFile $file): Egg
{
$parsed = $this->parser->handle($file);
return $this->connection->transaction(function () use ($parsed) {
$uuid = $parsed['uuid'] ?? Uuid::uuid4()->toString();
$egg = Egg::where('uuid', $uuid)->first() ?? new Egg();
$egg = $egg->forceFill([
'uuid' => $uuid,
'author' => Arr::get($parsed, 'author'),
'copy_script_from' => null,
]);
$egg = $this->parser->fillFromParsed($egg, $parsed);
$egg->save();
foreach ($parsed['variables'] ?? [] as $variable) {
EggVariable::query()->forceCreate(array_merge($variable, ['egg_id' => $egg->id]));
}
return $egg;
});
}
}