File: /var/www/elite/coordParser/NextGisParser.php
<?php
namespace coordParser;
class NextGisParser
{
const URL = 'https://geoservices.nextgis.com';
const API_KEY = 'dc0010ab8f32858cfd83ebe92f0888df';
const HOUR_LIMIT = 1000; // На самом деле 1050
const TYPE_PARCELS = 1;
const TYPE_UNITS = 2;
const TYPE_AREA = 4;
const TYPE_BUILDINGS = 5;
public array $state = ['requests' => []];
public function __construct()
{
$tempDir = __DIR__ . '/tmp';
if (!file_exists($tempDir)) {
mkdir($tempDir);
}
$todayState = $tempDir . '/' . date('Y-m-d') . '_nextGisState.json';
if (!file_exists($todayState)) {
file_put_contents($todayState, json_encode($this->state));
}
$this->state = json_decode(file_get_contents($todayState), true);
}
public function getLimitRemain(): int
{
$thisHourRequests = $this->state['requests'][date('H')] ?? 0;
return self::HOUR_LIMIT - $thisHourRequests;
}
public function advice(): void
{
if (empty($this->state['requests'][date('H')])) {
$this->state['requests'][date('H')] = 0;
}
$this->state['requests'][date('H')]++;
$this->saveState();
}
public function adviceError(): void
{
if (empty($this->state['errors'][date('H')])) {
$this->state['errors'][date('H')] = 0;
}
$this->state['errors'][date('H')]++;
$this->saveState();
}
public function saveState()
{
$tempDir = __DIR__ . '/tmp';
if (!file_exists($tempDir)) {
mkdir($tempDir);
}
$todayState = $tempDir . '/' . date('Y-m-d') . '_nextGisState.json';
file_put_contents($todayState, json_encode($this->state));
}
private function request(string $apiMethod, array $query = [])
{
$query['apikey'] = self::API_KEY;
$url = self::URL . $apiMethod . '?' . http_build_query($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($curl);
$this->advice();
if (curl_errno($curl)) {
echo 'Ошибка cURL: ' . curl_error($curl);
}
curl_close($curl);
return $response;
}
public function getById(string $id, int $type = self::TYPE_PARCELS)
{
$query = [
'type' => $type,
'id' => $id,
'cache' => 'included',
];
return json_decode($this->request('/pkk/features/by_id', $query));
}
public function getByPositions(float $lat, float $lon, int $type = self::TYPE_PARCELS)
{
$query = [
'type' => $type,
'lat' => $lat,
'lon' => $lon,
'cache' => 'included',
];
return json_decode($this->request('/pkk/features/by_pos', $query));
}
}