You are here

public function MoxtraConnector::request in Opigno Moxtra 3.x

Same name and namespace in other branches
  1. 8 src/MoxtraConnector.php \Drupal\opigno_moxtra\MoxtraConnector::request()

Helper function to send a request with JSON data to the Moxtra API.

Parameters

string $url: Request URL.

array $request_data: Request data.

string $method: HTTP method.

Return value

array Response data.

1 call to MoxtraConnector::request()
MoxtraConnector::getToken in src/MoxtraConnector.php
Build Moxtra access token.

File

src/MoxtraConnector.php, line 250

Class

MoxtraConnector

Namespace

Drupal\opigno_moxtra

Code

public function request($url, array $request_data, $method = 'POST') {
  $data = [];
  if (!$this
    ->checkSettings()) {
    return [];
  }
  try {
    $response = $this->httpClient
      ->request($method, $url, [
      'json' => $request_data,
    ]);
  } catch (RequestException $exception) {
    $this->logger
      ->error($exception);
    $response = $exception
      ->getResponse();
    $data['error'] = $exception
      ->getMessage();
  } catch (\Exception $exception) {
    $this->logger
      ->error($exception);
    $data['error'] = $exception
      ->getMessage();
  }
  if (isset($response)) {
    $data['http_code'] = $response
      ->getStatusCode();
    $response_body = $response
      ->getBody()
      ->getContents();
    if (!empty($response_body) && $response_body !== 'null') {
      $json_data = Json::decode($response_body);
      if (is_array($json_data) && !empty($json_data)) {
        $data = array_merge($data, $json_data);
      }
    }
    if ($data['http_code'] == 400) {
      if (isset($data['message']) && $data['message'] == 'cann\'t expel owner') {

        // Ignore 'cann't expel owner' error.
        $data['http_code'] = 200;
      }
    }
    if ($data['http_code'] == 404) {

      // Ignore 'User not found in member list.' error.
      $data['http_code'] = 200;
    }
    if ($data['http_code'] == 409) {

      // Ignore 'all invitees are already members' error.
      $data['http_code'] = 200;
    }
    if ($data['http_code'] != 200) {
      $this->logger
        ->error($this
        ->t('Error while contacting the Moxtra server.<br/><pre>Response: @response</pre>', [
        '@response' => print_r($data, TRUE),
      ]));
    }
  }
  else {
    $this->messenger
      ->addError($this
      ->t('Error while contacting the Moxtra server. Try again or contact the administrator.'));
    $data['http_code'] = 501;
  }
  return $data;
}