You are here

class RestClient in Salesforce Suite 8.3

Same name in this branch
  1. 8.3 src/Rest/RestClient.php \Drupal\salesforce\Rest\RestClient
  2. 8.3 modules/salesforce_encrypt/src/Rest/RestClient.php \Drupal\salesforce_encrypt\Rest\RestClient

Objects, properties, and methods to communicate with the Salesforce REST API.

Hierarchy

Expanded class hierarchy of RestClient

Deprecated

salesforce_encrypt is deprecated and will be removed in 8.x-4.0. Please see change record https://www.drupal.org/node/3034230 for additional information.

2 files declare their use of RestClient
RestClientTest.php in modules/salesforce_encrypt/tests/src/Unit/RestClientTest.php
SalesforceEncryptServiceProvider.php in modules/salesforce_encrypt/src/SalesforceEncryptServiceProvider.php

File

modules/salesforce_encrypt/src/Rest/RestClient.php, line 25

Namespace

Drupal\salesforce_encrypt\Rest
View source
class RestClient extends SalesforceRestClient implements EncryptedRestClientInterface {
  use StringTranslationTrait;

  /**
   * Encryption service.
   *
   * @var \Drupal\encrypt\EncryptServiceInterface
   */
  protected $encryption;

  /**
   * Encryption profile manager.
   *
   * @var \Drupal\encrypt\EncryptionProfileManagerInterface
   */
  protected $encryptionProfileManager;

  /**
   * The active encryption profile id.
   *
   * @var string
   */
  protected $encryptionProfileId;

  /**
   * The encryption profile to use when encrypting and decrypting data.
   *
   * @var \Drupal\encrypt\EncryptionProfileInterface
   */
  protected $encryptionProfile;

  /**
   * Construct a new Encrypted Rest Client.
   *
   * @param \GuzzleHttp\ClientInterface $http_client
   *   The GuzzleHttp Client.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   * @param \Drupal\Core\State\StateInterface $state
   *   The state service.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache service.
   * @param \Drupal\Component\Serialization\Json $json
   *   The JSON serializer service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The Time service.
   * @param \Drupal\encrypt\EncryptServiceInterface $encryption
   *   The encryption service.
   * @param \Drupal\encrypt\EncryptionProfileManagerInterface $encryptionProfileManager
   *   The Encryption profile manager service.
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock backend service.
   *
   * @deprecated salesforce_encrypt is deprecated and will be removed in 8.x-4.0. Please see change record https://www.drupal.org/node/3034230 for additional information.
   */
  public function __construct(ClientInterface $http_client, ConfigFactoryInterface $config_factory, StateInterface $state, CacheBackendInterface $cache, Json $json, TimeInterface $time, EncryptServiceInterface $encryption, EncryptionProfileManagerInterface $encryptionProfileManager, LockBackendInterface $lock) {
    parent::__construct($http_client, $config_factory, $state, $cache, $json, $time);
    $this->encryption = $encryption;
    $this->encryptionProfileId = $this->state
      ->get('salesforce_encrypt.profile');
    $this->encryptionProfileManager = $encryptionProfileManager;
    $this->encryptionProfile = NULL;
    $this->lock = $lock;
  }

  /**
   * {@inheritdoc}
   */
  public function enableEncryption(EncryptionProfileInterface $profile) {
    if ($ret = $this
      ->setEncryption($profile)) {
      $this->state
        ->resetCache();
    }
    return $ret;
  }

  /**
   * {@inheritdoc}
   */
  public function disableEncryption() {
    if ($ret = $this
      ->setEncryption()) {
      $this->state
        ->resetCache();
    }
    return $ret;
  }

  /**
   * {@inheritdoc}
   */
  public function hookEncryptionProfileDelete(EncryptionProfileInterface $profile) {
    if ($this->encryptionProfileId == $profile
      ->id()) {
      $this
        ->disableEncryption();
    }
  }

