You are here

abstract class PropertiesBase in Salesforce Suite 8.4

Same name and namespace in other branches
  1. 5.0.x modules/salesforce_mapping/src/Plugin/SalesforceMappingField/PropertiesBase.php \Drupal\salesforce_mapping\Plugin\SalesforceMappingField\PropertiesBase

Base class for properties plugins.

Hierarchy

Expanded class hierarchy of PropertiesBase

File

modules/salesforce_mapping/src/Plugin/SalesforceMappingField/PropertiesBase.php, line 23

Namespace

Drupal\salesforce_mapping\Plugin\SalesforceMappingField
View source
abstract class PropertiesBase extends SalesforceMappingFieldPluginBase {

  /**
   * Data fetcher service.
   *
   * @var \Drupal\typed_data\DataFetcherInterface
   */
  protected $dataFetcher;
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $plugin = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $plugin->dataFetcher = $container
      ->get('typed_data.data_fetcher');
    return $plugin;
  }

  /**
   * Data fetcher getter.
   *
   * @return \Drupal\typed_data\DataFetcherInterface|mixed
   *   Data fetcher.
   */
  public function dataFetcher() {
    if (empty($this->dataFetcher)) {
      $this->dataFetcher = \Drupal::service('typed_data.data_fetcher');
    }
    return $this->dataFetcher;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::validateConfigurationForm($form, $form_state);
    $vals = $form_state
      ->getValues();
    $config = $vals['config'];
    if (empty($config['salesforce_field'])) {
      $form_state
        ->setError($form['config']['salesforce_field'], $this
        ->t('Salesforce field is required.'));
    }
    if (empty($config['drupal_field_value'])) {
      $form_state
        ->setError($form['config']['drupal_field_value'], $this
        ->t('Drupal field is required.'));
    }

    // @TODO: Should we validate the $config['drupal_field_value']['setting'] property?
  }

  /**
   * {@inheritdoc}
   */
  public function checkFieldMappingDependency(array $dependencies) {
    $definition = $this
      ->getPluginDefinition();
    foreach ($definition['config_dependencies'] as $type => $dependency) {
      foreach ($dependency as $item) {
        if (!empty($dependencies[$type][$item])) {
          return TRUE;
        }
      }
    }

    // @TODO: Should we validate the $config['drupal_field_value']['setting'] property?
  }

  /**
   * {@inheritdoc}
   */
  public function value(EntityInterface $entity, SalesforceMappingInterface $mapping) {

    // No error checking here. If a property is not defined, it's a
    // configuration bug that needs to be solved elsewhere.
    // Multipicklist is the only target type that handles multi-valued fields.
    $describe = $this->salesforceClient
      ->objectDescribe($mapping
      ->getSalesforceObjectType());
    $field_definition = $describe
      ->getField($this
      ->config('salesforce_field'));
    if ($field_definition['type'] == 'multipicklist') {
      $data = $this
        ->getDataValue($entity, $this
        ->config('drupal_field_value'));
      if (!empty($data)) {
        $strings = [];
        foreach ($data as $item) {
          $strings[] = $item
            ->getString();
        }
        return implode(';', $strings);
      }
    }
    else {
      return $this
        ->getStringValue($entity, $this
        ->config('drupal_field_value'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function pullValue(SObject $sf_object, EntityInterface $entity, SalesforceMappingInterface $mapping) {
    $field_selector = $this
      ->config('drupal_field_value');
    $pullValue = parent::pullValue($sf_object, $entity, $mapping);
    try {

      // Fetch the TypedData property and set its value.
      $data = $this
        ->dataFetcher()
        ->fetchDataByPropertyPath($entity
        ->getTypedData(), $field_selector);
      $data
        ->setValue($pullValue);
      return $data;
    } catch (MissingDataException $e) {
    } catch (InvalidArgumentException $e) {
    }

    // Allow any other exception types to percolate.
    // If the entity doesn't have any value in the field, data fetch will
    // throw an exception. We must attempt to create the field.
    // Typed Data API doesn't provide any good way to initialize a field value
    // given a selector. Instead we have to do it ourselves.
    // We descend only to the first-level fields on the entity. Cascading pull
    // values to entity references is not supported.
    $parts = explode('.', $field_selector, 4);
    switch (count($parts)) {
      case 1:
        $entity
          ->set($field_selector, $pullValue);
        return $entity
          ->getTypedData()
          ->get($field_selector);
      case 2:
        $field_name = $parts[0];
        $delta = 0;
        $property = $parts[1];
        break;
      case 3:
        $field_name = $parts[0];
        $delta = $parts[1];
        $property = $parts[2];
        if (!is_numeric($delta)) {
          return;
        }
        break;
      case 4:
        return;
    }

    /** @var \Drupal\Core\TypedData\ListInterface $list_data */
    $list_data = $entity
      ->get($field_name);

    // If the given delta has not been initialized, initialize it.
    if (!$list_data
      ->get($delta) instanceof TypedDataInterface) {
      $list_data
        ->set($delta, []);
    }

    /** @var \Drupal\Core\TypedData\TypedDataInterface|\Drupal\Core\TypedData\ComplexDataInterface $typed_data */
    $typed_data = $list_data
      ->get($delta);
    if ($typed_data instanceof ComplexDataInterface && $property) {

      // If the given property has not been initialized, initialize it.
      if (!$typed_data
        ->get($property) instanceof TypedDataInterface) {
        $typed_data
          ->set($property, []);
      }

      /** @var \Drupal\Core\TypedData\TypedDataInterface $typed_data */
      $typed_data = $typed_data
        ->get($property);
    }
    if (!$typed_data instanceof TypedDataInterface) {
      return;
    }
    $typed_data
      ->setValue($pullValue);
    return $typed_data
      ->getParent();
  }

  /**
   * {@inheritdoc}
   */
  protected function getFieldDataDefinition(EntityInterface $entity) {
    if (!strpos($this
      ->config('drupal_field_value'), '.')) {
      return parent::getFieldDataDefinition($entity);
    }
    $data_definition = $this
      ->dataFetcher()
      ->fetchDefinitionByPropertyPath($entity
      ->getTypedData()
      ->getDataDefinition(), $this
      ->config('drupal_field_value'));
    if ($data_definition instanceof ListDataDefinitionInterface) {
      $data_definition = $data_definition
        ->getItemDefinition();
    }
    return $data_definition;
  }

  /**
   * Helper Method to check for and retrieve field data.
   *
   * If it is just a regular field/property of the entity, the data is
   * retrieved with ->value(). If this is a property referenced using the
   * typed_data module's extension, use typed_data module's DataFetcher class
   * to retrieve the value.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to search the Typed Data for.
   * @param string $drupal_field_value
   *   The Typed Data property to get.
   *
   * @return string
   *   The String representation of the Typed Data property value.
   */
  protected function getStringValue(EntityInterface $entity, $drupal_field_value) {
    try {
      $data = $this
        ->getDataValue($entity, $drupal_field_value);
      return empty($data) ? NULL : $data
        ->getString();
    } catch (\Exception $e) {
      return NULL;
    }
  }

  /**
   * Another helper Method to check for and retrieve field data.
   *
   * Same as getStringValue(), but returns the typed data prior to stringifying.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to search the Typed Data for.
   * @param string $drupal_field_value
   *   The Typed Data property to get.
   *
   * @return \Drupal\Core\TypedData\TypedDataInterface|NULL
   *   The array representation of the Typed Data property value.
   */
  protected function getDataValue(EntityInterface $entity, $drupal_field_value) {
    try {
      return $this
        ->dataFetcher()
        ->fetchDataByPropertyPath($entity
        ->getTypedData(), $drupal_field_value);
    } catch (\Exception $e) {
      return NULL;
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function getDrupalFieldType(DataDefinitionInterface $data_definition) {
    $field_main_property = $data_definition;
    if ($data_definition instanceof ComplexDataDefinitionInterface) {
      $field_main_property = $data_definition
        ->getPropertyDefinition($data_definition
        ->getMainPropertyName());
    }
    return $field_main_property ? $field_main_property
      ->getDataType() : NULL;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PropertiesBase::$dataFetcher protected property Data fetcher service.
PropertiesBase::checkFieldMappingDependency public function On dependency removal, determine if this plugin needs to be removed. Overrides SalesforceMappingFieldPluginBase::checkFieldMappingDependency
PropertiesBase::create public static function Creates an instance of the plugin. Overrides SalesforceMappingFieldPluginBase::create
PropertiesBase::dataFetcher public function Data fetcher getter.
PropertiesBase::getDataValue protected function Another helper Method to check for and retrieve field data.
PropertiesBase::getDrupalFieldType protected function Helper method to get the Field Type of the given Field Data Definition. Overrides SalesforceMappingFieldPluginBase::getDrupalFieldType 1
PropertiesBase::getFieldDataDefinition protected function Helper method to get the Data Definition for the current field. Overrides SalesforceMappingFieldPluginBase::getFieldDataDefinition
PropertiesBase::getStringValue protected function Helper Method to check for and retrieve field data.
PropertiesBase::pullValue public function Pull callback for field plugins. Overrides SalesforceMappingFieldPluginBase::pullValue
PropertiesBase::validateConfigurationForm public function Implements PluginFormInterface::validateConfigurationForm(). Overrides SalesforceMappingFieldPluginBase::validateConfigurationForm
PropertiesBase::value public function Given a Drupal entity, return the outbound value. Overrides SalesforceMappingFieldPluginInterface::value
SalesforceMappingFieldPluginBase::$entityFieldManager protected property Entity field manager service.
SalesforceMappingFieldPluginBase::$entityTypeBundleInfo protected property Entity type bundle info service.
SalesforceMappingFieldPluginBase::$entityTypeManager protected property Entity type manager service.
SalesforceMappingFieldPluginBase::$eventDispatcher protected property Event dispatcher service.
SalesforceMappingFieldPluginBase::$id protected property The machine name of the mapping.
SalesforceMappingFieldPluginBase::$label protected property The label of the mapping.
SalesforceMappingFieldPluginBase::$mappedObjectStorage protected property Storage handler for Mapped Objects.
SalesforceMappingFieldPluginBase::$mapping protected property The mapping to which this instance is attached.
SalesforceMappingFieldPluginBase::$mappingStorage protected property Storage handler for SF mappings.
SalesforceMappingFieldPluginBase::$salesforceClient protected property Salesforce client service.
SalesforceMappingFieldPluginBase::buildBrokenConfigurationForm protected function Helper for buildConfigurationForm() to build a broken field plugin.
SalesforceMappingFieldPluginBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm 13
SalesforceMappingFieldPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
SalesforceMappingFieldPluginBase::config public function In order to set a config value to null, use setConfiguration() Overrides SalesforceMappingFieldPluginInterface::config
SalesforceMappingFieldPluginBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration
SalesforceMappingFieldPluginBase::get public function Used for returning values by key. Overrides SalesforceMappingFieldPluginInterface::get
SalesforceMappingFieldPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
SalesforceMappingFieldPluginBase::getSalesforceFieldOptions protected function Helper to retreive a list of fields for a given object type.
SalesforceMappingFieldPluginBase::instanceOfEntityReference protected function Return TRUE if the given field uses an entity reference handler.
SalesforceMappingFieldPluginBase::isAllowed public static function Determine whether this plugin is allowed for a given mapping. Overrides SalesforceMappingFieldPluginInterface::isAllowed 4
SalesforceMappingFieldPluginBase::label public function Returns label of the mapping field plugin. Overrides SalesforceMappingFieldPluginInterface::label
SalesforceMappingFieldPluginBase::pull public function Whether this plugin supports "pull" operations. Overrides SalesforceMappingFieldPluginInterface::pull 6
SalesforceMappingFieldPluginBase::push public function Whether this plugin supports "push" operations. Overrides SalesforceMappingFieldPluginInterface::push 1
SalesforceMappingFieldPluginBase::pushValue public function Munge the value that's being prepared to push to Salesforce. Overrides SalesforceMappingFieldPluginInterface::pushValue
SalesforceMappingFieldPluginBase::selectionPluginManager protected function Wraper for plugin.manager.entity_reference_selection service.
SalesforceMappingFieldPluginBase::set public function Used for returning values by key. Overrides SalesforceMappingFieldPluginInterface::set
SalesforceMappingFieldPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
SalesforceMappingFieldPluginBase::submitConfigurationForm public function Implements PluginFormInterface::submitConfigurationForm(). Overrides PluginFormInterface::submitConfigurationForm 1
SalesforceMappingFieldPluginBase::__construct public function SalesforceMappingFieldPluginBase constructor. Overrides PluginBase::__construct 1
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.