Skip to content

Commit

Permalink
nabeelio#355 Calculate distance button (nabeelio#366)
Browse files Browse the repository at this point in the history
* nabeelio#355 Calculate distance button in add/edit Flight page

* Styling

* Move add/edit flight logic out of controller and into service layer

* Styling

* Formatting

* Run styleci against modules dir

* Styleci config

* Style fixes in /modules
  • Loading branch information
nabeelio authored Aug 26, 2019
1 parent 25999d5 commit bbec276
Show file tree
Hide file tree
Showing 57 changed files with 9,128 additions and 6,831 deletions.
7 changes: 3 additions & 4 deletions .styleci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ disabled:
# - unalign_equals
finder:
exclude:
- modules
- node_modules
- storage
- vendor
- node_modules
- storage
- vendor
name: "*.php"
not-name: "*.blade.php"
1 change: 1 addition & 0 deletions .travis/deploy_script.sh
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ if [ "$TRAVIS" = "true" ]; then
.phpstorm.meta.php
.styleci.yml
env.php
intellij_style.xml
config.php
docker-compose.yml
Makefile
Expand Down
41 changes: 41 additions & 0 deletions app/Exceptions/AirportNotFound.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace App\Exceptions;

class AirportNotFound extends HttpException
{
private $icao;

public function __construct($icao)
{
$this->icao = $icao;
parent::__construct(
404,
'Airport '.$icao.' not found'
);
}

/**
* Return the RFC 7807 error type (without the URL root)
*/
public function getErrorType(): string
{
return 'airport-not-found';
}

/**
* Get the detailed error string
*/
public function getErrorDetails(): string
{
return $this->getMessage();
}

/**
* Return an array with the error details, merged with the RFC7807 response
*/
public function getErrorMetadata(): array
{
return [];
}
}
45 changes: 45 additions & 0 deletions app/Exceptions/DuplicateFlight.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace App\Exceptions;

use App\Models\Flight;

class DuplicateFlight extends HttpException
{
private $flight;

public function __construct(Flight $flight)
{
$this->flight = $flight;
parent::__construct(
409,
'Duplicate flight with same number/code/leg found'
);
}

/**
* Return the RFC 7807 error type (without the URL root)
*/
public function getErrorType(): string
{
return 'duplicate-flight';
}

/**
* Get the detailed error string
*/
public function getErrorDetails(): string
{
return $this->getMessage();
}

/**
* Return an array with the error details, merged with the RFC7807 response
*/
public function getErrorMetadata(): array
{
return [
'flight_id' => $this->flight->id,
];
}
}
60 changes: 14 additions & 46 deletions app/Http/Controllers/Admin/FlightController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use App\Contracts\Controller;
use App\Http\Requests\CreateFlightRequest;
use App\Http\Requests\UpdateFlightRequest;
use App\Models\Enums\Days;
use App\Models\Enums\FlightType;
use App\Models\Flight;
use App\Models\FlightField;
Expand All @@ -22,11 +21,9 @@
use App\Services\FlightService;
use App\Services\ImportService;
use App\Support\Units\Time;
use Flash;
use Illuminate\Http\Request;
use Log;
use Response;
use Storage;
use Illuminate\Support\Facades\Log;
use Laracasts\Flash\Flash;

