/** * Init logger. */ private function initializeLogger() { $logger = new Logger('Easemob'); if ($this['config']['debug']) { $logger->pushHandler(new NullHandler()); } elseif ($logFile = $this['config']['log.file']) { $logger->pushHandler(new StreamHandler($logFile, $this['config']->get('log.level') ?: Logger::WARNING)); } Log::setLogger($logger); }
/** * Internal fetch token logic. * * @throws HttpException * @throws \light\Easemob\Exception\HttpException * * @return array */ protected function getTokenFromServer() { $this->http->clearMiddlewares(); $response = $this->http->post('token', ['grant_type' => 'client_credentials', 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret]); Log::debug('Get access token response', ['response' => (string) $response->getBody()]); $token = $this->http->parseJSON((string) $response->getBody()); if (!isset($token['access_token'])) { throw new HttpException('Request AccessToken fail.' . json_encode($token, JSON_UNESCAPED_UNICODE)); } return $token; }
/** * Parse json data. * * @param string|ResponseInterface $body * @param bool $throws * * @throws HttpException * * @return array */ public function parseJSON($body, $throws = true) { if ($body instanceof ResponseInterface) { $body = $body->getBody(); } $contents = json_decode($body, true); if (JSON_ERROR_NONE !== json_last_error()) { Log::error('Failed to parse JSON.', ['body' => $body]); if ($throws) { throw new HttpException('Failed to parse JSON.', json_last_error()); } } return $contents; }
/** * Parse response. * * @param ResponseInterface $response * * @throws EasemobException * @throws \light\Easemob\Exception\HttpException * * @return mixed */ protected function parseResponse(ResponseInterface $response) { $statusCode = $response->getStatusCode(); if (200 !== $statusCode) { //通用false代表此次请求失败,并没有成功 Log::error('Got an error reponse:', ['__class__' => get_called_class(), 'code' => $statusCode, 'responseBody' => (string) $response->getBody()]); return false; } $result = $this->http->parseJSON($response); Log::debug('Parse response body result:', ['response' => $result]); if (isset($result['error'])) { Log::error('Got an error from server:', ['__class__' => get_called_class(), 'error' => $result]); throw new EasemobException($result['error_description']); } return $result; }