Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
baserequester.php
1<?php
2
4
13
18abstract class BaseRequester
19{
21 protected $httpClient = null;
23 protected $url = '';
25 protected $requiredFields = [];
27 protected $fieldsToEncode = [];
29 protected $urlMaker = null;
31 protected $cachePool = null;
32
39 {
40 $this->httpClient = $httpClient;
41 $this->cachePool = $cachePool;
42 $this->urlMaker = new UrlMaker();
43 }
44
51 protected function makeUrl(array $params): string
52 {
53 return $this->urlMaker->make(
54 $params,
55 $this->url,
56 $this->requiredFields,
57 $this->fieldsToEncode
58 );
59 }
60
64 protected function getLoggerService(): LoggerService
65 {
67 }
68
73 protected function createCacheItemKey(string $url): string
74 {
75 return md5(
76 preg_replace('/&location=[0-9.,]*&/', '&', $url)
77 );
78 }
79
84 public function request(array $params)
85 {
86 $url = $this->makeUrl($params);
87 $result = false;
88 $httpRes = false;
89 $loggerService = $this->getLoggerService();
90 $loggerService->log(LogLevel::DEBUG, $url, EventType::SOURCE_GOOGLE_REQUESTER_URL);
91 $cacheItemKey = $this->createCacheItemKey($url);
92 $takenFromCache = false;
93
94 if($this->cachePool && $cachedAnswer = $this->cachePool->getItem($cacheItemKey))
95 {
96 $httpRes = $cachedAnswer['httpRes'];
97 $errors = $cachedAnswer['errors'];
98 $status = $cachedAnswer['status'];
99
100 $takenFromCache = true;
101 }
102 else
103 {
104 if (@$this->httpClient->get($url))
105 {
106 $httpRes = $this->httpClient->getResult();
107 }
108
109 $errors = $this->httpClient->getError();
110 $status = $this->httpClient->getStatus();
111 }
112
113 $loggerService->log(
114 LogLevel::DEBUG,
115 '{"httpRes":"'.$httpRes.'","errors":"'. $this->convertErrorsToString($errors).'","status":"'.$status.'"}',
117 );
118
119 if(!$httpRes && !empty($errors))
120 {
121 throw new RuntimeException(
122 $this->convertErrorsToString($errors),
124 );
125 }
126 else
127 {
128 $result = [];
129
130 if($httpRes)
131 {
132 try
133 {
134 $result = Json::decode($httpRes);
135 }
136 catch(\Exception $e)
137 {
138 $message = 'Can\'t decode Google server\'s answer.'
139 . ' URL: ' . $url
140 . ' Answer: '. $httpRes;
141
143 }
144
145 if(!$takenFromCache
146 && $this->cachePool
147 && $status === 200
148 && empty($errors)
149 && isset($result['status'])
150 && $result['status'] === 'OK'
151 )
152 {
153 $this->cachePool->addItem(
154 $cacheItemKey,
155 [
156 'httpRes' => $httpRes,
157 'errors' => $errors,
158 'status' => $status
159 ]
160 );
161 }
162 }
163
164 if ($status != 200)
165 {
166 $message = 'Http status: '.$status
167 . ' URL: ' . $url
168 . ' Answer: '. $httpRes;
169
171 }
172 }
173
174 return $result;
175 }
176
177 protected function convertErrorsToString(array $errors): string
178 {
179 $result = '';
180
181 foreach ($errors as $code => $message)
182 {
183 $result .= $message.'['.$code.'], ';
184 }
185
186 return $result;
187 }
188}
__construct(HttpClient $httpClient, CachedPool $cachePool=null)