2017-10-09 04:50:52 +00:00
< ? php
namespace Pterodactyl\Services\Eggs\Sharing ;
2020-10-06 04:29:35 +00:00
use Pterodactyl\Models\Egg ;
2017-10-09 04:50:52 +00:00
use Illuminate\Http\UploadedFile ;
2022-05-15 18:40:19 +00:00
use Illuminate\Support\Collection ;
use Pterodactyl\Models\EggVariable ;
2017-10-09 04:50:52 +00:00
use Illuminate\Database\ConnectionInterface ;
2022-05-15 18:40:19 +00:00
use Pterodactyl\Services\Eggs\EggParserService ;
2022-12-15 00:05:46 +00:00
use Pterodactyl\Exceptions\Service\Egg\BadJsonFormatException ;
2022-12-15 00:06:28 +00:00
use Pterodactyl\Exceptions\Service\InvalidFileUploadException ;
2017-10-09 04:50:52 +00:00
class EggUpdateImporterService
{
/**
* EggUpdateImporterService constructor .
*/
2022-12-15 00:05:46 +00:00
public function __construct (
private ConnectionInterface $connection ,
private EggParserService $eggParserService
) {
2017-10-09 04:50:52 +00:00
}
/**
* Update an existing Egg using an uploaded JSON file .
*
2022-05-15 18:40:19 +00:00
* @ throws \Pterodactyl\Exceptions\Service\InvalidFileUploadException | \Throwable
2017-10-09 04:50:52 +00:00
*/
2022-05-15 18:40:19 +00:00
public function handle ( Egg $egg , UploadedFile $file ) : Egg
2017-10-09 04:50:52 +00:00
{
2022-12-15 00:05:46 +00:00
if ( $file -> getError () !== UPLOAD_ERR_OK || ! $file -> isFile ()) {
throw new InvalidFileUploadException ( sprintf ( 'The selected file ["%s"] was not in a valid format to import. (is_file: %s is_valid: %s err_code: %s err: %s)' , $file -> getFilename (), $file -> isFile () ? 'true' : 'false' , $file -> isValid () ? 'true' : 'false' , $file -> getError (), $file -> getErrorMessage ()));
}
$parsed = json_decode ( $file -> openFile () -> fread ( $file -> getSize ()), true );
if ( json_last_error () !== 0 ) {
throw new BadJsonFormatException ( trans ( 'exceptions.nest.importer.json_error' , [ 'error' => json_last_error_msg ()]));
}
$parsed = $this -> eggParserService -> handle ( $parsed );
2022-05-15 18:40:19 +00:00
return $this -> connection -> transaction ( function () use ( $egg , $parsed ) {
2022-12-15 00:05:46 +00:00
$egg = $this -> eggParserService -> fillFromParsed ( $egg , $parsed );
2022-05-15 18:40:19 +00:00
$egg -> save ();
// Update existing variables or create new ones.
foreach ( $parsed [ 'variables' ] ? ? [] as $variable ) {
EggVariable :: unguarded ( function () use ( $egg , $variable ) {
$egg -> variables () -> updateOrCreate ([
'env_variable' => $variable [ 'env_variable' ],
], Collection :: make ( $variable ) -> except ( 'egg_id' , 'env_variable' ) -> toArray ());
});
}
2017-10-09 04:50:52 +00:00
2022-05-15 18:40:19 +00:00
$imported = array_map ( fn ( $value ) => $value [ 'env_variable' ], $parsed [ 'variables' ] ? ? []);
2017-10-09 04:50:52 +00:00
2022-05-15 18:40:19 +00:00
$egg -> variables () -> whereNotIn ( 'env_variable' , $imported ) -> delete ();
2017-10-09 04:50:52 +00:00
2022-05-15 18:40:19 +00:00
return $egg -> refresh ();
2017-10-09 04:50:52 +00:00
});
}
}