Your IP : 216.73.216.86


Current Path : /var/www/homesaver/www/bitrix/modules/fermaofd.ferma/classes/general/ferma-api/
Upload File :
Current File : /var/www/homesaver/www/bitrix/modules/fermaofd.ferma/classes/general/ferma-api/CFermaApiClient.php

<?php

require_once __DIR__ . '/../../../const.php';

use Bitrix\Main\Web\Json;

IncludeModuleLangFile(__DIR__ . '/../ferma-api.php');

class CFermaApiClient
{
    /**
     * @var string
     */
    private $apiHost;
    /**
     * @var string
     */
    private $errorsEmail;
    /**
     * @var int
     */
    private $timeout;
    /**
     * @var bool
     */
    private $logEnabled;

    private static $instances = [];

    public function __construct($apiHost, $errorsEmail, $timeout = 15)
    {
        $this->apiHost = $apiHost;
        $this->errorsEmail = $errorsEmail;
        $this->timeout = $timeout;
        $this->logEnabled = COption::GetOptionString(FERMAOFD_FERMA_MODULE_ID, 'api_log', 'N') === 'Y';
    }

    /**
     * @param string $apiHost
     * @param string $errorsEmail
     * @param int $timeout
     * @return CFermaApiClient
     */
    public static function instance($apiHost, $errorsEmail, $timeout = 15)
    {
        $hash = sha1($apiHost . '/' . $errorsEmail . '/' . $timeout);

        if (!isset(static::$instances[$hash])) {
            static::$instances[$hash] = new static($apiHost, $errorsEmail, $timeout);
        }

        return static::$instances[$hash];
    }

    /**
     * @param string $uri
     * @param array $data
     * @param string|null $accessToken
     * @return array
     * @throws \CFermaApiException
     */
    public function post($uri, $data = [], $accessToken = null)
    {
        $encodedData = Json::encode($data);

        $ch = curl_init($this->getFullUri($uri, $accessToken));
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . mb_strlen($encodedData, 'utf-8'),
        ]);

        $response = curl_exec($ch);

        try {
            $result = Json::decode($response);

            $this->log($uri, $data, $result);

            return $result;
        } catch (\Exception $e) {
            $this->log($uri, $data, $response);

            throw new CFermaApiException('Failed parse response.');
        }
    }

    private function log($endpoint, $request, $response)
    {
        if (!$this->logEnabled) {
            return;
        }

        CMainOfdFerma::log(
            GetMessage('FERMAOFD_API_REQUEST'), null,
            Json::encode([
                'endpoint' => $endpoint,
                'request' => $this->recursiveSafe($request),
                'response' => $this->recursiveSafe($response),
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), 'DEBUG'
        );
    }

    private function recursiveSafe(array $data): array
    {
        return array_reduce(array_keys($data), function (array $result, $key) use ($data) {
            if (is_array($data[$key])) {
                $result[$key] = $this->recursiveSafe($data[$key]);
            } elseif (is_string($data[$key]) && preg_match('/(login|password|passphrase|AuthToken)/i', $key)) {
                $result[$key] = '***';
            } else {
                $result[$key] = $data[$key];
            }

            return $result;
        }, []);
    }

    private function sendErrorReport(\Exception $e)
    {
        if (empty($this->errorsEmail)) {
            return;
        }

        $date = date('d.m.Y H:i');

        $message = sprintf(GetMessage('FERMAOFD_ERROR_REPORT_MESSAGE'), $e->getMessage());

        bxmail($this->errorsEmail, GetMessage('FERMAOFD_ERROR_REPORT_SUBJECT') . $date, $message);
    }

    private function getFullUri($uri, $accessToken = null)
    {
        $authToken = '';

        if ($accessToken) {
            $isArgs = strpos($uri, '?') !== false ? '&' : '?';
            $authToken = $isArgs . 'AuthToken=' . $accessToken;
        }

        return rtrim($this->apiHost, '/') . '/' . ltrim($uri, '/') . $authToken;
    }
}