/**
* Class FlightController
Expand Down Expand Up @@ -172,28 +169,15 @@ public function create()
*/
public function store(CreateFlightRequest $request)
{
$input = $request->all();
try {
$flight = $this->flightSvc->createFlight($request->all());
Flash::success('Flight saved successfully.');

// Create a temporary flight so we can validate
$flight = new Flight($input);
if ($this->flightSvc->isFlightDuplicate($flight)) {
Flash::error('Duplicate flight with same number/code/leg found, please change to proceed');
return redirect(route('admin.flights.edit', $flight->id));
} catch (\Exception $e) {
Flash::error($e->getMessage());
return redirect()->back()->withInput($request->all());
}

if (array_key_exists('days', $input) && filled($input['days'])) {
$input['days'] = Days::getDaysMask($input['days']);
}

$input['active'] = get_truth_state($input['active']);

$time = new Time($input['minutes'], $input['hours']);
$input['flight_time'] = $time->getMinutes();

$flight = $this->flightRepo->create($input);

Flash::success('Flight saved successfully.');
return redirect(route('admin.flights.edit', $flight->id));
}

/**
Expand Down Expand Up @@ -268,32 +252,16 @@ public function update($id, UpdateFlightRequest $request)
return redirect(route('admin.flights.index'));
}

$input = $request->all();
try {
$this->flightSvc->updateFlight($flight, $request->all());
Flash::success('Flight updated successfully.');

// apply the updates here temporarily, don't save
// the repo->update() call will actually do it
$flight->fill($input);
return redirect(route('admin.flights.index'));
} catch (\Exception $e) {
Flash::error($e->getMessage());

if ($this->flightSvc->isFlightDuplicate($flight)) {
Flash::error('Duplicate flight with same number/code/leg found, please change to proceed');
return redirect()->back()->withInput($request->all());
}

if (array_key_exists('days', $input) && filled($input['days'])) {
$input['days'] = Days::getDaysMask($input['days']);
}

$input['flight_time'] = Time::init(
$input['minutes'],
$input['hours']
)->getMinutes();

$input['active'] = get_truth_state($input['active']);

$this->flightRepo->update($input, $id);

Flash::success('Flight updated successfully.');
return redirect(route('admin.flights.index'));
}

/**
Expand Down
19 changes: 19 additions & 0 deletions app/Http/Controllers/Api/AirportController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Contracts\Controller;
use App\Http\Resources\Airport as AirportResource;
use App\Http\Resources\AirportDistance as AirportDistanceResource;
use App\Repositories\AirportRepository;
use App\Services\AirportService;
use Illuminate\Http\Request;
Expand Down Expand Up @@ -93,4 +94,22 @@ public function lookup($id)
$airport = $this->airportSvc->lookupAirport($id);
return new AirportResource(collect($airport));
}

/**
* Do a lookup, via vaCentral, for the airport information
*
* @param $fromIcao
* @param $toIcao
*
* @return AirportDistanceResource
*/
public function distance($fromIcao, $toIcao)
{
$distance = $this->airportSvc->calculateDistance($fromIcao, $toIcao);
return new AirportDistanceResource([
'fromIcao' => $fromIcao,
'toIcao' => $toIcao,
'distance' => $distance,
]);
}
}
1 change: 1 addition & 0 deletions app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class Kernel extends HttpKernel
//\Spatie\Pjax\Middleware\FilterIfPjax::class,
],
];

protected $routeMiddleware = [
'api.auth' => ApiAuth::class,
'auth' => Authenticate::class,
Expand Down
14 changes: 14 additions & 0 deletions app/Http/Resources/AirportDistance.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace App\Http\Resources;

class AirportDistance extends Response
{
public function toArray($request)
{
$res = parent::toArray($request);
$res['distance'] = $res['distance']->getResponseUnits();

return $res;
}
}
1 change: 1 addition & 0 deletions app/Http/Routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
Route::get('airports/hubs', 'AirportController@index_hubs');
Route::get('airports/{id}', 'AirportController@get');
Route::get('airports/{id}/lookup', 'AirportController@lookup');
Route::get('airports/{id}/distance/{to}', 'AirportController@distance');

Route::get('fleet', 'FleetController@index');
Route::get('fleet/aircraft/{id}', 'FleetController@get_aircraft');
Expand Down
48 changes: 48 additions & 0 deletions app/Services/AirportService.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,33 @@
use App\Contracts\AirportLookup as AirportLookupProvider;
use App\Contracts\Metar as MetarProvider;
use App\Contracts\Service;
use App\Exceptions\AirportNotFound;
use App\Repositories\AirportRepository;
use App\Support\Metar;
use App\Support\Units\Distance;
use Illuminate\Support\Facades\Cache;
use League\Geotools\Coordinate\Coordinate;
use League\Geotools\Geotools;
use PhpUnitsOfMeasure\Exception\NonNumericValue;
use PhpUnitsOfMeasure\Exception\NonStringUnitName;
use VaCentral\Airport;

/**
* Class AnalyticsService
*/
class AirportService extends Service
{
private $airportRepo;
private $lookupProvider;
private $metarProvider;

public function __construct(
AirportLookupProvider $lookupProvider,
AirportRepository $airportRepo,
MetarProvider $metarProvider

) {
$this->airportRepo = $airportRepo;
$this->lookupProvider = $lookupProvider;
$this->metarProvider = $metarProvider;
}
Expand Down Expand Up @@ -76,4 +86,42 @@ public function lookupAirport($icao)

return $airport;
}

/**
* Calculate the distance from one airport to another
*
* @param string $fromIcao
* @param string $toIcao
*
* @return Distance
*/
public function calculateDistance($fromIcao, $toIcao)
{
$from = $this->airportRepo->find($fromIcao, ['lat', 'lon']);
$to = $this->airportRepo->find($toIcao, ['lat', 'lon']);

if (!$from) {
throw new AirportNotFound($fromIcao);
}

if (!$to) {
throw new AirportNotFound($toIcao);
}

// Calculate the distance
$geotools = new Geotools();
$start = new Coordinate([$from->lat, $from->lon]);
$end = new Coordinate([$to->lat, $to->lon]);
$dist = $geotools->distance()->setFrom($start)->setTo($end);

// Convert into a Distance object
try {
$distance = new Distance($dist->in('mi')->greatCircle(), 'mi');
return $distance;
} catch (NonNumericValue $e) {
return;
} catch (NonStringUnitName $e) {
return;
}
}
}
Loading

0 comments on commit bbec276

Please sign in to comment.