xero_sync-8.x-1.x-dev/modules/xero_sync_user_contact/src/EventSubscriber/SyncToUserSubscriber.php
modules/xero_sync_user_contact/src/EventSubscriber/SyncToUserSubscriber.php
<?php
namespace Drupal\xero_sync_user_contact\EventSubscriber;
use Drupal\xero_sync\XeroSyncEntityHandlerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\xero_sync\Event\XeroSyncEvents;
use Drupal\xero_sync\Event\XeroSyncPropertiesEvent;
use Drupal\user\UserInterface;
use Drupal\xero_sync\XeroSyncUtilitiesTrait;
/**
* Specify information that should be set on the Xero contact.
*/
class SyncToUserSubscriber implements EventSubscriberInterface {
use XeroSyncUtilitiesTrait;
/**
* The entity handler.
*
* @var \Drupal\xero_sync\XeroSyncEntityHandlerInterface
*/
protected $entityHandler;
/**
* Constructs a new SyncToUserSubscriber object.
*
* @param \Drupal\xero_sync\XeroSyncEntityHandlerInterface $entity_handler
* The entity handler.
*/
public function __construct(XeroSyncEntityHandlerInterface $entity_handler) {
$this->entityHandler = $entity_handler;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events = [
XeroSyncEvents::SYNC_TO_ENTITY_FROM_ITEM . '.user' => 'updateUser',
];
return $events;
}
/**
* Specify information that should be set on the Drupal entity.
*
* @param \Drupal\xero_sync\Event\XeroSyncPropertiesEvent $event
* The Xero Sync event.
*/
public function updateUser(XeroSyncPropertiesEvent $event) {
// This is just paranoia, as we're subscribing to a user event we
// should be able to trust there's a user entity.
$hasUser = $event->getEntityType() === 'user' && ($event->getEntity() instanceof UserInterface);
$hasContact = $event->getItemType() === 'xero_contact';
if ($hasUser && $hasContact) {
$user = $event->getEntity();
$contactID = $event->getItem()->get('ContactID')->getString();
$guidDifferent = $this->getSyncedItemGuid($user) !== $contactID;
$typeDifferent = $this->getSyncedItemType($user) !== 'xero_contact';
$field = $this->getSyncField($user);
if ($field && ($guidDifferent || $typeDifferent)) {
$fieldName = $this->entityHandler->getFieldName($user->getEntityTypeId(), $user->bundle());
$user->set($fieldName, [
'type' => 'xero_contact',
'guid' => $contactID,
]);
$event->setModified();
}
}
}
}
