phpvms/app/Services/ImportExport/AircraftImporter.php

94 lines
2.4 KiB
PHP
Raw Normal View History

<?php
namespace App\Services\ImportExport;
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
*/
class AircraftImporter extends ImportExport
{
public $assetType = 'aircraft';
/**
* All of the columns that are in the CSV import
* Should match the database fields, for the most part
*/
public static $columns = [
'subfleet' => 'required',
'iata' => 'nullable',
'icao' => 'nullable',
'name' => 'required',
'registration' => 'required',
'hex_code' => 'nullable',
'zfw' => 'nullable|numeric',
'status' => 'nullable',
];
/**
* Find the subfleet specified, or just create it on the fly
2018-08-27 00:40:04 +08:00
*
* @param $type
2018-08-27 00:40:04 +08:00
*
* @return Subfleet|\Illuminate\Database\Eloquent\Model|null|object|static
*/
protected function getSubfleet($type)
{
$subfleet = Subfleet::firstOrCreate([
'type' => $type,
], ['name' => $type]);
return $subfleet;
}
/**
* Import a flight, parse out the different rows
2018-08-27 00:40:04 +08:00
*
* @param array $row
* @param int $index
2018-08-27 00:40:04 +08:00
*
* @return bool
2018-08-27 02:50:08 +08:00
* @throws \Exception
*/
public function import(array $row, $index): bool
{
$subfleet = $this->getSubfleet($row['subfleet']);
$row['subfleet_id'] = $subfleet->id;
2018-08-27 00:40:04 +08:00
// Generate a hex code
if (!$row['hex_code']) {
$row['hex_code'] = ICAO::createHexCode();
}
2018-08-27 00:40:04 +08:00
// Set a default status
2018-03-23 08:59:35 +08:00
$row['status'] = trim($row['status']);
2018-08-27 00:40:04 +08:00
if ($row['status'] === null || $row['status'] === '') {
$row['status'] = AircraftStatus::ACTIVE;
}
2018-08-27 00:40:04 +08:00
// Just set its state right now as parked
$row['state'] = AircraftState::PARKED;
2018-08-27 00:40:04 +08:00
// Try to add or update
$aircraft = Aircraft::firstOrNew([
'registration' => $row['registration'],
], $row);
try {
$aircraft->save();
2018-08-27 00:40:04 +08:00
} catch (\Exception $e) {
2018-03-23 06:17:37 +08:00
$this->errorLog('Error in row '.$index.': '.$e->getMessage());
return false;
}
2018-03-23 06:17:37 +08:00
$this->log('Imported '.$row['registration'].' '.$row['name']);
return true;
}
}