You are here

protected function RulesHttpClient::doExecute in Rules HTTP Client 8

Send a system email.

Parameters

string[] $url: Url addresses HTTP request.

string|null $headers: (optional) Header information of HTTP Request.

string $method: (optional) Method of HTTP request.

string|null $data: (optional) Raw data of HTTP request.

int|null $maxRedirect: (optional) Max redirect for HTTP request.

int|null $timeOut: (optional) Time Out for HTTP request.

File

src/Plugin/RulesAction/RulesHttpClient.php, line 132

Class

RulesHttpClient
Provides "Rules Http client" rules action.

Namespace

Drupal\rules_http_client\Plugin\RulesAction

Code

protected function doExecute(array $url, $headers, $method, $data = NULL, $maxRedirect = 3, $timeOut = 30) {

  // Headers section.
  $headers = explode("\r\n", $headers);
  if (is_array($headers)) {
    foreach ($headers as $header) {
      if (!empty($header) && strpos($header, ':') !== FALSE) {
        list($name, $value) = explode(':', $header, 2);
        if (!empty($name)) {
          $options['headers'][$name] = ltrim($value);
        }
      }
    }
  }
  $finalArray = [];
  if (is_array($data)) {

    // Data section.
    foreach ($data as $singleArray) {
      $finalSingleArray = explode('=', $singleArray);
      $finalArray[$finalSingleArray[0]] = $finalSingleArray[1];
    }

    // Json decode array.
    $finalArray = json_encode($finalArray);
  }

  // Payload data.
  $options['data'] = $finalArray;

  // Max redirects.
  $options['max_redirects'] = empty($maxRedirect) ? 3 : $maxRedirect;

  // Timeout.
  $options['timeout'] = empty($timeOut) ? 30 : $timeOut;
  $postUrl = $url[0];

  // Method.
  $method = strtoupper($method);

  // Options.
  $options['method'] = $method == 'POST' ? 'POST' : 'GET';
  $options = [
    'method' => $method,
    'body' => $finalArray,
  ];
  $client = $this->http_client;
  try {
    $response = $client
      ->request($method, $postUrl, $options);

    // Status of request.
    $status = $response
      ->getStatusCode();

    // Check if we succesfully get the output.
    if ($status == '200') {
      $stream = $response
        ->getBody();
      $stream
        ->rewind();
      $output = $stream
        ->getContents();

      // Set the response output from service call.
      $this
        ->setProvidedValue('http_response', $output);
    }
  } catch (RequestException $e) {
    $variables = [
      '@message' => 'Could not get access token',
      '@error_message' => $e
        ->getMessage(),
    ];
    $this->logger
      ->error('@message. Details: @error_message', $variables);
  }
}