hcportal-dev/Aiko/Libs/GeoTz.php

90 lines
2.4 KiB
PHP

<?php
namespace Aiko;
use DateTime;
use DateTimeZone;
use ErrorException;
use PDO;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
class GeoTz
{
protected $registry;
private $endpoint;
private $apiKey;
private $client;
public function __construct($registry)
{
$this->registry = $registry;
$this->endpoint = $this->registry->config->api_geo_tz_endpoint;
$this->apiKey = $this->registry->config->api_geo_tz_key;
$this->client = new Client([
'base_uri' => $this->endpoint,
'http_errors ' => false,
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
}
public function getCoordinateTimezone($lat, $lon)
{
return $this->getTimezoneApi($lat, $lon);
}
public function getTimezoneLocally($hourOffset)
{
$sign = $hourOffset < 0 ? '-' : '+';
$date = new DateTime('now', new DateTimeZone($sign . abs($hourOffset)));
return array(
'date' => $date->format('Y-m-d'),
'time' => $date->format('H:i:s'),
'date_time' => $date->format('Y-m-d H:i:s'),
'api' => []
);
}
private function getTimezoneApi($lat, $lon)
{
try {
$response = $this->client->get('/timezone', [
'query' => [
'apiKey' => $this->apiKey,
'lat' => $lat,
'long' => $lon
]
]);
if ($response->getStatusCode() !== 200) {
throw new ErrorException((string) $response->getBody()->getContents());
}
$data = $response->getBody()->getContents();
$tz = json_decode($data, true);
$date = new DateTime('now', new DateTimeZone($tz['timezone']));
return array(
'date' => $date->format('Y-m-d'),
'time' => $date->format('H:i:s'),
'date_time' => $date->format('Y-m-d H:i:s')
);
} catch (ErrorException $e) {
$this->registry
->log
->error('Geolocation / getTimezoneApi :'
. $e->getMessage() . ', Line: '
. $e->getLine() . ', File: '
. $e->getFile());
return [];
}
}
}