/** * @param \CIC\Cicregister\Domain\Model\FrontendUser $frontendUser * @param array $conf * @return string */ public function execute(\CIC\Cicregister\Domain\Model\FrontendUser $frontendUser, array $conf) { // 1. Decide whether we're creating a lead or a contact based on the SFDC Ids stored on the user record. if ($frontendUser->getSfdcLeadID()) { $objType = 'lead'; $objId = $frontendUser->getSfdcLeadID(); } elseif ($frontendUser->getSfdcContactID()) { $objType = 'contact'; $objId = $frontendUser->getSfdcContactID(); } else { $objType = 'lead'; } // TODO: Consider validating contacts to make sure they're real before doing a contact upsert. $this->initSFConnection(); // 2. Check if the existing lead has at some point been converted to a contact. If so, then we'll want to // go ahead and update the contact, not the lead. if ($objId && $objType == 'lead') { $contactId = $this->getContactIDByLeadID($objId); if ($contactId) { $frontendUser->setSfdcContactID($contactId); $objType = 'contact'; $objId = $contactId; } } // 3. Upsert the ocontact or the lead. if ($objType == 'lead') { $SFUpsertObject = $this->createSfLead($frontendUser); } elseif ($objType == 'contact') { $SFUpsertObject = $this->createSfContact($frontendUser); } if ($objId) { $SFUpsertObject->fields['Id'] = $objId; } $SFUpsertObjectId = $this->upsertOneObject($SFUpsertObject); // 4. If we have a SFDC Id after the upsert, then we assume it succeeded and we add the ID to the correct // field on the user record. If we do not have a SFDC Id, then we assume that the upsert failed, and we // try to insert a fresh lead. if ($SFUpsertObjectId) { // success if ($objType == 'lead') { $frontendUser->setSfdcLeadID($SFUpsertObjectId); $frontendUser->setSfdcSyncTimestamp(time()); } elseif ($objType == 'contact') { $frontendUser->setSfdcContactID($SFUpsertObjectId); $frontendUser->setSfdcSyncTimestamp(time()); } } elseif ($SFUpsertObject->fields['Id']) { // failure; try again without the ID (force an insert) $SFUpsertObject->fields['Id'] = ''; $SFUpsertObjectId = $this->upsertOneObject($SFUpsertObject); $frontendUser->setSfdcLeadID($SFUpsertObjectId); $frontendUser->setSfdcContactID(''); $frontendUser->setSfdcSyncTimestamp(time()); } else { // TODO: Handle this exception. } // 5. Add the campaign ID to the contact or lead, if required. if ($SFUpsertObjectId && $conf['sfdcCampaignId']) { $SFCampaignMember = new sObject(); $SFCampaignMember->type = 'CampaignMember'; $SFCampaignMember->fields['CampaignId'] = $conf['sfdcCampaignId']; if ($type == 'Lead') { $SFCampaignMember->fields['LeadId'] = $SFUpsertObjectId; $SFCampaignMember->fields['ContactId'] = NULL; } elseif ($type == 'Contact') { $SFCampaignMember->fields['ContactId'] = $SFUpsertObjectId; $SFCampaignMember->fields['LeadId'] = NULL; } $SFCampaignMemberId = $this->upsertOneObject($SFCampaignMember); } }