public function SalesforceExampleSubscriber::pullPresave in Salesforce Suite 8.3
Same name and namespace in other branches
- 8.4 modules/salesforce_example/src/EventSubscriber/SalesforceExampleSubscriber.php \Drupal\salesforce_example\EventSubscriber\SalesforceExampleSubscriber::pullPresave()
- 5.0.x modules/salesforce_example/src/EventSubscriber/SalesforceExampleSubscriber.php \Drupal\salesforce_example\EventSubscriber\SalesforceExampleSubscriber::pullPresave()
Pull presave event callback.
Parameters
\Drupal\salesforce_mapping\Event\SalesforcePullEvent $event: The event.
File
- modules/
salesforce_example/ src/ EventSubscriber/ SalesforceExampleSubscriber.php, line 122
Class
- SalesforceExampleSubscriber
- Class SalesforceExampleSubscriber.
Namespace
Drupal\salesforce_example\EventSubscriberCode
public function pullPresave(SalesforcePullEvent $event) {
$mapping = $event
->getMapping();
switch ($mapping
->id()) {
case 'contact':
// In this example, given a Contact record, do a just-in-time fetch for
// Attachment data, if given.
$account = $event
->getEntity();
$sf_data = $event
->getMappedObject()
->getSalesforceRecord();
$client = \Drupal::service('salesforce.client');
// Fetch the attachment URL from raw sf data.
$attachments = [];
try {
$attachments = $sf_data
->field('Attachments');
} catch (\Exception $e) {
// noop, fall through.
}
if (@$attachments['totalSize'] < 1) {
// If Attachments field was empty, do nothing.
return;
}
// If Attachments field was set, it will contain a URL from which we can
// fetch the attached binary. We must append "body" to the retreived URL
// https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_sobject_blob_retrieve.htm
$attachment_url = $attachments['records'][0]['attributes']['url'];
$attachment_url = $client
->getInstanceUrl() . $attachment_url . '/Body';
// Fetch the attachment body, via RestClient::httpRequestRaw.
try {
$file_data = $client
->httpRequestRaw($attachment_url);
} catch (\Exception $e) {
// Unable to fetch file data from SF.
\Drupal::logger('db')
->error(t('failed to fetch attachment for user @user', [
'@user' => $account
->id(),
]));
return;
}
// Fetch file destination from account settings.
$destination = "public://user_picture/profilepic-" . $sf_data
->id() . ".jpg";
// Attach the new file id to the user entity
/* var \Drupal\file\FileInterface */
if ($file = file_save_data($file_data, $destination, FILE_EXISTS_REPLACE)) {
$account->user_picture->target_id = $file
->id();
}
else {
\Drupal::logger('db')
->error('failed to save profile pic for user ' . $account
->id());
}
break;
}
}