1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-10 21:22:58 +01:00
invoiceninja/app/Jobs/Util/StartMigration.php
Benjamin Beganović 40af77d324
(V2) Improve validation & error handling (#3414)
* wip - migration transfer

* (WIP) Response refactor:
- Catching exceptions at top level
- Tests refactor

* wip

* Wrappign migration validator:
- Migration dropped to queue
- New validator messages
- New exception messages

* Fixes for tests
2020-03-04 09:44:42 +11:00

105 lines
2.7 KiB
PHP

<?php
namespace App\Jobs\Util;
use App\Exceptions\MigrationValidatorFailed;
use App\Exceptions\NonExistingMigrationFile;
use App\Exceptions\ResourceDependencyMissing;
use App\Mail\MigrationFailed;
use App\Models\User;
use App\Models\Company;
use App\Libraries\MultiDB;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Exceptions\ProcessingMigrationArchiveFailed;
use App\Exceptions\ResourceNotAvailableForMigration;
use Illuminate\Support\Facades\Mail;
class StartMigration implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $filepath;
/**
* @var User
*/
private $user;
/**
* @var Company
*/
private $company;
/**
* Create a new job instance.
*
* @param $filepath
* @param User $user
* @param Company $company
*/
public function __construct($filepath, User $user, Company $company)
{
$this->filepath = base_path("public/storage/$filepath");
$this->user = $user;
$this->company = $company;
}
/**
* Execute the job.
*
* @return void
* @throws ProcessingMigrationArchiveFailed
* @throws NonExistingMigrationFile
*/
public function handle()
{
MultiDB::setDb($this->company->db);
$zip = new \ZipArchive();
$archive = $zip->open($this->filepath);
$filename = pathinfo($this->filepath, PATHINFO_FILENAME);
try {
if (!$archive)
throw new ProcessingMigrationArchiveFailed();
$zip->extractTo(storage_path("migrations/{$filename}"));
$zip->close();
if (app()->environment() == 'testing')
return;
$this->start($filename);
} catch (NonExistingMigrationFile | ProcessingMigrationArchiveFailed | ResourceNotAvailableForMigration | MigrationValidatorFailed | ResourceDependencyMissing $e) {
Mail::to(auth()->user())->send(new MigrationFailed($e->getMessage()));
if(app()->environment() !== 'production') info($e->getMessage());
}
}
/**
* Main method to start the migration.
* @throws NonExistingMigrationFile
*/
public function start(string $filename): void
{
$file = storage_path("migrations/$filename/migration.json");
if (!file_exists($file))
throw new NonExistingMigrationFile();
$handle = fopen($file, "r");
$file = fread($handle, filesize($file));
fclose($handle);
$data = json_decode($file, 1);
Import::dispatchNow($data, $this->company, $this->user);
}
}