Fix formatting and interfaces in nearly every file

This commit is contained in:
Nabeel Shahzad
2018-03-19 20:50:40 -05:00
parent 04c5b9e7bf
commit ccf56ddec1
331 changed files with 3282 additions and 2492 deletions

View File

@@ -2,12 +2,20 @@
namespace App\Console;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
use Log;
use Symfony\Component\Process\Process;
class BaseCommand extends Command
/**
* Class BaseCommand
* @package App\Console
*/
abstract class Command extends \Illuminate\Console\Command
{
/**
* @return mixed
*/
abstract public function handle();
/**
* Splice the logger and replace the active handlers with
* the handlers from the "cron" stack in config/logging.php
@@ -17,7 +25,7 @@ class BaseCommand extends Command
*
* @param string $channel_name Channel name to grab the handlers from
*/
public function redirectLoggingToStdout($channel_name)
public function redirectLoggingToStdout($channel_name): void
{
$logger = app(\Illuminate\Log\Logger::class);
@@ -28,7 +36,7 @@ class BaseCommand extends Command
$handler->close();
}
} catch (\Exception $e) {
$this->error('Error closing handlers: ' . $e->getMessage());
$this->error('Error closing handlers: '.$e->getMessage());
}
// Open the handlers for the channel name,
@@ -38,7 +46,7 @@ class BaseCommand extends Command
Log::channel($channel_name)->getHandlers()
);
} catch (\Exception $e) {
$this->error('Couldn\'t splice the logger: ' . $e->getMessage());
$this->error('Couldn\'t splice the logger: '.$e->getMessage());
}
}
@@ -47,10 +55,9 @@ class BaseCommand extends Command
* @param $filename
* @return \Generator
*/
public function readFile($filename)
public function readFile($filename): ?\Generator
{
$fp = fopen($filename, 'rb');
while (($line = fgets($fp)) !== false) {
$line = rtrim($line, "\r\n");
if ($line[0] === ';') {
@@ -64,20 +71,20 @@ class BaseCommand extends Command
}
/**
* @param $cmd
* @param $cmd
* @param bool $return
* @return string
* @throws \Symfony\Component\Process\Exception\RuntimeException
* @throws \Symfony\Component\Process\Exception\LogicException
*/
public function runCommand($cmd, $return = false, $verbose = true)
public function runCommand($cmd, $return = false, $verbose = true): string
{
if (\is_array($cmd)) {
$cmd = join(' ', $cmd);
}
if ($verbose) {
$this->info('Running "' . $cmd . '"');
$this->info('Running "'.$cmd.'"');
}
$val = '';

View File

@@ -2,12 +2,16 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
use App\Facades\Utils;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Collection;
class AcarsReplay extends BaseCommand
/**
* Class AcarsReplay
* @package App\Console\Commands
*/
class AcarsReplay extends Command
{
protected $signature = 'phpvms:replay {files} {--manual} {--write-all} {--no-submit}';
protected $description = 'Replay an ACARS file';
@@ -35,7 +39,6 @@ class AcarsReplay extends BaseCommand
*/
protected $httpClient;
/**
* Return an instance of an HTTP client all ready to post
*/
@@ -45,46 +48,43 @@ class AcarsReplay extends BaseCommand
$this->httpClient = new Client([
'base_uri' => config('app.url'),
'headers' => [
'headers' => [
'Authorization' => $this->apiKey,
]
]);
}
/*protected function getArguments()
{
return [
['--files', InputOption::VALUE_OPTIONAL]
];
}*/
/**
* Make a request to start a PIREP
* @param \stdClass $flight
* @return string
* @throws \RuntimeException
*/
protected function startPirep($flight): string
{
# convert the planned flight time to be completely in minutes
$pft = Utils::hoursToMinutes($flight->planned_hrsenroute,
$flight->planned_minenroute);
$pft = Utils::hoursToMinutes(
$flight->planned_hrsenroute,
$flight->planned_minenroute
);
$flight_number = substr($flight->callsign, 3);
$response = $this->httpClient->post('/api/pireps/prefile', [
'json' => [
'airline_id' => 1,
'flight_number' => $flight_number,
'aircraft_id' => 1,
'dpt_airport_id' => $flight->planned_depairport,
'arr_airport_id' => $flight->planned_destairport,
'level' => $flight->planned_altitude,
'planned_flight_time' => $pft,
'route' => $flight->planned_route,
'airline_id' => 1,
'flight_number' => $flight_number,
'aircraft_id' => 1,
'dpt_airport_id' => $flight->planned_depairport,
'arr_airport_id' => $flight->planned_destairport,
'level' => $flight->planned_altitude,
'planned_flight_time' => $pft,
'route' => $flight->planned_route,
]
]);
$body = \json_decode($response->getBody()->getContents());
return $body->id;
}
@@ -92,14 +92,16 @@ class AcarsReplay extends BaseCommand
* Mark the PIREP as filed
* @param $pirep_id
* @return mixed
* @throws \RuntimeException
*/
protected function filePirep($pirep_id)
{
$response = $this->httpClient->post('/api/pireps/'.$pirep_id.'/file', [
'json'=> []
'json' => []
]);
$body = \json_decode($response->getBody()->getContents());
return $body;
}
@@ -107,18 +109,19 @@ class AcarsReplay extends BaseCommand
* @param $pirep_id
* @param $data
* @return array
* @throws \RuntimeException
*/
protected function postUpdate($pirep_id, $data)
{
$uri = '/api/pireps/' . $pirep_id . '/acars/position';
$uri = '/api/pireps/'.$pirep_id.'/acars/position';
$position = [
'log' => '',
'lat' => $data->latitude,
'lon' => $data->longitude,
'heading' => $data->heading,
'altitude' => $data->altitude,
'gs' => $data->groundspeed,
'log' => '',
'lat' => $data->latitude,
'lon' => $data->longitude,
'heading' => $data->heading,
'altitude' => $data->altitude,
'gs' => $data->groundspeed,
'transponder' => $data->transponder,
];
@@ -129,13 +132,14 @@ class AcarsReplay extends BaseCommand
];
$this->info("Update: $data->callsign, $position[lat] x $position[lon] \t\t"
. "hdg: $position[heading]\t\talt: $position[altitude]\t\tgs: $position[gs]");
."hdg: $position[heading]\t\talt: $position[altitude]\t\tgs: $position[gs]");
$response = $this->httpClient->post($uri, [
'json' => $upd
]);
$body = \json_decode($response->getBody()->getContents());
return [
$data->callsign,
$position['lat'],
@@ -149,22 +153,24 @@ class AcarsReplay extends BaseCommand
/**
* Parse this file and run the updates
* @param array $files
* @throws \RuntimeException
*/
protected function updatesFromFile(array $files)
{
/**
* @var $flights Collection
*/
$flights = collect($files)->transform(function ($f)
{
$file = storage_path('/replay/' . $f . '.json');
$flights = collect($files)->transform(function ($f) {
$file = storage_path('/replay/'.$f.'.json');
if (file_exists($file)) {
$this->info('Loading ' . $file);
$this->info('Loading '.$file);
$contents = file_get_contents($file);
$contents = \json_decode($contents);
return collect($contents->updates);
} else {
$this->error($file . ' not found, skipping');
$this->error($file.' not found, skipping');
return false;
}
})
@@ -178,12 +184,11 @@ class AcarsReplay extends BaseCommand
/**
* File the initial pirep to get a "preflight" status
*/
$flights->each(function ($updates, $idx)
{
$flights->each(function ($updates, $idx) {
$update = $updates->first();
$pirep_id = $this->startPirep($update);
$this->pirepList[$update->callsign] = $pirep_id;
$this->info('Prefiled ' . $update->callsign . ', ID: ' . $pirep_id);
$this->info('Prefiled '.$update->callsign.', ID: '.$pirep_id);
});
/**
@@ -202,14 +207,14 @@ class AcarsReplay extends BaseCommand
$this->postUpdate($pirep_id, $update);
# we're done and don't put the "no-submit" option
if($updates->count() === 0 && !$this->option('no-submit')) {
if ($updates->count() === 0 && !$this->option('no-submit')) {
$this->filePirep($pirep_id);
}
})->filter(function ($updates, $idx) {
return $updates->count() > 0;
});
if(!$this->option('write-all')) {
if (!$this->option('write-all')) {
if (!$this->option('manual')) {
sleep($this->sleepTime);
} else {
@@ -221,8 +226,8 @@ class AcarsReplay extends BaseCommand
/**
* Execute the console command.
*
* @return mixed
* @throws \RuntimeException
*/
public function handle()
{

View File

@@ -2,15 +2,22 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
use Log;
class CreateDatabase extends BaseCommand
/**
* Class CreateDatabase
* @package App\Console\Commands
*/
class CreateDatabase extends Command
{
protected $signature = 'database:create {--reset} {--conn=?}';
protected $description = 'Create a database';
protected $os;
/**
* CreateDatabase constructor.
*/
public function __construct()
{
parent::__construct();
@@ -24,21 +31,22 @@ class CreateDatabase extends BaseCommand
*/
protected function create_mysql($dbkey)
{
$host = config($dbkey . 'host');
$port = config($dbkey . 'port');
$name = config($dbkey . 'database');
$user = config($dbkey . 'username');
$pass = config($dbkey . 'password');
$host = config($dbkey.'host');
$port = config($dbkey.'port');
$name = config($dbkey.'database');
$user = config($dbkey.'username');
$pass = config($dbkey.'password');
$dbSvc = new \App\Console\Services\Database();
$dsn = $dbSvc->createDsn($host, $port);
Log::info('Connection string: ' . $dsn);
Log::info('Connection string: '.$dsn);
try {
$conn = $dbSvc->createPDO($dsn, $user, $pass);
} catch (\PDOException $e) {
Log::error($e);
return false;
}
@@ -59,6 +67,7 @@ class CreateDatabase extends BaseCommand
$conn->exec($sql);
} catch (\PDOException $e) {
Log::error($e);
return false;
}
}
@@ -75,14 +84,14 @@ class CreateDatabase extends BaseCommand
}
if ($this->option('reset') === true) {
$cmd = ['rm', '-rf', config($dbkey . 'database')];
$cmd = ['rm', '-rf', config($dbkey.'database')];
$this->runCommand($cmd);
}
if (!file_exists(config($dbkey . 'database'))) {
if (!file_exists(config($dbkey.'database'))) {
$cmd = [
$exec,
config($dbkey . 'database'),
config($dbkey.'database'),
'""',
];
@@ -108,21 +117,17 @@ class CreateDatabase extends BaseCommand
}
}*/
$this->info('Using connection "' . config('database.default') . '"');
$this->info('Using connection "'.config('database.default').'"');
$conn = config('database.default');
$dbkey = 'database.connections.' . $conn . '.';
$dbkey = 'database.connections.'.$conn.'.';
if (config($dbkey . 'driver') === 'mysql') {
if (config($dbkey.'driver') === 'mysql') {
$this->create_mysql($dbkey);
}
elseif (config($dbkey . 'driver') === 'sqlite') {
} elseif (config($dbkey.'driver') === 'sqlite') {
$this->create_sqlite($dbkey);
}
// TODO: Eventually
elseif (config($dbkey . 'driver') === 'postgres') {
} // TODO: Eventually
elseif (config($dbkey.'driver') === 'postgres') {
$this->create_postgres($dbkey);
}
}

View File

@@ -2,7 +2,7 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
use App\Models\Acars;
use App\Models\Airline;
use App\Models\Pirep;
@@ -12,7 +12,11 @@ use DB;
use PDO;
use Symfony\Component\Yaml\Yaml;
class DevCommands extends BaseCommand
/**
* Class DevCommands
* @package App\Console\Commands
*/
class DevCommands extends Command
{
protected $signature = 'phpvms {cmd} {param?}';
protected $description = 'Developer commands';
@@ -30,15 +34,15 @@ class DevCommands extends BaseCommand
}
$commands = [
'list-awards' => 'listAwardClasses',
'clear-acars' => 'clearAcars',
'clear-users' => 'clearUsers',
'compile-assets' => 'compileAssets',
'db-attrs' => 'dbAttrs',
'xml-to-yaml' => 'xmlToYaml',
'list-awards' => 'listAwardClasses',
'clear-acars' => 'clearAcars',
'clear-users' => 'clearUsers',
'compile-assets' => 'compileAssets',
'db-attrs' => 'dbAttrs',
'xml-to-yaml' => 'xmlToYaml',
];
if(!array_key_exists($command, $commands)) {
if (!array_key_exists($command, $commands)) {
$this->error('Command not found!');
exit();
}
@@ -56,7 +60,7 @@ class DevCommands extends BaseCommand
$headers = ['Award Name', 'Class'];
$formatted_awards = [];
foreach($awards as $award) {
foreach ($awards as $award) {
$formatted_awards[] = [$award->name, \get_class($award)];
}
@@ -68,7 +72,7 @@ class DevCommands extends BaseCommand
*/
protected function clearAcars()
{
if(config('database.default') === 'mysql') {
if (config('database.default') === 'mysql') {
DB::statement('SET foreign_key_checks=0');
}
@@ -122,7 +126,7 @@ class DevCommands extends BaseCommand
$server_version = $pdo->getAttribute(PDO::ATTR_SERVER_VERSION);
$emulate_prepares = version_compare($server_version, $emulate_prepares_below_version, '<');
$this->info('Server Version: '. $server_version);
$this->info('Server Version: '.$server_version);
$this->info('Emulate Prepares: '.$emulate_prepares);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $emulate_prepares);
@@ -134,7 +138,7 @@ class DevCommands extends BaseCommand
protected function xmlToYaml()
{
$file = $this->argument('param');
$this->info('Reading '. $file);
$this->info('Reading '.$file);
$xml_str = file_get_contents($file);
$xml = new \SimpleXMLElement($xml_str);
@@ -148,7 +152,7 @@ class DevCommands extends BaseCommand
foreach ($xml->database->table_data->row as $row) {
$yaml_row = [];
foreach($row->field as $field) {
foreach ($row->field as $field) {
$fname = (string) $field['name'];
$fvalue = (string) $field;
@@ -163,6 +167,6 @@ class DevCommands extends BaseCommand
$file_name = $table_name.'.yml';
file_put_contents(storage_path($file_name), Yaml::dump($yaml, 4, 2));
$this->info('Writing yaml to storage: '. $file_name);
$this->info('Writing yaml to storage: '.$file_name);
}
}

View File

@@ -2,14 +2,14 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
use Modules\Installer\Services\ConfigService;
/**
* Create a fresh development install
* @package App\Console\Commands
*/
class DevInstall extends BaseCommand
class DevInstall extends Command
{
protected $signature = 'phpvms:dev-install {--reset-db}';
protected $description = 'Run a developer install and run the sample migration';
@@ -20,7 +20,7 @@ class DevInstall extends BaseCommand
*/
public function handle()
{
if(!$this->option('reset-db')) {
if (!$this->option('reset-db')) {
$this->rewriteConfigs();
}
@@ -69,26 +69,26 @@ class DevInstall extends BaseCommand
# Remove the old files
$config_file = base_path('config.php');
if(file_exists($config_file)) {
if (file_exists($config_file)) {
unlink($config_file);
}
$env_file = base_path('env.php');
if(file_exists($env_file)) {
if (file_exists($env_file)) {
unlink($env_file);
}
$this->info('Removing the sqlite db');
$db_file = storage_path('db.sqlite');
if(file_exists($db_file)) {
if (file_exists($db_file)) {
unlink($db_file);
}
$this->info('Regenerating the config files');
$cfgSvc->createConfigFiles([
'APP_ENV' => 'dev',
'APP_ENV' => 'dev',
'SITE_NAME' => 'phpvms test',
'DB_CONN' => 'sqlite',
'DB_CONN' => 'sqlite',
]);
$this->info('Config files generated!');

View File

@@ -2,9 +2,9 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
class ImportFromClassic extends BaseCommand
class ImportFromClassic extends Command
{
protected $signature = 'phpvms:importer {db_host} {db_name} {db_user} {db_pass?} {table_prefix=phpvms_}';
protected $description = 'Import from an older version of phpVMS';
@@ -15,10 +15,10 @@ class ImportFromClassic extends BaseCommand
public function handle()
{
$db_creds = [
'host' => $this->argument('db_host'),
'name' => $this->argument('db_name'),
'user' => $this->argument('db_user'),
'pass' => $this->argument('db_pass'),
'host' => $this->argument('db_host'),
'name' => $this->argument('db_name'),
'user' => $this->argument('db_user'),
'pass' => $this->argument('db_pass'),
'table_prefix' => $this->argument('table_prefix')
];

View File

@@ -2,9 +2,13 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
class Install extends BaseCommand
/**
* Class Install
* @package App\Console\Commands
*/
class Install extends Command
{
protected $signature = 'phpvms:install
{--update}
@@ -13,11 +17,17 @@ class Install extends BaseCommand
protected $description = 'Install or update phpVMS';
/**
* Install constructor.
*/
public function __construct()
{
parent::__construct();
}
/**
* @return mixed|void
*/
public function handle()
{
$this->info('Installing phpVMS...');
@@ -25,7 +35,7 @@ class Install extends BaseCommand
$this->setupDatabase();
# Only run these if we're doing an initial install
if(!$this->option('update')) {
if (!$this->option('update')) {
$this->writeLocalConfig();
$this->initialData();
}
@@ -38,22 +48,20 @@ class Install extends BaseCommand
*/
protected function setupDatabase()
{
if(!$this->option('update')) {
if (!$this->option('update')) {
$this->call('database:create');
}
$this->info('Running database migrations...');
$this->call('migrate');
# TODO: Call initial seed data, for the groups and other supporting data
}
/**
* Write a local config file
*/
protected function writeLocalConfig()
protected function writeLocalConfig(): void
{
}
/**
@@ -63,15 +71,14 @@ class Install extends BaseCommand
{
# TODO: Prompt for initial airline info
$airline_name = $this->option('airline-name');
if(!$airline_name) {
if (!$airline_name) {
$airline_name = $this->ask('Enter your airline name');
}
$airline_code = $this->option('airline-code');
if(!$airline_code) {
if (!$airline_code) {
$airline_code = $this->ask('Enter your airline code');
}
# TODO: Prompt for admin user/password
}
}

View File

@@ -2,15 +2,33 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
use App\Models\Enums\NavaidType;
use App\Models\Navdata;
class NavdataImport extends BaseCommand
/**
* Class NavdataImport
* @package App\Console\Commands
*/
class NavdataImport extends Command
{
protected $signature = 'phpvms:navdata';
protected $description = '';
/**
* @return mixed|void
* @throws \League\Geotools\Exception\InvalidArgumentException
*/
public function handle()
{
$this->info('Emptying the current navdata...');
Navdata::query()->truncate();
$this->info('Looking for nav files...');
$this->read_wp_nav_aid();
$this->read_wp_nav_fix();
}
/**
* Read and parse in the navaid file
* @throws \League\Geotools\Exception\InvalidArgumentException
@@ -49,6 +67,7 @@ class NavdataImport extends BaseCommand
$file_path = storage_path('/navdata/WPNAVAID.txt');
if (!file_exists($file_path)) {
$this->error('WPNAVAID.txt not found in storage/navdata');
return false;
}
@@ -57,10 +76,9 @@ class NavdataImport extends BaseCommand
$imported = 0;
foreach($generator as $line) {
foreach ($generator as $line) {
$navaid = [
'id' => trim(substr($line, 24, 4)), // ident column
'id' => trim(substr($line, 24, 4)), // ident column
'name' => trim(substr($line, 0, 24)),
'type' => trim(substr($line, 29, 4)),
'lat' => trim(substr($line, 33, 9)),
@@ -70,8 +88,7 @@ class NavdataImport extends BaseCommand
];
# Map to the Navaid enum
switch($navaid['type'])
{
switch ($navaid['type']) {
case 'ILS':
$navaid['type'] = NavaidType::LOC;
break;
@@ -104,12 +121,12 @@ class NavdataImport extends BaseCommand
], $navaid);
$imported++;
if($imported % 100 === 0) {
$this->info('Imported ' . $imported . ' entries...');
if ($imported % 100 === 0) {
$this->info('Imported '.$imported.' entries...');
}
}
$this->info('Imported a total of ' . $imported . ' nav aids');
$this->info('Imported a total of '.$imported.' nav aids');
}
/**
@@ -137,8 +154,9 @@ class NavdataImport extends BaseCommand
*/
$file_path = storage_path('/navdata/WPNAVFIX.txt');
if(!file_exists($file_path)) {
if (!file_exists($file_path)) {
$this->error('WPNAVFIX.txt not found in storage/navdata');
return false;
}
@@ -148,11 +166,11 @@ class NavdataImport extends BaseCommand
$imported = 0;
foreach ($generator as $line) {
$navfix = [
'id' => trim(substr($line, 0, 4)), // ident column
'id' => trim(substr($line, 0, 4)), // ident column
'name' => trim(substr($line, 24, 6)),
'type' => NavaidType::FIX,
'lat' => trim(substr($line, 30, 10)),
'lon' => trim(substr($line, 40, 11)),
'lat' => trim(substr($line, 30, 10)),
'lon' => trim(substr($line, 40, 11)),
];
switch ($navfix['type']) {
@@ -165,20 +183,10 @@ class NavdataImport extends BaseCommand
$imported++;
if ($imported % 100 === 0) {
$this->info('Imported ' . $imported . ' entries...');
$this->info('Imported '.$imported.' entries...');
}
}
$this->info('Imported a total of ' . $imported . ' nav fixes');
}
public function handle()
{
$this->info('Emptying the current navdata...');
Navdata::query()->truncate();
$this->info('Looking for nav files...');
$this->read_wp_nav_aid();
$this->read_wp_nav_fix();
$this->info('Imported a total of '.$imported.' nav fixes');
}
}

View File

@@ -2,13 +2,16 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
use GuzzleHttp\Client;
class TestApi extends BaseCommand
/**
* Class TestApi
* @package App\Console\Commands
*/
class TestApi extends Command
{
protected $signature = 'phpvms:test-api {apikey} {url}';
protected $httpClient;
/**
@@ -17,11 +20,11 @@ class TestApi extends BaseCommand
public function handle()
{
$this->httpClient = new Client([
'headers' => [
'Authorization' => $this->argument('apikey'),
'Content-type' => 'application/json',
'X-API-Key' => $this->argument('apikey'),
]
'headers' => [
'Authorization' => $this->argument('apikey'),
'Content-type' => 'application/json',
'X-API-Key' => $this->argument('apikey'),
]
]);
$result = $this->httpClient->get($this->argument('url'));

View File

@@ -2,10 +2,14 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
use Symfony\Component\Yaml\Yaml;
class Version extends BaseCommand
/**
* Class Version
* @package App\Console\Commands
*/
class Version extends Command
{
protected $signature = 'phpvms:version {--write} {--base-only}';
@@ -19,7 +23,7 @@ class Version extends BaseCommand
# prefix with the date in YYMMDD format
$date = date('ymd');
$version = $date . '-' . $version;
$version = $date.'-'.$version;
return $version;
}
@@ -46,11 +50,11 @@ class Version extends BaseCommand
# Only show the major.minor.patch version
if ($this->option('base-only')) {
$version = 'v' . $cfg['current']['major'] . '.'
. $cfg['current']['minor'] . '.'
. $cfg['current']['patch'];
$version = 'v'.$cfg['current']['major'].'.'
.$cfg['current']['minor'].'.'
.$cfg['current']['patch'];
}
print $version . "\n";
print $version."\n";
}
}

View File

@@ -2,16 +2,24 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
use App\Services\DatabaseService;
use DB;
use Symfony\Component\Yaml\Yaml;
class YamlExport extends BaseCommand
/**
* Class YamlExport
* @package App\Console\Commands
*/
class YamlExport extends Command
{
protected $signature = 'phpvms:export {tables*}';
protected $description = 'YAML table export';
/**
* YamlExport constructor.
* @param DatabaseService $dbSvc
*/
public function __construct(DatabaseService $dbSvc)
{
parent::__construct();
@@ -23,17 +31,17 @@ class YamlExport extends BaseCommand
public function handle()
{
$tables = $this->argument('tables');
if(empty($tables)) {
if (empty($tables)) {
$this->error('No tables specified');
exit();
}
$export_tables = [];
foreach($tables as $table) {
foreach ($tables as $table) {
$export_tables[$table] = [];
$rows = DB::table($table)->get();
foreach($rows as $row) {
foreach ($rows as $row) {
$export_tables[$table][] = (array) $row;
}
}

View File

@@ -2,16 +2,23 @@
namespace App\Console\Commands;
use App\Console\BaseCommand;
use App\Console\Command;
use App\Services\DatabaseService;
class YamlImport extends BaseCommand
/**
* Class YamlImport
* @package App\Console\Commands
*/
class YamlImport extends Command
{
protected $signature = 'phpvms:import {files*}';
protected $description = 'Developer commands';
protected $dbSvc;
/**
* YamlImport constructor.
* @param DatabaseService $dbSvc
*/
public function __construct(DatabaseService $dbSvc)
{
parent::__construct();
@@ -20,31 +27,28 @@ class YamlImport extends BaseCommand
/**
* Run dev related commands
* @throws \Exception
*/
public function handle()
{
$files = $this->argument('files');
if(empty($files)) {
if (empty($files)) {
$this->error('No files to import specified!');
exit();
}
$ignore_errors = true;
/*$ignore_errors = $this->option('ignore_errors');
if(!$ignore_errors) {
$ignore_errors = false;
}*/
foreach($files as $file) {
if(!file_exists($file)) {
$this->error('File ' . $file .' doesn\'t exist');
foreach ($files as $file) {
if (!file_exists($file)) {
$this->error('File '.$file.' doesn\'t exist');
exit;
}
$this->info('Importing ' . $file);
$this->info('Importing '.$file);
$imported = $this->dbSvc->seed_from_yaml_file($file, $ignore_errors);
foreach($imported as $table => $count) {
foreach ($imported as $table => $count) {
$this->info('Imported '.$count.' records from "'.$table.'"');
}
}

View File

@@ -2,7 +2,7 @@
namespace App\Console\Cron;
use App\Console\BaseCommand;
use App\Console\Command;
use App\Events\CronMonthly;
/**
@@ -10,12 +10,15 @@ use App\Events\CronMonthly;
* listeners, etc can just be called to run those tasks
* @package App\Console\Cron
*/
class Monthly extends BaseCommand
class Monthly extends Command
{
protected $signature = 'cron:monthly';
protected $description = 'Run the monthly cron tasks';
protected $schedule;
/**
*
*/
public function handle(): void
{
$this->redirectLoggingToStdout('cron');

View File

@@ -2,7 +2,7 @@
namespace App\Console\Cron;
use App\Console\BaseCommand;
use App\Console\Command;
use App\Events\CronNightly;
/**
@@ -10,12 +10,15 @@ use App\Events\CronNightly;
* listeners, etc can just be called to run those tasks
* @package App\Console\Cron
*/
class Nightly extends BaseCommand
class Nightly extends Command
{
protected $signature = 'cron:nightly';
protected $description = 'Run the nightly cron tasks';
protected $schedule;
/**
*
*/
public function handle(): void
{
$this->redirectLoggingToStdout('cron');

View File

@@ -2,7 +2,7 @@
namespace App\Console\Cron;
use App\Console\BaseCommand;
use App\Console\Command;
use App\Events\CronMonthly;
/**
@@ -10,12 +10,15 @@ use App\Events\CronMonthly;
* listeners, etc can just be called to run those tasks
* @package App\Console\Cron
*/
class Weekly extends BaseCommand
class Weekly extends Command
{
protected $signature = 'cron:monthly';
protected $description = 'Run the monthly cron tasks';
protected $schedule;
/**
*
*/
public function handle(): void
{
$this->redirectLoggingToStdout('cron');

View File

@@ -8,13 +8,12 @@ use App\Console\Cron\Weekly;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
/**
* Class Kernel
* @package App\Console
*/
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\AcarsReplay::class,
Commands\CreateDatabase::class,
@@ -28,7 +27,7 @@ class Kernel extends ConsoleKernel
/**
* Define the application's command schedule.
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule): void
@@ -45,7 +44,7 @@ class Kernel extends ConsoleKernel
protected function commands(): void
{
require app_path('Routes/console.php');
$this->load(__DIR__ . '/Commands');
$this->load(__DIR__ . '/Cron');
$this->load(__DIR__.'/Commands');
$this->load(__DIR__.'/Cron');
}
}

View File

@@ -2,7 +2,7 @@
namespace App\Console\Services;
use Doctrine\DBAL\Driver\PDOException;
use PDOException;
use PDO;
/**
@@ -13,16 +13,16 @@ class Database
{
/**
* Create the base connection DSN, optionally include the DB name
* @param $host
* @param $port
* @param $host
* @param $port
* @param null $name
* @return string
*/
public function createDsn($host, $port, $name=null)
public function createDsn($host, $port, $name = null)
{
$conn = config('database.default');
$dsn = "$conn:host=$host;port=$port";
if(filled($name)) {
if (filled($name)) {
$dsn .= ';dbname='.$name;
}

View File

@@ -15,7 +15,7 @@ use App\Models\Rank;
use App\Models\Subfleet;
use App\Models\User;
use Carbon\Carbon;
use Doctrine\DBAL\Driver\PDOException;
use PDOException;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
@@ -56,7 +56,7 @@ class Importer
*/
const BATCH_READ_ROWS = 300;
const SUBFLEET_NAME = 'Imported Aircraft';
const SUBFLEET_NAME = 'Imported Aircraft';
/**
* Importer constructor.
@@ -69,11 +69,11 @@ class Importer
# The db credentials
$this->creds = array_merge([
'host' => '127.0.0.1',
'port' => 3306,
'name' => '',
'user' => '',
'pass' => '',
'host' => '127.0.0.1',
'port' => 3306,
'name' => '',
'user' => '',
'pass' => '',
'table_prefix' => 'phpvms_'
], $db_creds);
}
@@ -105,13 +105,13 @@ class Importer
*/
protected function reconnect()
{
$dsn = 'mysql:' . implode(';', [
'host=' . $this->creds['host'],
'port=' . $this->creds['port'],
'dbname=' . $this->creds['name']
$dsn = 'mysql:'.implode(';', [
'host='.$this->creds['host'],
'port='.$this->creds['port'],
'dbname='.$this->creds['name']
]);
$this->info('Connection string: ' . $dsn);
$this->info('Connection string: '.$dsn);
try {
$this->conn = new PDO($dsn, $this->creds['user'], $this->creds['pass']);
@@ -127,14 +127,15 @@ class Importer
*/
protected function comment($message)
{
$this->log->writeln('<comment>' . $message . '</comment>');
$this->log->writeln('<comment>'.$message.'</comment>');
}
/**
* @param $message
*/
protected function error($message) {
$this->log->writeln('<error>' . $message . '</error>');
protected function error($message)
{
$this->log->writeln('<error>'.$message.'</error>');
}
/**
@@ -142,10 +143,9 @@ class Importer
*/
protected function info($message)
{
if(\is_array($message)) {
if (\is_array($message)) {
print_r($message);
}
else {
} else {
$this->log->writeln('<info>'.$message.'</info>');
}
}
@@ -157,7 +157,7 @@ class Importer
*/
protected function tableName($table)
{
if($this->creds['table_prefix'] !== false) {
if ($this->creds['table_prefix'] !== false) {
return $this->creds['table_prefix'].$table;
}
@@ -173,9 +173,10 @@ class Importer
{
try {
$model->save();
return true;
} catch (QueryException $e) {
if($e->getCode() !== '23000') {
if ($e->getCode() !== '23000') {
$this->error($e);
}
@@ -191,7 +192,7 @@ class Importer
*/
protected function addMapping($entity, $old_id, $new_id)
{
if(!array_key_exists($entity, $this->mappedEntities)) {
if (!array_key_exists($entity, $this->mappedEntities)) {
$this->mappedEntities[$entity] = [];
}
@@ -206,12 +207,12 @@ class Importer
*/
protected function getMapping($entity, $old_id)
{
if(!array_key_exists($entity, $this->mappedEntities)) {
if (!array_key_exists($entity, $this->mappedEntities)) {
return 0;
}
$entity = $this->mappedEntities[$entity];
if(array_key_exists($old_id, $entity)) {
if (array_key_exists($old_id, $entity)) {
return $entity[$old_id];
}
@@ -225,6 +226,7 @@ class Importer
protected function parseDate($date)
{
$carbon = Carbon::parse($date);
return $carbon;
}
@@ -235,9 +237,9 @@ class Importer
*/
protected function convertDuration($duration)
{
if(strpos($duration, '.') !== false) {
if (strpos($duration, '.') !== false) {
$delim = '.';
} elseif(strpos($duration, ':')) {
} elseif (strpos($duration, ':')) {
$delim = ':';
} else {
# no delimiter, assume it's just a straight hour
@@ -259,52 +261,52 @@ class Importer
{
$table = $this->tableName($table);
$sql = 'SELECT COUNT(*) FROM ' . $table;
$sql = 'SELECT COUNT(*) FROM '.$table;
$rows = $this->conn->query($sql)->fetchColumn();
$this->info('Found '.$rows.' rows in '.$table);
return (int) $rows;
}
/**
* Read all the rows in a table, but read them in a batched manner
* @param string $table The name of the table
* @param null $read_rows Number of rows to read
* @param string $table The name of the table
* @param null $read_rows Number of rows to read
* @return \Generator
*/
protected function readRows($table, $read_rows=null)
protected function readRows($table, $read_rows = null)
{
// Set the table prefix if it has been entered
$this->tableName($table);
$offset = 0;
if($read_rows === null) {
if ($read_rows === null) {
$read_rows = self::BATCH_READ_ROWS;
}
$total_rows = $this->getTotalRows($table);
while($offset < $total_rows)
{
while ($offset < $total_rows) {
$rows_to_read = $offset + $read_rows;
if($rows_to_read > $total_rows) {
if ($rows_to_read > $total_rows) {
$rows_to_read = $total_rows;
}
$this->info('Reading '.$offset.' to '.$rows_to_read.' of '.$total_rows);
$sql = 'SELECT * FROM ' . $this->tableName($table)
. ' LIMIT ' . self::BATCH_READ_ROWS . ' OFFSET ' . $offset;
$sql = 'SELECT * FROM '.$this->tableName($table)
.' LIMIT '.self::BATCH_READ_ROWS.' OFFSET '.$offset;
try {
foreach ($this->conn->query($sql) as $row) {
yield $row;
}
} catch(PDOException $e) {
} catch (PDOException $e) {
// Without incrementing the offset, it should re-run the same query
$this->error($e);
if(strpos($e->getMessage(), 'server has gone away') !== false) {
if (strpos($e->getMessage(), 'server has gone away') !== false) {
$this->reconnect();
continue;
}
@@ -344,22 +346,21 @@ class Importer
$this->comment('--- RANK IMPORT ---');
$count = 0;
foreach ($this->readRows('ranks') as $row)
{
foreach ($this->readRows('ranks') as $row) {
$rank = Rank::firstOrCreate(
['name' => $row->rank],
['image_url' => $row->rankimage, 'hours'=>$row->minhours]
['image_url' => $row->rankimage, 'hours' => $row->minhours]
);
$this->addMapping('ranks', $row->rankid, $rank->id);
$this->addMapping('ranks', $row->rank, $rank->id);
if($rank->wasRecentlyCreated) {
if ($rank->wasRecentlyCreated) {
++$count;
}
}
$this->info('Imported ' . $count . ' ranks');
$this->info('Imported '.$count.' ranks');
}
/**
@@ -371,8 +372,7 @@ class Importer
$this->comment('--- AIRLINE IMPORT ---');
$count = 0;
foreach ($this->readRows('airlines') as $row)
{
foreach ($this->readRows('airlines') as $row) {
$airline = Airline::firstOrCreate(
['icao' => $row->code],
['iata' => $row->code, 'name' => $row->name, 'active' => $row->enabled]
@@ -386,7 +386,7 @@ class Importer
}
}
$this->info('Imported '. $count.' airlines');
$this->info('Imported '.$count.' airlines');
}
/**
@@ -401,23 +401,22 @@ class Importer
$this->info('Subfleet ID is '.$subfleet->id);
$count = 0;
foreach($this->readRows('aircraft') as $row)
{
foreach ($this->readRows('aircraft') as $row) {
$aircraft = Aircraft::firstOrCreate(
['name' => $row->fullname, 'registration' => $row->registration],
['icao' => $row->icao,
['icao' => $row->icao,
'subfleet_id' => $subfleet->id,
'active' => $row->enabled
'active' => $row->enabled
]);
$this->addMapping('aircraft', $row->id, $aircraft->id);
if($aircraft->wasRecentlyCreated) {
if ($aircraft->wasRecentlyCreated) {
++$count;
}
}
$this->info('Imported ' . $count . ' aircraft');
$this->info('Imported '.$count.' aircraft');
}
/**
@@ -428,16 +427,15 @@ class Importer
$this->comment('--- AIRPORT IMPORT ---');
$count = 0;
foreach ($this->readRows('airports') as $row)
{
foreach ($this->readRows('airports') as $row) {
$attrs = [
'id' => trim($row->icao),
'icao' => trim($row->icao),
'name' => $row->name,
'id' => trim($row->icao),
'icao' => trim($row->icao),
'name' => $row->name,
'country' => $row->country,
'lat' => $row->lat,
'lon' => $row->lng,
'hub' => $row->hub,
'lat' => $row->lat,
'lon' => $row->lng,
'hub' => $row->hub,
];
$airport = Airport::updateOrCreate(
@@ -445,12 +443,12 @@ class Importer
$attrs
);
if($airport->wasRecentlyCreated) {
if ($airport->wasRecentlyCreated) {
++$count;
}
}
$this->info('Imported ' . $count . ' airports');
$this->info('Imported '.$count.' airports');
}
/**
@@ -461,8 +459,7 @@ class Importer
$this->comment('--- FLIGHT SCHEDULE IMPORT ---');
$count = 0;
foreach ($this->readRows('schedules') as $row)
{
foreach ($this->readRows('schedules') as $row) {
$airline_id = $this->getMapping('airlines', $row->code);
$flight_num = trim($row->flightnum);
@@ -470,14 +467,14 @@ class Importer
$attrs = [
'dpt_airport_id' => $row->depicao,
'arr_airport_id' => $row->arricao,
'route' => $row->route ?: '',
'distance' => round($row->distance ?: 0, 2),
'level' => $row->flightlevel ?: 0,
'dpt_time' => $row->deptime ?: '',
'arr_time' => $row->arrtime ?: '',
'flight_time' => $this->convertDuration($row->flighttime) ?: '',
'notes' => $row->notes ?: '',
'active' => $row->enabled ?: true,
'route' => $row->route ?: '',
'distance' => round($row->distance ?: 0, 2),
'level' => $row->flightlevel ?: 0,
'dpt_time' => $row->deptime ?: '',
'arr_time' => $row->arrtime ?: '',
'flight_time' => $this->convertDuration($row->flighttime) ?: '',
'notes' => $row->notes ?: '',
'active' => $row->enabled ?: true,
];
try {
@@ -493,12 +490,12 @@ class Importer
// TODO: deserialize route_details into ACARS table
if($flight->wasRecentlyCreated) {
if ($flight->wasRecentlyCreated) {
++$count;
}
}
$this->info('Imported ' . $count . ' flights');
$this->info('Imported '.$count.' flights');
}
/**
@@ -509,8 +506,7 @@ class Importer
$this->comment('--- PIREP IMPORT ---');
$count = 0;
foreach ($this->readRows('pireps') as $row)
{
foreach ($this->readRows('pireps') as $row) {
$pirep_id = $row->pirepid;
$user_id = $this->getMapping('users', $row->pilotid);
$airline_id = $this->getMapping('airlines', $row->code);
@@ -518,17 +514,17 @@ class Importer
$attrs = [
#'id' => $pirep_id,
'user_id' => $user_id,
'airline_id' => $airline_id,
'aircraft_id' => $aircraft_id,
'flight_number' => $row->flightnum ?: '',
'user_id' => $user_id,
'airline_id' => $airline_id,
'aircraft_id' => $aircraft_id,
'flight_number' => $row->flightnum ?: '',
'dpt_airport_id' => $row->depicao,
'arr_airport_id' => $row->arricao,
'block_fuel' => $row->fuelused,
'route' => $row->route ?: '',
'source_name' => $row->source,
'created_at' => $this->parseDate($row->submitdate),
'updated_at' => $this->parseDate($row->modifieddate),
'block_fuel' => $row->fuelused,
'route' => $row->route ?: '',
'source_name' => $row->source,
'created_at' => $this->parseDate($row->submitdate),
'updated_at' => $this->parseDate($row->modifieddate),
];
# Set the distance
@@ -542,7 +538,7 @@ class Importer
$attrs['planned_flight_time'] = $duration;
# Set how it was filed
if(strtoupper($row->source) === 'MANUAL') {
if (strtoupper($row->source) === 'MANUAL') {
$attrs['source'] = PirepSource::MANUAL;
} else {
$attrs['source'] = PirepSource::ACARS;
@@ -550,16 +546,16 @@ class Importer
# Set the flight type
$row->flighttype = strtoupper($row->flighttype);
if($row->flighttype === 'P') {
if ($row->flighttype === 'P') {
$attrs['flight_type'] = FlightType::PASSENGER;
} elseif($row->flighttype === 'C') {
} elseif ($row->flighttype === 'C') {
$attrs['flight_type'] = FlightType::CARGO;
} else {
$attrs['flight_type'] = FlightType::CHARTER;
}
# Set the flight level of the PIREP is set
if(property_exists($row, 'flightlevel')) {
if (property_exists($row, 'flightlevel')) {
$attrs['level'] = $row->flightlevel;
} else {
$attrs['level'] = 0;
@@ -571,11 +567,11 @@ class Importer
);
$source = strtoupper($row->source);
if($source === 'SMARTCARS') {
if ($source === 'SMARTCARS') {
# TODO: Parse smartcars log into the acars table
} elseif($source === 'KACARS') {
} elseif ($source === 'KACARS') {
# TODO: Parse kACARS log into acars table
} elseif($source === 'XACARS') {
} elseif ($source === 'XACARS') {
# TODO: Parse XACARS log into acars table
}
@@ -587,7 +583,7 @@ class Importer
}
}
$this->info('Imported ' . $count . ' pireps');
$this->info('Imported '.$count.' pireps');
}
protected function importUsers()
@@ -596,10 +592,9 @@ class Importer
$count = 0;
foreach ($this->readRows('pilots', 50) as $row) {
# TODO: What to do about pilot ids
$name = $row->firstname . ' ' . $row->lastname;
$name = $row->firstname.' '.$row->lastname;
$airline_id = $this->getMapping('airlines', $row->code);
$rank_id = $this->getMapping('ranks', $row->rank);
@@ -608,17 +603,17 @@ class Importer
$new_password = Str::random(60);
$attrs = [
'name' => $name,
'password' => Hash::make($new_password),
'api_key' => Utils::generateApiKey(),
'airline_id' => $airline_id,
'rank_id' => $rank_id,
'name' => $name,
'password' => Hash::make($new_password),
'api_key' => Utils::generateApiKey(),
'airline_id' => $airline_id,
'rank_id' => $rank_id,
'home_airport_id' => $row->hub,
'curr_airport_id' => $row->hub,
'flights' => (int)$row->totalflights,
'flight_time' => Utils::hoursToMinutes($row->totalhours),
'state' => $state,
'created_at' => $this->parseDate($row->joindate),
'flights' => (int) $row->totalflights,
'flight_time' => Utils::hoursToMinutes($row->totalhours),
'state' => $state,
'created_at' => $this->parseDate($row->joindate),
];
$user = User::updateOrCreate(
@@ -633,7 +628,7 @@ class Importer
}
}
$this->info('Imported ' . $count . ' users');
$this->info('Imported '.$count.' users');
}
/**
@@ -641,7 +636,6 @@ class Importer
*/
protected function findLastPireps()
{
}
/**
@@ -665,9 +659,9 @@ class Importer
// Declare array of classic states
$phpvms_classic_states = [
'ACTIVE' => 0,
'ACTIVE' => 0,
'INACTIVE' => 1,
'BANNED' => 2,
'BANNED' => 2,
'ON_LEAVE' => 3
];
@@ -682,7 +676,7 @@ class Importer
} elseif ($state === $phpvms_classic_states['ON_LEAVE']) {
return UserState::ON_LEAVE;
} else {
$this->error('Unknown status: '. $state);
$this->error('Unknown status: '.$state);
}
}
}