map_route_planner-1.0.0-alpha4/src/WsServiceConnector.php

src/WsServiceConnector.php
<?php

namespace Drupal\map_route_planner;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

/**
 * Class WsServiceConnector.
 *
 * The Web-Service Connector.
 *
 * @package Drupal\map_route_planner
 */
class WsServiceConnector {

  /**
   * A guzzle client instance.
   *
   * @var \GuzzleHttp\Client
   */
  protected $guzzleClient;

  /**
   * Performs a request to an api.
   *
   * @param string $url
   *   The API URL.
   * @param array $body
   *   All the body elements to be sent in the request (generally in POST).
   * @param string $method
   *   Either "get" or "post". Default to "get".
   *
   * @return mixed|null
   *   Return result request.
   */
  public function requestWebService(
    string $url,
    string $method = 'post',
    array $body = ['id'=> 'data-explorer']
  ) : ?array {
    $data = NULL;
    $this->guzzleClient = \Drupal::httpClient();

    if (!empty($url)) {

      try {
        $parameters = [];
        if (!empty($body)) {
          $parameters['json'] = $body;
        }
        switch ($method) {
          case 'post':
            if (!empty($parameters)) {
              $response = $this->guzzleClient->post($url, $parameters);
            }
            else {
              $response = $this->guzzleClient->post($url);
            }
            break;

          default:
            $response = $this->guzzleClient->get($url);
            break;
        }
        $ok_status_codes = [200, 202, 204];
        if (in_array($response->getStatusCode(), $ok_status_codes, TRUE)) {
          $data = json_decode($response->getBody(), TRUE);
        }
        else {
          // When the response code is 500, 400 ...
          \Drupal::logger('map_route_planner')->error(
            __FUNCTION__ . ' ' . $response->getReasonPhrase()
          );
        }
      }
      catch (GuzzleException $e) {
        \Drupal::logger('map_route_planner')->error(
          __FUNCTION__ . ' ' . $e->getMessage()
        );
      }
    }

    return $data;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc