Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
api.php
1<?php
2
4
6
11
12Loc::loadMessages(__FILE__);
13
19class Api
20{
21 private $accessToken = NULL;
22 public static $apiUrl = 'https://api.vk.com/method/';
23 public static $apiVersion = "5.131";
24 private $exportId;
25 private $response;
26
28
35 public function __construct($accessToken, $exportId)
36 {
37 $this->exportId = $exportId;
38 $this->response = array();
39
40 if ($accessToken)
41 {
42 $this->accessToken = $accessToken;
43 }
44 else
45 {
46 throw new ArgumentNullException('accessToken');
47 }
48 }
49
57 public function run($method, $params = array())
58 {
59 $params['access_token'] = $this->accessToken;
60 $params['v'] = self::$apiVersion;
61 $url = self::$apiUrl . $method;
62
63 $http = new HttpClient();
64 $responseStr = $http->post($url, $params);
65
66 if (!is_string($responseStr))
67 {
68 return NULL;
69 }
70
71 $this->response = Json::decode($responseStr);
72 $this->checkError($method, $params);
73
74 return $this->response['response'];
75 }
76
85 private function checkError($method, $params)
86 {
87// check limit of requests count. If limit catched - run again
88 if ($this->checkRequestsLimit())
89 {
90 return $this->run($method, $params);
91 }
92// FATAL errors - stop running
93 if (isset($this->response["error"]))
94 {
95 $logger = new Vk\Logger($this->exportId);
96 $logger->addLog(
97 'Catch error in method ' . $method,
98 array('ERROR' => $this->response["error"] . ' - ' . $this->response["error_msg"], "PARAMS" => $params)
99 );
100 $logger->addError($this->response["error"]["error_code"], $method);
101
102 throw new Vk\ExecuteException("VK_critical_execution_error " . $this->response["error"]["error_code"] . " in method " . $method);
103 }
104
105// EXECUTE errors can be fatal or not critical
106 if (isset($this->response["execute_errors"]))
107 {
108 $logger = new Vk\Logger($this->exportId);
109 foreach ($this->response["execute_errors"] as $er)
110 {
111 $logger->addLog(
112 'Execute error in method ' . $method,
113 array('ERROR' => $er["error_code"] . ' (' . $er["method"] . ') - ' . $er["error_msg"], "PARAMS" => $params,
114 "RESPONSE" => $this->response)
115 );
116 $logger->addError($er["error_code"]);
117 }
118 }
119
120 return NULL;
121 }
122
123
124 private function checkRequestsLimit()
125 {
126// we can do only LIMIT count of requests per second. If catched error - wait one second, clear error and do next
127 if (isset($this->response["error"]) && $this->response["error"]["error_code"] == self::TOO_MANY_REQUESTS_ERROR_CODE)
128 {
129 sleep(1);
130 $this->response = array();
131
132 return true;
133 }
134
135 return false;
136 }
137
138}
static loadMessages($file)
Definition loc.php:64
__construct($accessToken, $exportId)
Definition api.php:35
run($method, $params=array())
Definition api.php:57