2018-03-21 08:17:11 +08:00
|
|
|
<?php
|
|
|
|
|
2018-03-23 01:43:58 +08:00
|
|
|
namespace App\Services\ImportExport;
|
2018-03-21 08:17:11 +08:00
|
|
|
|
|
|
|
use App\Interfaces\ImportExport;
|
|
|
|
use App\Models\Aircraft;
|
|
|
|
use App\Models\Enums\AircraftState;
|
|
|
|
use App\Models\Enums\AircraftStatus;
|
|
|
|
use App\Models\Subfleet;
|
|
|
|
use App\Support\ICAO;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Import aircraft
|
|
|
|
* @package App\Services\Import
|
|
|
|
*/
|
|
|
|
class AircraftImporter extends ImportExport
|
|
|
|
{
|
2018-03-23 01:43:58 +08:00
|
|
|
public $assetType = 'aircraft';
|
|
|
|
|
2018-03-21 08:17:11 +08:00
|
|
|
/**
|
|
|
|
* All of the columns that are in the CSV import
|
|
|
|
* Should match the database fields, for the most part
|
|
|
|
*/
|
|
|
|
public static $columns = [
|
|
|
|
'subfleet',
|
|
|
|
'name',
|
|
|
|
'registration',
|
|
|
|
'hex_code',
|
|
|
|
'status',
|
|
|
|
];
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Find the subfleet specified, or just create it on the fly
|
|
|
|
* @param $type
|
|
|
|
* @return Subfleet|\Illuminate\Database\Eloquent\Model|null|object|static
|
|
|
|
*/
|
|
|
|
protected function getSubfleet($type)
|
|
|
|
{
|
2018-03-23 01:43:58 +08:00
|
|
|
$subfleet = Subfleet::firstOrCreate([
|
|
|
|
'type' => $type,
|
|
|
|
], ['name' => $type]);
|
2018-03-21 08:17:11 +08:00
|
|
|
|
|
|
|
return $subfleet;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Import a flight, parse out the different rows
|
|
|
|
* @param array $row
|
|
|
|
* @param int $index
|
|
|
|
* @return bool
|
|
|
|
*/
|
2018-03-23 01:43:58 +08:00
|
|
|
public function import(array $row, $index): bool
|
2018-03-21 08:17:11 +08:00
|
|
|
{
|
|
|
|
$subfleet = $this->getSubfleet($row['subfleet']);
|
|
|
|
|
|
|
|
$row['subfleet_id'] = $subfleet->id;
|
|
|
|
|
|
|
|
# Generate a hex code
|
|
|
|
if(!$row['hex_code']) {
|
|
|
|
$row['hex_code'] = ICAO::createHexCode();
|
|
|
|
}
|
|
|
|
|
|
|
|
# Set a default status
|
|
|
|
if($row['status'] === null) {
|
|
|
|
$row['status'] = AircraftStatus::ACTIVE;
|
|
|
|
}
|
|
|
|
|
|
|
|
# Just set its state right now as parked
|
|
|
|
$row['state'] = AircraftState::PARKED;
|
|
|
|
|
|
|
|
# Try to add or update
|
|
|
|
$aircraft = Aircraft::firstOrNew([
|
|
|
|
'registration' => $row['registration'],
|
|
|
|
], $row);
|
|
|
|
|
|
|
|
try {
|
|
|
|
$aircraft->save();
|
|
|
|
} catch(\Exception $e) {
|
|
|
|
$this->status = 'Error in row '.$index.': '.$e->getMessage();
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->status = 'Imported '.$row['registration'].' '.$row['name'];
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|