2023-09-22 21:31:47 +02:00
< ? php
namespace App\Models ;
use Illuminate\Database\Eloquent\Factories\HasFactory ;
2023-09-29 21:38:11 +02:00
use Illuminate\Support\Str ;
2023-09-22 21:31:47 +02:00
class LocalFileVolume extends BaseModel
{
use HasFactory ;
protected $guarded = [];
2024-02-14 10:21:53 +01:00
protected static function booted ()
{
static :: created ( function ( LocalFileVolume $fileVolume ) {
$fileVolume -> saveStorageOnServer ( $fileVolume -> service );
});
}
2023-09-22 21:31:47 +02:00
public function service ()
{
2023-09-25 12:49:55 +02:00
return $this -> morphTo ( 'resource' );
2023-09-22 21:31:47 +02:00
}
2023-09-29 21:38:11 +02:00
public function saveStorageOnServer ( ServiceApplication | ServiceDatabase $service )
{
$workdir = $service -> service -> workdir ();
$server = $service -> service -> server ;
$commands = collect ([
" mkdir -p $workdir > /dev/null 2>&1 || true " ,
" cd $workdir "
]);
$fileVolume = $this ;
$path = Str :: of ( data_get ( $fileVolume , 'fs_path' ));
$content = data_get ( $fileVolume , 'content' );
if ( $path -> startsWith ( '.' )) {
$path = $path -> after ( '.' );
$path = $workdir . $path ;
}
$isFile = instant_remote_process ([ " test -f $path && echo OK || echo NOK " ], $server );
$isDir = instant_remote_process ([ " test -d $path && echo OK || echo NOK " ], $server );
if ( $isFile == 'OK' && $fileVolume -> is_directory ) {
throw new \Exception ( " File $path is a file on the server, but you are trying to mark it as a directory. Please delete the file on the server or mark it as directory. " );
} else if ( $isDir == 'OK' && ! $fileVolume -> is_directory ) {
throw new \Exception ( " File $path is a directory on the server, but you are trying to mark it as a file. Please delete the directory on the server or mark it as directory. " );
}
2023-10-04 09:58:39 +02:00
if ( ! $fileVolume -> is_directory && $isDir == 'NOK' ) {
$content = base64_encode ( $content );
$commands -> push ( " echo ' $content ' | base64 -d > $path " );
2024-02-14 10:13:49 +01:00
} else if ( $isDir == 'NOK' && $fileVolume -> is_directory ) {
2023-09-29 21:38:11 +02:00
$commands -> push ( " mkdir -p $path > /dev/null 2>&1 || true " );
}
2023-10-04 09:58:39 +02:00
ray ( $commands -> toArray ());
2023-09-29 21:38:11 +02:00
return instant_remote_process ( $commands , $server );
}
2023-09-22 21:31:47 +02:00
}