<?php
namespace App\Lidia; abstract class ApiGeneralAbstract { private $proxyServerUrl = NULL; public function __construct($proxyServerUrl) { if (!$proxyServerUrl) { throw new \Exception(__METHOD__.': `proxyServerUrl` is not configured.'); } $this->proxyServerUrl = $proxyServerUrl; } protected function request($post) { $postData = json_encode($post); $ch = curl_init(); if (!$ch) { throw new \RuntimeException("Cannot initiate CURL connection."); } curl_setopt($ch, CURLOPT_URL, $this->proxyServerUrl); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_USERAGENT, "LIDIA API PHP 2.0"); $response = curl_exec ($ch); if (!$response) { $errorMessage = curl_error($ch); \Log::getInstance()->error(sprintf("[%s]. Requested operation:%s failed - no response. Error: %s.", __METHOD__, $post->operation, $errorMessage), [ 'request' => new \Engine\Logger\Context\Json($post), ]); throw new \RuntimeException("Empty response from LIDIA. Error during connection: ".$errorMessage); } $context = ['request' => new \Engine\Logger\Context\Json($post)]; if ($post->operation != 'downloadVersion') { $context['response'] = new \Engine\Logger\Context\StringRaw($response); } $curlErrorMessage = curl_error($ch); if ($curlErrorMessage) { \Log::getInstance()->info(sprintf("[%s]. Requested operation:%s. Curl error message: %s", __METHOD__, $post->operation, $curlErrorMessage), $context); } else { \Log::getInstance()->info(sprintf("[%s]. Requested operation:%s.", __METHOD__, $post->operation), $context); } return $response; } public function executeOperation(\App\Lidia\RequestAbstract $request, \App\Lidia\ResponseAbstract $response) { $str = $this->request($request); $responseStdClass = json_decode($str); if (!$responseStdClass) { throw new \RuntimeException("The response is invalid."); } $response->setStatus($responseStdClass->status); $response->setMessage($responseStdClass->message); $this->mapResponse($response, $responseStdClass); } abstract protected function mapResponse(\App\Lidia\ResponseAbstract $response, \stdClass $responseStdClass); } 