Skip to content

Commit

Permalink
less instantiation
Browse files Browse the repository at this point in the history
  • Loading branch information
HerrLevin committed Dec 11, 2024
1 parent c3a0906 commit 6ed73fe
Show file tree
Hide file tree
Showing 15 changed files with 174 additions and 185 deletions.
8 changes: 7 additions & 1 deletion app/Console/Commands/RefreshCurrentTrips.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Console\Commands;

use App\DataProviders\DataProviderFactory;
use App\DataProviders\DataProviderInterface;
use App\DataProviders\HafasController;
use App\DataProviders\HafasStopoverService;
use App\Enum\TripSource;
Expand All @@ -17,6 +18,11 @@ class RefreshCurrentTrips extends Command
protected $signature = 'trwl:refreshTrips';
protected $description = 'Refresh delay data from current active trips';

private function getDataProvider(): DataProviderInterface {
// Probably only HafasController is needed here, because this Command is very Hafas specific
return (new DataProviderFactory)->create(HafasController::class);
}

public function handle(): int {
$this->info('Getting trips to be refreshed...');

Expand Down Expand Up @@ -55,7 +61,7 @@ public function handle(): int {
$this->info('Refreshing trip ' . $trip->trip_id . ' (' . $trip->linename . ')...');
$trip->update(['last_refreshed' => now()]);

$rawHafas = (new DataProviderFactory)->create(HafasController::class)::fetchRawHafasTrip($trip->trip_id, $trip->linename);
$rawHafas = $this->getDataProvider()::fetchRawHafasTrip($trip->trip_id, $trip->linename);
$updatedCounts = HafasStopoverService::refreshStopovers($rawHafas);
$this->info('Updated ' . $updatedCounts->stopovers . ' stopovers.');

Expand Down
13 changes: 0 additions & 13 deletions app/DataProviders/DataProviderFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,6 @@

class DataProviderFactory
{
/**
* @template T of DataProviderInterface
* @param class-string<T> $class
*
* @return T
* @throws InvalidArgumentException
*/
public static function createDataProvider(string $class) {
$self = new self();

return $self->create($class);
}

/**
* @template T of DataProviderInterface
* @param class-string<T> $class
Expand Down
16 changes: 14 additions & 2 deletions app/DataProviders/HafasStopoverService.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@

class HafasStopoverService
{
private DataProviderInterface $dataProvider;

/**
* @template T of DataProviderInterface
* @param class-string<T> $dataProvider
* @param DataProviderFactory|null $dataProviderFactory
*/
public function __construct(string $dataProvider, ?DataProviderFactory $dataProviderFactory = null) {
$dataProviderFactory ??= new DataProviderFactory();
$this->dataProvider = $dataProviderFactory->create($dataProvider);
}

public static function refreshStopovers(stdClass $rawHafas): stdClass {
$stopoversUpdated = 0;
$payloadArrival = [];
Expand Down Expand Up @@ -72,8 +84,8 @@ public static function refreshStopovers(stdClass $rawHafas): stdClass {
* @return void
* @throws HafasException
*/
public static function refreshStopover(Stopover $stopover): void {
$departure = (new DataProviderFactory)->create(HafasController::class)::getDepartures(
public function refreshStopover(Stopover $stopover): void {
$departure = $this->dataProvider::getDepartures(
station: $stopover->station,
when: $stopover->departure_planned,
)->filter(function(stdClass $trip) use ($stopover) {
Expand Down
10 changes: 10 additions & 0 deletions app/Http/Controllers/API/v1/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace App\Http\Controllers\API\v1;

use App\DataProviders\DataProviderFactory;
use App\DataProviders\DataProviderInterface;
use App\DataProviders\HafasController;
use App\Models\OAuthClient;
use App\Models\User;
use Illuminate\Contracts\Auth\Authenticatable;
Expand Down Expand Up @@ -96,6 +99,13 @@
*/
class Controller extends \App\Http\Controllers\Controller
{
protected DataProviderInterface $dataProvider;

public function __construct() {
// todo: set data provider based on user settings
$this->dataProvider = (new DataProviderFactory())->create(HafasController::class);
}

public function sendResponse(
mixed $data = null,
int $code = 200,
Expand Down
4 changes: 1 addition & 3 deletions app/Http/Controllers/API/v1/EventController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace App\Http\Controllers\API\v1;

use App\DataProviders\DataProviderFactory;
use App\DataProviders\HafasController;
use App\Http\Controllers\Backend\EventController as EventBackend;
use App\Http\Controllers\StatusController;
use App\Http\Resources\EventDetailsResource;
Expand Down Expand Up @@ -251,7 +249,7 @@ public function suggest(Request $request): JsonResponse {
]);

if (isset($validated['nearestStation'])) {
$stations = (new DataProviderFactory)->create(HafasController::class)::getStations($validated['nearestStation'], 1);
$stations = $this->dataProvider::getStations($validated['nearestStation'], 1);
if (count($stations) === 0) {
return $this->sendError(error: __('events.request.station_not_found'), code: 400);
}
Expand Down
7 changes: 3 additions & 4 deletions app/Http/Controllers/API/v1/TransportController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace App\Http\Controllers\API\v1;

use App\DataProviders\DataProviderFactory;
use App\DataProviders\HafasController;
use App\Dto\Transport\Station as StationDto;
use App\Enum\Business;
Expand Down Expand Up @@ -154,7 +153,7 @@ public function getDepartures(Request $request, int $stationId): JsonResponse {
$station = Station::findOrFail($stationId);

try {
$departures = (new DataProviderFactory)->create(HafasController::class)::getDepartures(
$departures = $this->dataProvider::getDepartures(
station: $station,
when: $timestamp,
type: TravelType::tryFrom($validated['travelType'] ?? null),
Expand Down Expand Up @@ -312,7 +311,7 @@ public function getNextStationByCoordinates(Request $request): JsonResponse {
]);

try {
$nearestStation = (new DataProviderFactory)->create(HafasController::class)::getNearbyStations(
$nearestStation = $this->dataProvider::getNearbyStations(
latitude: $validated['latitude'],
longitude: $validated['longitude'],
results: 1
Expand Down Expand Up @@ -514,7 +513,7 @@ public function setHome(int $stationId): JsonResponse {
*/
public function getTrainStationAutocomplete(string $query): JsonResponse {
try {
$trainAutocompleteResponse = TransportBackend::getTrainStationAutocomplete($query);
$trainAutocompleteResponse = (new TransportBackend(HafasController::class))->getTrainStationAutocomplete($query);
return $this->sendResponse($trainAutocompleteResponse);
} catch (HafasException) {
return $this->sendError("There has been an error with our data provider", 503);
Expand Down
35 changes: 0 additions & 35 deletions app/Http/Controllers/Backend/Transport/StationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@

namespace App\Http\Controllers\Backend\Transport;

use App\DataProviders\DataProviderFactory;
use App\DataProviders\HafasController;
use App\Exceptions\HafasException;
use App\Http\Controllers\Controller;
use App\Http\Resources\StationResource;
use App\Models\Checkin;
use App\Models\Station;
use App\Models\Stopover;
use App\Models\User;
use App\Repositories\StationRepository;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
Expand All @@ -25,36 +20,6 @@ public function __construct(?StationRepository $stationRepository = null) {
$this->stationRepository = $stationRepository ?? new StationRepository();
}

/**
* @throws HafasException
* @throws ModelNotFoundException
*/
public static function lookupStation(string|int $query): Station {
//Lookup by station ibnr
if (is_numeric($query)) {
$station = Station::where('ibnr', $query)->first();
if ($station !== null) {
return $station;
}
}

//Lookup by ril identifier
if (!is_numeric($query) && strlen($query) <= 5 && ctype_upper($query)) {
$station = (new DataProviderFactory)->create(HafasController::class)::getStationByRilIdentifier($query);
if ($station !== null) {
return $station;
}
}

//Lookup HAFAS
$station = (new DataProviderFactory)->create(HafasController::class)::getStations(query: $query, results: 1)->first();
if ($station !== null) {
return $station;
}

throw new ModelNotFoundException;
}

/**
* Get the latest Stations the user is arrived.
*
Expand Down
80 changes: 78 additions & 2 deletions app/Http/Controllers/Frontend/Admin/CheckinController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace App\Http\Controllers\Frontend\Admin;

use App\DataProviders\DataProviderFactory;
use App\DataProviders\HafasController;
use App\Enum\Business;
use App\Enum\StatusVisibility;
use App\Enum\TravelType;
Expand All @@ -10,22 +12,96 @@
use App\Exceptions\StationNotOnTripException;
use App\Exceptions\TrainCheckinAlreadyExistException;
use App\Http\Controllers\Backend\Transport\TrainCheckinController;
use App\Http\Controllers\TransportController as TransportBackend;
use App\Hydrators\CheckinRequestHydrator;
use App\Models\Event;
use App\Models\Station;
use App\Models\Status;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rules\Enum;
use Illuminate\View\View;
use JetBrains\PhpStorm\ArrayShape;
use Throwable;

class CheckinController
{
/**
* @throws HafasException
* @throws ModelNotFoundException
* @deprecated adapt admin panel to api endpoints
*/
public static function lookupStation(string|int $query): Station {
//Lookup by station ibnr
if (is_numeric($query)) {
$station = Station::where('ibnr', $query)->first();
if ($station !== null) {
return $station;
}
}

//Lookup by ril identifier
if (!is_numeric($query) && strlen($query) <= 5 && ctype_upper($query)) {
$station = (new DataProviderFactory)->create(HafasController::class)::getStationByRilIdentifier($query);
if ($station !== null) {
return $station;
}
}

//Lookup HAFAS
$station = (new DataProviderFactory)->create(HafasController::class)::getStations(query: $query, results: 1)->first();
if ($station !== null) {
return $station;
}

throw new ModelNotFoundException;
}

/**
* @param string|int $stationQuery
* @param Carbon|null $when
* @param TravelType|null $travelType
* @param bool $localtime
*
* @return array
* @throws HafasException
* @deprecated use DataProviderInterface::getDepartures(...) directly instead (-> less overhead)
*/
#[ArrayShape([
'station' => Station::class,
'departures' => Collection::class,
'times' => "array"
])]
public static function getDepartures(
string|int $stationQuery,
Carbon $when = null,
TravelType $travelType = null,
bool $localtime = false
): array {
$station = self::lookupStation($stationQuery);

$when = $when ?? Carbon::now()->subMinutes(5);
$times = [
'now' => $when,
'prev' => $when->clone()->subMinutes(15),
'next' => $when->clone()->addMinutes(15)
];

$departures = (new DataProviderFactory)->create(HafasController::class)::getDepartures(
station: $station,
when: $when,
type: $travelType,
localtime: $localtime
)->sortBy(function($departure) {
return $departure->when ?? $departure->plannedWhen;
});

return ['station' => $station, 'departures' => $departures->values(), 'times' => $times];
}

public function renderStationboard(Request $request): View|RedirectResponse {
$validated = $request->validate([
Expand All @@ -52,7 +128,7 @@ public function renderStationboard(Request $request): View|RedirectResponse {

if (isset($validated['station'])) {
try {
$trainStationboardResponse = TransportBackend::getDepartures(
$trainStationboardResponse = self::getDepartures(
stationQuery: $validated['station'],
when: $when,
travelType: TravelType::tryFrom($validated['filter'] ?? null),
Expand Down
29 changes: 4 additions & 25 deletions app/Http/Controllers/FrontendTransportController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,10 @@

namespace App\Http\Controllers;

use App\Dto\CheckinSuccess;
use App\Enum\Business;
use App\Enum\StatusVisibility;
use App\Enum\TravelType;
use App\Exceptions\Checkin\AlreadyCheckedInException;
use App\Exceptions\CheckInCollisionException;
use App\DataProviders\HafasController;
use App\Exceptions\HafasException;
use App\Exceptions\StationNotOnTripException;
use App\Exceptions\TrainCheckinAlreadyExistException;
use App\Http\Controllers\Backend\Helper\StatusHelper;
use App\Http\Controllers\Backend\Transport\HomeController;
use App\Http\Controllers\Backend\Transport\StationController;
use App\Http\Controllers\Backend\Transport\TrainCheckinController;
use App\Http\Controllers\TransportController as TransportBackend;
use App\Models\Event;
use App\Models\Station;
use App\Models\Stopover;
use App\Models\Trip;
use Carbon\Carbon;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rules\Enum;
use Throwable;

/**
* @deprecated Content will be moved to the backend/frontend/API packages soon, please don't add new functions here!
Expand All @@ -37,7 +14,9 @@ class FrontendTransportController extends Controller
{
public function TrainAutocomplete(string $station): JsonResponse {
try {
$trainAutocompleteResponse = TransportBackend::getTrainStationAutocomplete($station);
//todo: adapt data provider to users preferences
$provider = new TransportBackend(HafasController::class);
$trainAutocompleteResponse = $provider->getTrainStationAutocomplete($station);
return response()->json($trainAutocompleteResponse);
} catch (HafasException $e) {
abort(503, $e->getMessage());
Expand Down
Loading

0 comments on commit 6ed73fe

Please sign in to comment.