public function CrmCoreUserSyncRelation::relate in CRM Core 8
Same name and namespace in other branches
- 8.3 modules/crm_core_user_sync/src/CrmCoreUserSyncRelation.php \Drupal\crm_core_user_sync\CrmCoreUserSyncRelation::relate()
Synchronizes user and contact.
Parameters
\Drupal\user\UserInterface $account: Account to be synchronized. Programmatically created accounts can override default behavior by setting $account->crm_core_no_auto_sync = TRUE.
\Drupal\crm_core_contact\IndividualInterface $contact: Contact to be associated with $account.
Return value
\Drupal\crm_core_contact\ContactInterface A contact object.
Throws
\Drupal\Core\Entity\EntityStorageException
Overrides CrmCoreUserSyncRelationInterface::relate
File
- modules/
crm_core_user_sync/ src/ CrmCoreUserSyncRelation.php, line 133
Class
- CrmCoreUserSyncRelation
- Relation service.
Namespace
Drupal\crm_core_user_syncCode
public function relate(UserInterface $account, IndividualInterface $contact = NULL) {
// No contact and $account->crm_core_no_auto_sync => no sync.
if (empty($contact) && !empty($account->crm_core_no_auto_sync)) {
return NULL;
}
if (empty($contact)) {
// Account already have related contact.
if ($this
->getUserIndividualId($account
->id())) {
return NULL;
}
// Get corresponding contact type.
$contact_type = $this->rules
->getContactType($account);
// No rules configured.
if (!$contact_type) {
return NULL;
}
// Create the contact.
$contact = Individual::create([
'type' => $contact_type,
]);
$contact
->setOwner($account);
// For now we just add the name.
$contact->name->given = $account
->getAccountName();
$contact
->save();
}
// Check if contact can be synchronized to a contact.
if (!$this->rules
->valid($account, $contact)) {
return NULL;
}
// Check if crm_core_user_sync relation exists for any of endpoint.
if ($this
->getUserIndividualId($account
->id()) || $this
->getIndividualUserId($contact
->id())) {
return NULL;
}
$relation = Relation::create();
$relation
->setUser($account);
$relation
->setIndividual($contact);
$relation
->save();
$this->logger
->notice('User @user @uid has been synchronized to the contact @contact_id, relation @rid has been created.', [
'@user' => $account
->getDisplayName(),
'@uid' => $account
->id(),
'@contact_id' => $contact
->id(),
'@rid' => $relation
->id(),
]);
return $contact;
}