Skip to content

Commit

Permalink
FULLY PREPARED FOR MULTIPLE DATA SOURCES
Browse files Browse the repository at this point in the history
  • Loading branch information
HerrLevin committed Dec 11, 2024
1 parent 6ed73fe commit 6d086e7
Show file tree
Hide file tree
Showing 14 changed files with 89 additions and 76 deletions.
2 changes: 1 addition & 1 deletion app/Console/Commands/RefreshCurrentTrips.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function handle(): int {
$this->info('Refreshing trip ' . $trip->trip_id . ' (' . $trip->linename . ')...');
$trip->update(['last_refreshed' => now()]);

$rawHafas = $this->getDataProvider()::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
16 changes: 7 additions & 9 deletions app/DataProviders/DataProviderInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,17 @@

interface DataProviderInterface
{
public static function fetchHafasTrip(string $tripID, string $lineName);
public function fetchHafasTrip(string $tripID, string $lineName);

public static function fetchRawHafasTrip(string $tripId, string $lineName);
public function fetchRawHafasTrip(string $tripId, string $lineName);

public static function getStations(string $query, int $results);
public function getStations(string $query, int $results);

public static function getDepartures(Station $station, Carbon $when, int $duration = 15, TravelType $type = null, bool $localtime = false);
public function getDepartures(Station $station, Carbon $when, int $duration = 15, TravelType $type = null, bool $localtime = false);

public static function fetchDepartures(Station $station, Carbon $when, int $duration, TravelType $type, bool $skipTimeShift);
public function getNearbyStations(float $latitude, float $longitude, int $results);

public static function getNearbyStations(float $latitude, float $longitude, int $results);
public function getStationByRilIdentifier(string $rilIdentifier);

public static function getStationByRilIdentifier(string $rilIdentifier);

public static function getStationsByFuzzyRilIdentifier(string $rilIdentifier);
public function getStationsByFuzzyRilIdentifier(string $rilIdentifier);
}
71 changes: 37 additions & 34 deletions app/DataProviders/HafasController.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,20 @@

class HafasController extends Controller implements DataProviderInterface
{
private static function getHttpClient(): PendingRequest {

private function client(): PendingRequest {
return Http::baseUrl(config('trwl.db_rest'))
->timeout(config('trwl.db_rest_timeout'));
}

public static function getStationByRilIdentifier(string $rilIdentifier): ?Station {
public function getStationByRilIdentifier(string $rilIdentifier): ?Station {
$station = Station::where('rilIdentifier', $rilIdentifier)->first();
if ($station !== null) {
return $station;
}

try {
$response = self::getHttpClient()
->get("/stations/$rilIdentifier");
$response = $this->client()->get("/stations/$rilIdentifier");
if ($response->ok() && !empty($response->body()) && $response->body() !== '[]') {
$data = json_decode($response->body(), false, 512, JSON_THROW_ON_ERROR);
$station = StationRepository::parseHafasStopObject($data);
Expand All @@ -49,29 +49,30 @@ public static function getStationByRilIdentifier(string $rilIdentifier): ?Statio
return $station;
}

public static function getStationsByFuzzyRilIdentifier(string $rilIdentifier): ?Collection {
public function getStationsByFuzzyRilIdentifier(string $rilIdentifier): ?Collection {
$stations = Station::where('rilIdentifier', 'LIKE', "$rilIdentifier%")->orderBy('rilIdentifier')->get();
if ($stations->count() > 0) {
return $stations;
}
return collect([self::getStationByRilIdentifier(rilIdentifier: $rilIdentifier)]);
return collect([$this->getStationByRilIdentifier(rilIdentifier: $rilIdentifier)]);
}

/**
* @throws HafasException
*/
public static function getStations(string $query, int $results = 10): Collection {
public function getStations(string $query, int $results = 10): Collection {
try {
$response = self::getHttpClient()
->get("/locations",
[
'query' => $query,
'fuzzy' => 'true',
'stops' => 'true',
'addresses' => 'false',
'poi' => 'false',
'results' => $results
]);
$response = $this->client()->get(
"/locations",
[
'query' => $query,
'fuzzy' => 'true',
'stops' => 'true',
'addresses' => 'false',
'poi' => 'false',
'results' => $results
]
);

$data = json_decode($response->body(), false, 512, JSON_THROW_ON_ERROR);
if (empty($data) || !$response->ok()) {
Expand All @@ -87,13 +88,16 @@ public static function getStations(string $query, int $results = 10): Collection
/**
* @throws HafasException
*/
public static function getNearbyStations(float $latitude, float $longitude, int $results = 8): Collection {
public function getNearbyStations(float $latitude, float $longitude, int $results = 8): Collection {
try {
$response = self::getHttpClient()->get("/stops/nearby", [
'latitude' => $latitude,
'longitude' => $longitude,
'results' => $results
]);
$response = $this->client()->get(
"/stops/nearby",
[
'latitude' => $latitude,
'longitude' => $longitude,
'results' => $results
]
);

if (!$response->ok()) {
throw new HafasException(__('messages.exception.generalHafas'));
Expand All @@ -117,14 +121,13 @@ public static function getNearbyStations(float $latitude, float $longitude, int
* @throws HafasException
* @throws JsonException
*/
public static function fetchDepartures(
private function fetchDepartures(
Station $station,
Carbon $when,
int $duration = 15,
TravelType $type = null,
bool $skipTimeShift = false
) {
$client = self::getHttpClient();
$time = $skipTimeShift ? $when : (clone $when)->shiftTimezone("Europe/Berlin");
$query = [
'when' => $time->toIso8601String(),
Expand All @@ -140,7 +143,7 @@ public static function fetchDepartures(
HTT::TRAM->value => FptfHelper::checkTravelType($type, TravelType::TRAM),
HTT::TAXI->value => FptfHelper::checkTravelType($type, TravelType::TAXI),
];
$response = $client->get('/stops/' . $station->ibnr . '/departures', $query);
$response = $this->client()->get('/stops/' . $station->ibnr . '/departures', $query);

if (!$response->ok()) {
throw new HafasException(__('messages.exception.generalHafas'));
Expand All @@ -159,7 +162,7 @@ public static function fetchDepartures(
* @return Collection
* @throws HafasException
*/
public static function getDepartures(
public function getDepartures(
Station $station,
Carbon $when,
int $duration = 15,
Expand All @@ -169,7 +172,7 @@ public static function getDepartures(
try {
$requestTime = is_null($station->time_offset) || $localtime
? $when : (clone $when)->subHours($station->time_offset);
$data = self::fetchDepartures(
$data = $this->fetchDepartures(
$station,
$requestTime,
$duration,
Expand All @@ -188,14 +191,14 @@ public static function getDepartures(
// Check if the timezone for this station is equal in its offset to Europe/Berlin.
// If so, fetch again **without** adjusting the timezone
if ($timezone === CarbonTimeZone::create("Europe/Berlin")->toOffsetName()) {
$data = self::fetchDepartures($station, $when, $duration, $type, true);
$data = $this->fetchDepartures($station, $when, $duration, $type, true);

$station->shift_time = false;
$station->save();
break;
}
// if the timezone is not equal to Europe/Berlin, fetch the offset
$data = self::fetchDepartures($station, (clone $when)->subHours($offset), $duration, $type);
$data = $this->fetchDepartures($station, (clone $when)->subHours($offset), $duration, $type);

$station->time_offset = $offset;
$station->save();
Expand Down Expand Up @@ -236,8 +239,8 @@ public static function getDepartures(
/**
* @throws HafasException|JsonException
*/
public static function fetchRawHafasTrip(string $tripId, string $lineName) {
$tripResponse = self::getHttpClient()->get("trips/" . rawurlencode($tripId), [
public function fetchRawHafasTrip(string $tripId, string $lineName) {
$tripResponse = $this->client()->get("trips/" . rawurlencode($tripId), [
'lineName' => $lineName,
'polyline' => 'true',
'stopovers' => 'true'
Expand Down Expand Up @@ -265,8 +268,8 @@ public static function fetchRawHafasTrip(string $tripId, string $lineName) {
* @return Trip
* @throws HafasException|JsonException
*/
public static function fetchHafasTrip(string $tripID, string $lineName): Trip {
$tripJson = self::fetchRawHafasTrip($tripID, $lineName);
public function fetchHafasTrip(string $tripID, string $lineName): Trip {
$tripJson = $this->fetchRawHafasTrip($tripID, $lineName);
$origin = Repositories\StationRepository::parseHafasStopObject($tripJson->origin);
$destination = Repositories\StationRepository::parseHafasStopObject($tripJson->destination);
$operator = null;
Expand Down
2 changes: 1 addition & 1 deletion app/DataProviders/HafasStopoverService.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public static function refreshStopovers(stdClass $rawHafas): stdClass {
* @throws HafasException
*/
public function refreshStopover(Stopover $stopover): void {
$departure = $this->dataProvider::getDepartures(
$departure = $this->dataProvider->getDepartures(
station: $stopover->station,
when: $stopover->departure_planned,
)->filter(function(stdClass $trip) use ($stopover) {
Expand Down
7 changes: 4 additions & 3 deletions app/DataProviders/Repositories/StationRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ public static function parseHafasStopObject(stdClass $hafasStop): Station {
$data['rilIdentifier'] = $hafasStop->ril100;
}

return Station::updateOrCreate([
'ibnr' => $hafasStop->id
], $data);
return Station::updateOrCreate(
['ibnr' => $hafasStop->id],
$data
);
}

public static function parseHafasStops(array $hafasResponse): Collection {
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Controllers/API/v1/EventController.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ public function suggest(Request $request): JsonResponse {
]);

if (isset($validated['nearestStation'])) {
$stations = $this->dataProvider::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
4 changes: 2 additions & 2 deletions app/Http/Controllers/API/v1/TransportController.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public function getDepartures(Request $request, int $stationId): JsonResponse {
$station = Station::findOrFail($stationId);

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

try {
$nearestStation = $this->dataProvider::getNearbyStations(
$nearestStation = $this->dataProvider->getNearbyStations(
latitude: $validated['latitude'],
longitude: $validated['longitude'],
results: 1
Expand Down
14 changes: 8 additions & 6 deletions app/Http/Controllers/Frontend/Admin/CheckinController.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ class CheckinController
* @deprecated adapt admin panel to api endpoints
*/
public static function lookupStation(string|int $query): Station {
$dataProvider = (new DataProviderFactory)->create(HafasController::class);

//Lookup by station ibnr
if (is_numeric($query)) {
$station = Station::where('ibnr', $query)->first();
Expand All @@ -46,14 +48,14 @@ public static function lookupStation(string|int $query): Station {

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

//Lookup HAFAS
$station = (new DataProviderFactory)->create(HafasController::class)::getStations(query: $query, results: 1)->first();
$station = $dataProvider->getStations(query: $query, results: 1)->first();
if ($station !== null) {
return $station;
}
Expand All @@ -69,14 +71,14 @@ public static function lookupStation(string|int $query): Station {
*
* @return array
* @throws HafasException
* @deprecated use DataProviderInterface::getDepartures(...) directly instead (-> less overhead)
* @deprecated use DataProviderInterface->getDepartures(...) directly instead (-> less overhead)
*/
#[ArrayShape([
'station' => Station::class,
'departures' => Collection::class,
'times' => "array"
])]
public static function getDepartures(
public static function getDeprecatedDepartures(
string|int $stationQuery,
Carbon $when = null,
TravelType $travelType = null,
Expand All @@ -91,7 +93,7 @@ public static function getDepartures(
'next' => $when->clone()->addMinutes(15)
];

$departures = (new DataProviderFactory)->create(HafasController::class)::getDepartures(
$departures = (new DataProviderFactory)->create(HafasController::class)->getDepartures(
station: $station,
when: $when,
type: $travelType,
Expand Down Expand Up @@ -128,7 +130,7 @@ public function renderStationboard(Request $request): View|RedirectResponse {

if (isset($validated['station'])) {
try {
$trainStationboardResponse = self::getDepartures(
$trainStationboardResponse = self::getDeprecatedDepartures(
stationQuery: $validated['station'],
when: $when,
travelType: TravelType::tryFrom($validated['filter'] ?? null),
Expand Down
13 changes: 10 additions & 3 deletions app/Http/Controllers/Frontend/Admin/EventController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Http\Controllers\Frontend\Admin;

use App\DataProviders\DataProviderFactory;
use App\DataProviders\DataProviderInterface;
use App\DataProviders\HafasController;
use App\Enum\EventRejectionReason;
use App\Exceptions\HafasException;
Expand All @@ -21,6 +22,12 @@

class EventController extends Controller
{
private DataProviderInterface $dataProvider;

public function __construct(string $dataProvider = null) {
$dataProvider ??= HafasController::class;
$this->dataProvider = (new DataProviderFactory())->create($dataProvider);
}

private const VALIDATOR_RULES = [
'name' => ['required', 'max:255'],
Expand Down Expand Up @@ -148,7 +155,7 @@ public function acceptSuggestion(Request $request): RedirectResponse {
}

if (isset($validated['nearest_station_name'])) {
$station = (new DataProviderFactory)->create(HafasController::class)::getStations($validated['nearest_station_name'], 1)->first();
$station = $this->dataProvider->getStations($validated['nearest_station_name'], 1)->first();

if ($station === null) {
return back()->with('alert-danger', 'Die Station konnte nicht gefunden werden.');
Expand Down Expand Up @@ -188,7 +195,7 @@ public function create(Request $request): RedirectResponse {

$station = null;
if (isset($validated['nearest_station_name'])) {
$station = (new DataProviderFactory)->create(HafasController::class)::getStations($validated['nearest_station_name'], 1)->first();
$station = $this->dataProvider->getStations($validated['nearest_station_name'], 1)->first();

if ($station === null) {
return back()->with('alert-danger', 'Die Station konnte nicht gefunden werden.');
Expand Down Expand Up @@ -220,7 +227,7 @@ public function edit(int $id, Request $request): RedirectResponse {
if (strlen($validated['nearest_station_name'] ?? '') === 0) {
$validated['station_id'] = null;
} elseif ($validated['nearest_station_name'] && $validated['nearest_station_name'] !== $event->station->name) {
$station = (new DataProviderFactory)->create(HafasController::class)::getStations($validated['nearest_station_name'], 1)->first();
$station = $this->dataProvider->getStations($validated['nearest_station_name'], 1)->first();

if ($station === null) {
return back()->with('alert-danger', 'Die Station konnte nicht gefunden werden.');
Expand Down
5 changes: 2 additions & 3 deletions app/Http/Controllers/TransportController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use App\DataProviders\DataProviderFactory;
use App\DataProviders\DataProviderInterface;
use App\DataProviders\HafasController;
use App\Exceptions\HafasException;
use App\Http\Resources\StationResource;
use App\Models\Checkin;
Expand Down Expand Up @@ -38,11 +37,11 @@ public function __construct(string $dataProvider) {
*/
public function getTrainStationAutocomplete(string $query): Collection {
if (!is_numeric($query) && strlen($query) <= 5 && ctype_upper($query)) {
$stations = (new DataProviderFactory)->create(HafasController::class)::getStationsByFuzzyRilIdentifier(rilIdentifier: $query);
$stations = $this->dataProvider->getStationsByFuzzyRilIdentifier(rilIdentifier: $query);
}

if (!isset($stations) || $stations[0] === null) {
$stations = (new DataProviderFactory)->create(HafasController::class)::getStations($query);
$stations = $this->dataProvider->getStations($query);
}

return $stations->map(function(Station $station) {
Expand Down
2 changes: 1 addition & 1 deletion app/Repositories/CheckinHydratorRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function getHafasTrip(string $tripID, string $lineName): Trip {
$trip = Trip::where('id', $tripID)->where('linename', $lineName)->first();
}
$trip = $trip ?? Trip::where('trip_id', $tripID)->where('linename', $lineName)->first();
return $trip ?? $dataProvider::fetchHafasTrip($tripID, $lineName);
return $trip ?? $dataProvider->fetchHafasTrip($tripID, $lineName);
}

public function findEvent(int $id): ?Event {
Expand Down
Loading

0 comments on commit 6d086e7

Please sign in to comment.