View source
<?php
namespace Drupal\salesforce\Rest;
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\salesforce\IdentityNotFoundException;
use Drupal\salesforce\SalesforceAuthProviderPluginManagerInterface;
use Drupal\salesforce\SelectQueryInterface;
use Drupal\salesforce\SFID;
use Drupal\salesforce\SObject;
use Drupal\salesforce\SelectQuery;
use Drupal\salesforce\SelectQueryResult;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use Drupal\Component\Datetime\TimeInterface;
class RestClient implements RestClientInterface {
use StringTranslationTrait;
public $response;
protected $httpClient;
protected $configFactory;
protected $url;
protected $immutableConfig;
protected $state;
protected $cache;
protected $json;
protected $authManager;
protected $authProvider;
protected $authConfig;
protected $authToken;
protected $httpClientOptions;
const CACHE_LIFETIME = 300;
const LONGTERM_CACHE_LIFETIME = 86400;
public function __construct(ClientInterface $http_client, ConfigFactoryInterface $config_factory, StateInterface $state, CacheBackendInterface $cache, Json $json, TimeInterface $time, SalesforceAuthProviderPluginManagerInterface $authManager) {
$this->configFactory = $config_factory;
$this->httpClient = $http_client;
$this->immutableConfig = $this->configFactory
->get('salesforce.settings');
$this->state = $state;
$this->cache = $cache;
$this->json = $json;
$this->time = $time;
$this->httpClientOptions = [];
$this->authManager = $authManager;
$this->authProvider = $authManager
->getProvider();
$this->authConfig = $authManager
->getConfig();
$this->authToken = $authManager
->getToken();
return $this;
}
public function getShortTermCacheLifetime() {
return $this->immutableConfig
->get('short_term_cache_lifetime') ?? static::CACHE_LIFETIME;
}
public function getLongTermCacheLifetime() {
return $this->immutableConfig
->get('long_term_cache_lifetime') ?? static::LONGTERM_CACHE_LIFETIME;
}
public function isInit() {
if (!$this->authProvider || !$this->authManager) {
return FALSE;
}
if (!$this->authToken) {
$this->authToken = $this->authManager
->refreshToken();
return isset($this->authToken);
}
return TRUE;
}
public function apiCall($path, array $params = [], $method = 'GET', $returnObject = FALSE) {
if (!$this
->isInit()) {
throw new RestException(NULL, $this
->t('RestClient is not initialized.'));
}
if (strpos($path, '/') === 0) {
$url = $this->authProvider
->getInstanceUrl() . $path;
}
else {
$url = $this->authProvider
->getApiEndpoint() . $path;
}
try {
$this->response = new RestResponse($this
->apiHttpRequest($url, $params, $method));
} catch (RequestException $e) {
$this->response = $e
->getResponse();
if (!$this->response || $this->response
->getStatusCode() != 401) {
throw new RestException($this->response, $e
->getMessage(), $e
->getCode(), $e);
}
}
if ($this->response
->getStatusCode() == 401) {
$this->authToken = $this->authManager
->refreshToken();
try {
$this->response = new RestResponse($this
->apiHttpRequest($url, $params, $method));
} catch (RequestException $e) {
$this->response = $e
->getResponse();
throw new RestException($this->response, $e
->getMessage(), $e
->getCode(), $e);
}
}
if (empty($this->response) || (int) floor($this->response
->getStatusCode() / 100) != 2) {
throw new RestException($this->response, $this
->t('Unknown error occurred during API call "@call": status code @code : @reason', [
'@call' => $path,
'@code' => $this->response
->getStatusCode(),
'@reason' => $this->response
->getReasonPhrase(),
]));
}
$this
->updateApiUsage($this->response);
if ($returnObject) {
return $this->response;
}
else {
return $this->response->data;
}
}
protected function apiHttpRequest($url, array $params, $method) {
if (!$this->authToken) {
throw new \Exception($this
->t('Missing OAuth Token'));
}
$headers = [
'Authorization' => 'OAuth ' . $this->authToken
->getAccessToken(),
'Content-type' => 'application/json',
];
$data = NULL;
if (!empty($params)) {
$data = $this->json
->encode($params);
}
return $this
->httpRequest($url, $data, $headers, $method);
}
public function httpRequestRaw($url) {
if (!$this->authManager
->getToken()) {
throw new \Exception($this
->t('Missing OAuth Token'));
}
$headers = [
'Authorization' => 'OAuth ' . $this->authToken
->getAccessToken(),
'Content-type' => 'application/json',
];
$response = $this
->httpRequest($url, NULL, $headers);
return $response
->getBody()
->getContents();
}
protected function httpRequest($url, $data = NULL, array $headers = [], $method = 'GET') {
$args = NestedArray::mergeDeep($this->httpClientOptions, [
'headers' => $headers,
'body' => $data,
]);
return $this->httpClient
->{$method}($url, $args);
}
public function setHttpClientOptions(array $options) {
$this->httpClientOptions = NestedArray::mergeDeep($this->httpClientOptions, $options);
return $this;
}
public function setHttpClientOption($option_name, $option_value) {
$this->httpClientOptions[$option_name] = $option_value;
return $this;
}
public function getHttpClientOptions() {
return $this->httpClientOptions;
}
public function getHttpClientOption($option_name) {
return $this->httpClientOptions[$option_name];
}
protected function getErrorData(RequestException $e) {
$response = $e
->getResponse();
$response_body = $response
->getBody()
->getContents();
$data = $this->json
->decode($response_body);
if (!empty($data[0])) {
$data = $data[0];
}
return $data;
}
public function getVersions($reset = FALSE) {
if (!$reset && ($cache = $this->cache
->get('salesforce:versions'))) {
return $cache->data;
}
$versions = [];
if (!$this->authProvider) {
return [];
}
try {
$id = $this->authProvider
->getIdentity();
} catch (IdentityNotFoundException $e) {
return [];
}
$url = str_replace('v{version}/', '', $id
->getUrl('rest'));
$response = new RestResponse($this
->httpRequest($url));
foreach ($response->data as $version) {
$versions[$version['version']] = $version;
}
$this->cache
->set('salesforce:versions', $versions, $this
->getRequestTime() + $this
->getLongTermCacheLifetime(), [
'salesforce',
]);
return $versions;
}
public function getApiUsage() {
return $this->state
->get('salesforce.usage');
}
protected function updateApiUsage(RestResponse $response) {
if ($limit_info = $response
->getHeader('Sforce-Limit-Info')) {
if (is_array($limit_info)) {
$limit_info = reset($limit_info);
}
$this->state
->set('salesforce.usage', $limit_info);
}
}
public function objects(array $conditions = [
'updateable' => TRUE,
], $reset = FALSE) {
if (!$reset && ($cache = $this->cache
->get('salesforce:objects'))) {
$result = $cache->data;
}
else {
$result = $this
->apiCall('sobjects');
$this->cache
->set('salesforce:objects', $result, $this
->getRequestTime() + $this
->getShortTermCacheLifetime(), [
'salesforce',
]);
}
$sobjects = [];
foreach ($result['sobjects'] as $key => $object) {
if (empty($object['name'])) {
print_r($object);
}
if (!empty($conditions)) {
foreach ($conditions as $condition => $value) {
if ($object[$condition] == $value) {
$sobjects[$object['name']] = $object;
}
}
}
else {
$sobjects[$object['name']] = $object;
}
}
return $sobjects;
}
public function query(SelectQueryInterface $query) {
return new SelectQueryResult($this
->apiCall('query?q=' . (string) $query));
}
public function queryAll(SelectQueryInterface $query) {
return new SelectQueryResult($this
->apiCall('queryAll?q=' . (string) $query));
}
public function queryMore(SelectQueryResult $results) {
if ($results
->done()) {
return new SelectQueryResult([
'totalSize' => $results
->size(),
'done' => TRUE,
'records' => [],
]);
}
$version_path = parse_url($this->authProvider
->getApiEndpoint(), PHP_URL_PATH);
$next_records_url = str_replace($version_path, '', $results
->nextRecordsUrl());
return new SelectQueryResult($this
->apiCall($next_records_url));
}
public function objectDescribe($name, $reset = FALSE) {
if (empty($name)) {
throw new \Exception($this
->t('No name provided to describe'));
}
if (!$reset && ($cache = $this->cache
->get('salesforce:object:' . $name))) {
return $cache->data;
}
else {
$response = new RestResponseDescribe($this
->apiCall("sobjects/{$name}/describe", [], 'GET', TRUE));
$this->cache
->set('salesforce:object:' . $name, $response, $this
->getRequestTime() + $this
->getShortTermCacheLifetime(), [
'salesforce',
]);
return $response;
}
}
public function objectCreate($name, array $params) {
$response = $this
->apiCall("sobjects/{$name}", $params, 'POST', TRUE);
$data = $response->data;
return new SFID($data['id']);
}
public function objectUpsert($name, $key, $value, array $params) {
if (isset($params[$key])) {
unset($params[$key]);
}
$response = $this
->apiCall("sobjects/{$name}/{$key}/{$value}", $params, 'PATCH', TRUE);
if ($response
->getStatusCode() == 204) {
$this->original_response = $response;
$sf_object = $this
->objectReadbyExternalId($name, $key, $value);
return $sf_object
->id();
}
$data = $response->data;
return new SFID($data['id']);
}
public function objectUpdate($name, $id, array $params) {
$this
->apiCall("sobjects/{$name}/{$id}", $params, 'PATCH');
}
public function objectRead($name, $id) {
return new SObject($this
->apiCall("sobjects/{$name}/{$id}"));
}
public function objectReadbyExternalId($name, $field, $value) {
return new SObject($this
->apiCall("sobjects/{$name}/{$field}/{$value}"));
}
public function objectDelete($name, $id, $throw_exception = FALSE) {
try {
$this
->apiCall("sobjects/{$name}/{$id}", [], 'DELETE');
} catch (RequestException $e) {
if ($throw_exception || $e
->getResponse()
->getStatusCode() != 404) {
throw $e;
}
}
}
public function getDeleted($type, $startDate, $endDate) {
return $this
->apiCall("sobjects/{$type}/deleted/?start={$startDate}&end={$endDate}");
}
public function listResources() {
return new RestResponseResources($this
->apiCall('', [], 'GET', TRUE));
}
public function getUpdated($name, $start = NULL, $end = NULL) {
if (empty($start)) {
$start = strtotime('-29 days');
}
$start = urlencode(gmdate(DATE_ATOM, $start));
if (empty($end)) {
$end = time();
}
$end = urlencode(gmdate(DATE_ATOM, $end));
return $this
->apiCall("sobjects/{$name}/updated/?start={$start}&end={$end}");
}
public function getRecordTypes($name = NULL, $reset = FALSE) {
if (!$reset && ($cache = $this->cache
->get('salesforce:record_types'))) {
$record_types = $cache->data;
}
else {
$query = new SelectQuery('RecordType');
$query->fields = [
'Id',
'Name',
'DeveloperName',
'SobjectType',
];
$result = $this
->query($query);
$record_types = [];
foreach ($result
->records() as $rt) {
$record_types[$rt
->field('SobjectType')][$rt
->field('DeveloperName')] = $rt;
}
$this->cache
->set('salesforce:record_types', $record_types, $this
->getRequestTime() + $this
->getShortTermCacheLifetime(), [
'salesforce',
]);
}
if ($name != NULL) {
if (!isset($record_types[$name])) {
return FALSE;
}
return $record_types[$name];
}
return $record_types ?: FALSE;
}
public function getRecordTypeIdByDeveloperName($name, $devname, $reset = FALSE) {
$record_types = $this
->getRecordTypes($name, $reset);
if (empty($record_types[$devname])) {
return FALSE;
}
return $record_types[$devname]
->id();
}
public function getObjectTypeName(SFID $id) {
$prefix = substr((string) $id, 0, 3);
$describe = $this
->objects();
foreach ($describe as $object) {
if ($prefix == $object['keyPrefix']) {
return $object['name'];
}
}
return FALSE;
}
protected function getRequestTime() {
return $this->time
->getRequestTime();
}
}