  /**
   * Set the given encryption profile as active.
   *
   * If given profile is null, decrypt and disable encryption.
   *
   * @param \Drupal\encrypt\EncryptionProfileInterface|null $profile
   *   The encryption profile. If null, encryption will be disabled.
   */
  protected function setEncryption(EncryptionProfileInterface $profile = NULL) {
    if (!$this->lock
      ->acquire('salesforce_encrypt')) {
      throw new \RuntimeException('Unable to acquire lock.');
    }
    $access_token = $this
      ->getAccessToken();
    $refresh_token = $this
      ->getRefreshToken();
    $identity = $this
      ->getIdentity();
    $consumerKey = $this
      ->getConsumerKey();
    $consumerSecret = $this
      ->getConsumerSecret();
    $this->encryptionProfileId = $profile == NULL ? NULL : $profile
      ->id();
    $this->encryptionProfile = $profile;
    $this->state
      ->set('salesforce_encrypt.profile', $this->encryptionProfileId);
    $this
      ->setAccessToken($access_token);
    $this
      ->setRefreshToken($refresh_token);
    $this
      ->setIdentity($identity);
    $this
      ->setConsumerKey($consumerKey);
    $this
      ->setConsumerSecret($consumerSecret);
    $this->lock
      ->release('salesforce_encrypt');
  }

  /**
   * {@inheritdoc}
   */
  public function getEncryptionProfile() {
    if ($this->encryptionProfile) {
      return $this->encryptionProfile;
    }
    elseif (empty($this->encryptionProfileId)) {
      return NULL;
    }
    else {
      $this->encryptionProfile = $this->encryptionProfileManager
        ->getEncryptionProfile($this->encryptionProfileId);
      if (empty($this->encryptionProfile)) {
        throw new EntityNotFoundException([
          'id' => $this->encryptionProfileId,
        ], 'encryption_profile');
      }
      return $this->encryptionProfile;
    }
  }

  /**
   * Deprecated, use doGetEncryptionProfile.
   *
   * @deprecated use ::doGetEncryptionProfile().
   */
  protected function _getEncryptionProfile() {
    return $this
      ->doGetEncryptionProfile();
  }

  /**
   * Exception-handling wrapper around getEncryptionProfile().
   *
   * GetEncryptionProfile() will throw an EntityNotFoundException exception
   * if it has an encryption profile ID but cannot load it.  In this wrapper
   * we handle that exception by setting a helpful error message and allow
   * execution to proceed.
   *
   * @return \Drupal\encrypt\EncryptionProfileInterface|null
   *   The encryption profile if it can be loaded, otherwise NULL.
   */
  protected function doGetEncryptionProfile() {
    try {
      $profile = $this
        ->getEncryptionProfile();
    } catch (EntityNotFoundException $e) {
      drupal_set_message($this
        ->t('Error while loading encryption profile. You will need to <a href=":encrypt">assign a new encryption profile</a>, then <a href=":oauth">re-authenticate to Salesforce</a>.', [
        ':encrypt' => Url::fromRoute('salesforce_encrypt.settings')
          ->toString(),
        ':oauth' => Url::fromRoute('salesforce.authorize')
          ->toString(),
      ]), 'error');
    }
    return $profile;
  }

  /**
   * {@inheritdoc}
   */
  public function encrypt($value) {
    if (empty($this
      ->doGetEncryptionProfile())) {
      return $value;
    }
    else {
      return $this->encryption
        ->encrypt($value, $this
        ->doGetEncryptionProfile());
    }
  }

