xero_sync-8.x-1.x-dev/src/XeroSyncUtilitiesTrait.php
src/XeroSyncUtilitiesTrait.php
<?php
namespace Drupal\xero_sync;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
/**
* A trait for sharing utility code needed in various places.
*/
trait XeroSyncUtilitiesTrait {
/**
* Creates a stub of a typed data representation of a Xero item.
*
* @param string $itemType
* The item's Xero datatype.
* @param string $itemId
* The item's Xero guid.
*
* @return \Drupal\xero\TypedData\XeroComplexItemInterface
* The created typed data object.
*/
protected function buildXeroItemWithId($itemType, $itemId) {
$definition = $this->typedDataManager->createDataDefinition($itemType);
$item = $this->typedDataManager->create($definition, []);
$guidName = $item->getXeroProperty('guid_name');
$item->set($guidName, $itemId);
$item->stub = TRUE;
return $item;
}
/**
* Get the field on an entity that stores a reference to its synced Xero item.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
*
* @return bool|\Drupal\Core\Field\FieldItemListInterface
* The field item list object, or false if the entity has no such field.
*/
protected function getSyncField(EntityInterface $entity) {
if (!($entity instanceof FieldableEntityInterface)) {
return FALSE;
}
$entityHandler = $this instanceof XeroSyncEntityHandlerInterface ? $this : $this->entityHandler;
$fieldName = $entityHandler->getFieldName($entity->getEntityTypeId(), $entity->bundle());
// $entity->hasField() returns NULL on $entity->original, so we try to get
// the field and catch the exception if it doesn't exist.
$hasField = $entity->hasField($fieldName);
if ($hasField === FALSE) {
return FALSE;
}
try {
return $entity->get($fieldName);
}
catch (\InvalidArgumentException $e) {
return FALSE;
}
}
/**
* Get the Xero Guid for the item synced with an entity.
*
* This is available only if the entity has a synced item and a field that
* stores a reference to the item.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
*
* @return string|null
* The Xero guid.
*
* @throws \Drupal\Core\TypedData\Exception\MissingDataException
*/
protected function getSyncedItemGuid(EntityInterface $entity) {
$field = $this->getSyncField($entity);
if ($field && !$field->isEmpty()) {
return $field->first()->guid;
}
}
/**
* Get the Xero type for the item synced with an entity.
*
* This is available only if the entity has a synced item and a field that
* stores a reference to the item.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
*
* @return string|null
* The Xero type.
*
* @throws \Drupal\Core\TypedData\Exception\MissingDataException
*/
protected function getSyncedItemType(EntityInterface $entity) {
$field = $this->getSyncField($entity);
if ($field && !$field->isEmpty()) {
return $field->first()->type;
}
}
}
