Skip to content

Commit

Permalink
Add timezone to geolocation
Browse files Browse the repository at this point in the history
  • Loading branch information
Niek Pijp committed Apr 12, 2022
1 parent 9f09576 commit 3796026
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
28 changes: 26 additions & 2 deletions src/Geolocation.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Brainstud\UnlimitedGeolocation;

use DateTimeZone;
use stdClass;

/**
Expand All @@ -13,12 +14,29 @@ class Geolocation
{
/**
* @param string $countryCode The Country code in ISO 3166-1 alpha-2 format.
* @param ?string $timeZone The timezone
*/
public function __construct(
public string $countryCode
public string $countryCode,
public ?string $timeZone = null
) {
}

/**
* Get the geolocation data from a country code.
* @param string $countryCode
* @return Geolocation
*/
public static function fromCountryCode(string $countryCode): Geolocation
{
$timeZone = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $countryCode);
if (count($timeZone) > 1) {
return new Geolocation($countryCode);
}

return new Geolocation($countryCode, current($timeZone));
}

/**
* Convert IpRegistry data to Geolocation
* @param stdClass $data
Expand All @@ -27,7 +45,13 @@ public function __construct(
public static function fromIpRegistry(stdClass $data): Geolocation
{
$countryCode = $data->location?->country?->code;
$timeZone = $data->time_zone?->id;

return new Geolocation($countryCode);
return new Geolocation($countryCode, $timeZone);
}

public function isComplete(): bool
{
return $this->countryCode && $this->timeZone;
}
}
5 changes: 4 additions & 1 deletion src/UnlimitedGeolocation.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ private static function getFromHeader(Request $request): ?Geolocation
&& is_string($value)
&& strlen($value) === 2
) {
return new Geolocation($value);
$location = Geolocation::fromCountryCode($value);
if ($location->isComplete()) {
return $location;
}
}

return null;
Expand Down

0 comments on commit 3796026

Please sign in to comment.