Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
basesender.php
1<?php
2
4
10
14abstract class BaseSender
15{
16 public function __construct()
17 {
18 }
19
26 public function performRequest($action, array $parameters = []): Result
27 {
28 $httpClient = $this->buildHttpClient();
29
30 $url = $this->getServiceUrl() . "/api/?action=".$action;
31
32 $request = [
33 "action" => $action,
34 "serializedParameters" => base64_encode(gzencode(Json::encode($parameters))),
35 ];
36
37 $request["BX_TYPE"] = Client::getPortalType();
38 $request["BX_LICENCE"] = Client::getLicenseCode();
39 $request["SERVER_NAME"] = Client::getServerName();
40 $request["BX_HASH"] = Client::signRequest($request);
41
42 $result = $httpClient->query(HttpClient::HTTP_POST, $url, $request);
43
44 return $this->buildResult($httpClient, $result);
45 }
46
47 protected function buildHttpClient(): HttpClient
48 {
49 return new HttpClient($this->getHttpClientParameters());
50 }
51
52 protected function buildResult(HttpClient $httpClient, bool $requestResult): Result
53 {
54 return $this->createAnswerForJsonResponse(
55 $requestResult,
56 $httpClient->getResult(),
57 $httpClient->getError(),
58 $httpClient->getStatus()
59 );
60 }
61
62 protected function createAnswerForJsonResponse($queryResult, $response, $errors, $status): Result
63 {
64 $result = new Result();
65
66 if(!$queryResult)
67 {
68 foreach ($errors as $code => $message)
69 {
70 $result->addError(new Error($message, $code));
71 }
72
73 return $result;
74 }
75
76 if($status != 200)
77 {
78 $result->addError(new Error("Server returned " . $status . " code", "WRONG_SERVER_RESPONSE"));
79 return $result;
80 }
81
82 if($response == "")
83 {
84 $result->addError(new Error("Empty server response", "EMPTY_SERVER_RESPONSE"));
85 return $result;
86 }
87
88 try
89 {
90 $parsedResponse = Json::decode($response);
91 }
92 catch (\Exception $e)
93 {
94 $result->addError(new Error("Could not parse server response. Raw response: " . $response));
95 return $result;
96 }
97
98 if($parsedResponse["status"] === "error")
99 {
100 foreach ($parsedResponse["errors"] as $error)
101 {
102 $result->addError(new Error($error["message"], $error["code"], $error["customData"]));
103 }
104 }
105 else if(is_array($parsedResponse["data"]))
106 {
107 $result->setData($parsedResponse["data"]);
108 }
109
110 return $result;
111 }
112
116 public function getHttpClientParameters(): array
117 {
118 return [
119 "socketTimeout" => 10,
120 "streamTimeout" => 30,
121 "disableSslVerification" => true
122 ];
123 }
124
125 protected abstract function getServiceUrl(): string;
126}
createAnswerForJsonResponse($queryResult, $response, $errors, $status)
buildResult(HttpClient $httpClient, bool $requestResult)
performRequest($action, array $parameters=[])
static signRequest(array $parameters, string $suffix="")
Definition client.php:63