  /**
   * {@inheritdoc}
   */
  public function decrypt($value) {
    if (empty($this
      ->doGetEncryptionProfile()) || empty($value) || mb_strlen($value) === 0) {
      return $value;
    }
    else {
      return $this->encryption
        ->decrypt($value, $this
        ->doGetEncryptionProfile());
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getAccessToken() {
    return $this
      ->decrypt(parent::getAccessToken());
  }

  /**
   * {@inheritdoc}
   */
  public function setAccessToken($token) {
    return parent::setAccessToken($this
      ->encrypt($token));
  }

  /**
   * {@inheritdoc}
   */
  public function getRefreshToken() {
    return $this
      ->decrypt(parent::getRefreshToken());
  }

  /**
   * {@inheritdoc}
   */
  public function setRefreshToken($token) {
    return parent::setRefreshToken($this
      ->encrypt($token));
  }

  /**
   * {@inheritdoc}
   */
  public function setIdentity($data) {
    if (is_array($data)) {
      $data = serialize($data);
    }
    return parent::setIdentity($this
      ->encrypt($data));
  }

  /**
   * {@inheritdoc}
   */
  public function getIdentity() {
    $data = $this
      ->decrypt(parent::getIdentity());
    if (!empty($data) && !is_array($data)) {
      $data = unserialize($data);
    }
    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function getConsumerKey() {
    return $this
      ->decrypt(parent::getConsumerKey());
  }

  /**
   * {@inheritdoc}
   */
  public function setConsumerKey($value) {
    return parent::setConsumerKey($this
      ->encrypt($value));
  }

  /**
   * {@inheritdoc}
   */
  public function getConsumerSecret() {
    return $this
      ->decrypt(parent::getConsumerSecret());
  }

  /**
   * {@inheritdoc}
   */
  public function setConsumerSecret($value) {
    return parent::setConsumerSecret($this
      ->encrypt($value));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
RestClient::$cache protected property The cache service.
RestClient::$configFactory protected property Config factory service.
RestClient::$encryption protected property Encryption service.
RestClient::$encryptionProfile protected property The encryption profile to use when encrypting and decrypting data.
RestClient::$encryptionProfileId protected property The active encryption profile id.
RestClient::$encryptionProfileManager protected property Encryption profile manager.
RestClient::$httpClient protected property GuzzleHttp client.
RestClient::$httpClientOptions protected property
RestClient::$immutableConfig protected property Salesforce immutable config object. Useful for gets.
RestClient::$json protected property The JSON serializer service.
RestClient::$mutableConfig protected property Salesforce mutable config object. Useful for sets.
RestClient::$response public property Response object.
RestClient::$state protected property The state service.
RestClient::$storage Deprecated private property Token storage.
RestClient::$url protected property Salesforce API URL.
RestClient::apiCall public function Make a call to the Salesforce REST API. Overrides RestClientInterface::apiCall 1
RestClient::apiHttpRequest protected function Private helper to issue an SF API request.
RestClient::CACHE_LIFETIME constant
RestClient::decrypt public function Decrypts a value using active encryption profile, or return the same value. Overrides EncryptedRestClientInterface::decrypt
RestClient::disableEncryption public function Decrypt and re-save sensitive salesforce config values. Overrides EncryptedRestClientInterface::disableEncryption
RestClient::doGetEncryptionProfile protected function Exception-handling wrapper around getEncryptionProfile().
RestClient::enableEncryption public function Encrypts all sensitive salesforce config values. Overrides EncryptedRestClientInterface::enableEncryption
RestClient::encrypt public function Encrypts a value using the active encryption profile, or return plaintext. Overrides EncryptedRestClientInterface::encrypt
RestClient::getAccessToken public function Get the access token. Overrides RestClient::getAccessToken
RestClient::getApiEndPoint public function Get the API end point for a given type of the API. Overrides RestClientInterface::getApiEndPoint
RestClient::getApiUsage public function Get the api usage, as returned in the most recent API request header. Overrides RestClientInterface::getApiUsage
RestClient::getApiVersion public function Wrapper for config rest_api_version.version. Overrides RestClientInterface::getApiVersion
RestClient::getAuthCallbackUrl public function Helper to build the redirect URL for OAUTH workflow. Overrides RestClientInterface::getAuthCallbackUrl
RestClient::getAuthEndpointUrl public function Get Salesforce oauth login endpoint. (OAuth step 1) Overrides RestClientInterface::getAuthEndpointUrl 1
RestClient::getAuthTokenUrl public function Get Salesforce oauth token endpoint. (OAuth step 2) Overrides RestClientInterface::getAuthTokenUrl 1
RestClient::getConsumerKey public function Consumer key getter. Overrides RestClient::getConsumerKey
RestClient::getConsumerSecret public function Comsumer secret getter. Overrides RestClient::getConsumerSecret
RestClient::getDeleted public function Retrieves objects deleted within the given timeframe. Overrides RestClientInterface::getDeleted
RestClient::getEncryptionProfile public function Returns the EncryptionProfileInterface assigned to Salesforce Encrypt. Overrides EncryptedRestClientInterface::getEncryptionProfile
RestClient::getErrorData protected function Extract normalized error information from a RequestException.
RestClient::getHttpClientOption public function Getter for a single, named HTTP client option. Overrides RestClientInterface::getHttpClientOption
RestClient::getHttpClientOptions public function Getter for HTTP client options. Overrides RestClientInterface::getHttpClientOptions
RestClient::getIdentity public function Return the Salesforce identity, which is stored in a variable. Overrides RestClient::getIdentity
RestClient::getInstanceUrl public function Get the SF instance URL. Useful for linking to objects. Overrides RestClientInterface::getInstanceUrl
RestClient::getLoginUrl public function Login url getter. Overrides RestClientInterface::getLoginUrl
RestClient::getObjectTypeName public function Utility function to determine object type for given SFID. Overrides RestClientInterface::getObjectTypeName
RestClient::getRecordTypeIdByDeveloperName public function Given a DeveloperName and SObject Name, return SFID of the RecordType. Overrides RestClientInterface::getRecordTypeIdByDeveloperName
RestClient::getRecordTypes public function Retrieve all record types for this org. Overrides RestClientInterface::getRecordTypes 1
RestClient::getRefreshToken public function Get refresh token. Overrides RestClient::getRefreshToken
RestClient::getRequestTime protected function Returns REQUEST_TIME.
RestClient::getUpdated public function Return a list of SFIDs for the given object for the given timeframe. Overrides RestClientInterface::getUpdated
RestClient::getVersions public function Wrapper for "Versions" resource to list information about API releases. Overrides RestClientInterface::getVersions
RestClient::handleAuthResponse public function Helper callback for OAuth handshake, and refreshToken() Overrides RestClientInterface::handleAuthResponse 1
RestClient::hookEncryptionProfileDelete public function If the given profile is our active one, disable encryption. Overrides EncryptedRestClientInterface::hookEncryptionProfileDelete
RestClient::httpRequest protected function Make the HTTP request. Wrapper around drupal_http_request().
RestClient::httpRequestRaw public function Return raw response content from given URL. Overrides RestClientInterface::httpRequestRaw
RestClient::initializeIdentity public function Retrieve and store the Salesforce identity given an ID url. Overrides RestClientInterface::initializeIdentity
RestClient::isAuthorized public function Determine if this SF instance is fully configured. Overrides RestClientInterface::isAuthorized 1
RestClient::listResources public function Return a list of available resources for the configured API version. Overrides RestClientInterface::listResources 1
RestClient::LONGTERM_CACHE_LIFETIME constant
RestClient::objectCreate public function Create a new object of the given type. Overrides RestClientInterface::objectCreate 1
RestClient::objectDelete public function Delete a Salesforce object. Overrides RestClientInterface::objectDelete 1
RestClient::objectDescribe public function Retrieve all the metadata for an object. Overrides RestClientInterface::objectDescribe 1
RestClient::objectRead public function Return a fullly loaded Salesforce object. Overrides RestClientInterface::objectRead
RestClient::objectReadbyExternalId public function Return a full loaded Salesforce object from External ID. Overrides RestClientInterface::objectReadbyExternalId
RestClient::objects public function Available objects and their metadata for your organization's data. Overrides RestClientInterface::objects 1
RestClient::objectUpdate public function Update an existing object. Overrides RestClientInterface::objectUpdate 1
RestClient::objectUpsert public function Create new records or update existing records. Overrides RestClientInterface::objectUpsert 1
RestClient::query public function Use SOQL to get objects based on query string. Overrides RestClientInterface::query
RestClient::queryAll public function Same as ::query(), but also returns deleted or archived records. Overrides RestClientInterface::queryAll
RestClient::queryMore public function Given a select query result, fetch the next results set, if it exists. Overrides RestClientInterface::queryMore
RestClient::refreshToken public function Refresh access token based on the refresh token. Overrides RestClientInterface::refreshToken
RestClient::setAccessToken public function Set the access token. Overrides RestClient::setAccessToken
RestClient::setApiVersion public function Setter for config salesforce.settings rest_api_version and use_latest. Overrides RestClientInterface::setApiVersion
RestClient::setConsumerKey public function Consumer key setter. Overrides RestClient::setConsumerKey
RestClient::setConsumerSecret public function Consumer key setter. Overrides RestClient::setConsumerSecret
RestClient::setEncryption protected function Set the given encryption profile as active.
RestClient::setHttpClientOption public function Set a single Guzzle HTTP client option. Overrides RestClientInterface::setHttpClientOption
RestClient::setHttpClientOptions public function Set options for Guzzle HTTP client. Overrides RestClientInterface::setHttpClientOptions
RestClient::setIdentity public function Set the Salesforce identity, which is stored in a variable. Overrides RestClient::setIdentity
RestClient::setInstanceUrl public function Set the SF instance URL. Overrides RestClientInterface::setInstanceUrl
RestClient::setLoginUrl public function Login url setter. Overrides RestClientInterface::setLoginUrl
RestClient::setRefreshToken public function Set the refresh token. Overrides RestClient::setRefreshToken
RestClient::storage Deprecated private function Storage helper.
RestClient::updateApiUsage protected function Helper to extract API Usage info from response header and write to state.
RestClient::_getEncryptionProfile Deprecated protected function Deprecated, use doGetEncryptionProfile.
RestClient::__construct Deprecated public function Construct a new Encrypted Rest Client. Overrides RestClient::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.