You are here

function wsdata_field_entity_load in Web Service Data 8

Same name and namespace in other branches
  1. 2.0.x modules/wsdata_field/wsdata_field.module \wsdata_field_entity_load()

Implements hook_entity_load().

File

modules/wsdata_field/wsdata_field.module, line 64
Main module file for wsdata_field.

Code

function wsdata_field_entity_load(array $entities, $entity_type_id) {
  foreach ($entities as $entity) {
    if ($entity instanceof ContentEntityInterface) {

      // Fetch the field definitions for the this node.
      $fields = $entity
        ->getFieldDefinitions();
      foreach ($fields as $field) {

        // Get the fields storage definitions.
        $field_storage = $field
          ->getFieldStorageDefinition();

        /* Check if the field has the custom storage flag set to true
           and c heck to make sure the object is of type FieldStorageConfig. */
        if ($field_storage
          ->hasCustomStorage()) {
          if (is_a($field_storage, 'Drupal\\field\\Entity\\FieldStorageConfig')) {

            // Fetch the wsfield config entity.
            $wsfield_config = \Drupal::service('entity_type.manager')
              ->getStorage('wsfield_config')
              ->load($field_storage
              ->get('field_name'));
            if ($wsfield_config != NULL) {

              /* If the wsfield config exist we are in business
                 replace the value with the return of the wscall. */
              $replacements = is_array($wsfield_config->replacements) ? $wsfield_config->replacements : [];

              // Get the cache tags.
              $tags = $entity
                ->getCacheTagsToInvalidate();
              $wsdata = \Drupal::service('wsdata');
              $langcode = $entity
                ->language()
                ->getId();
              if ($wsfield_config->languageHandling && $wsfield_config->languageHandling == 'interfaceLanguage') {
                $langcode = \Drupal::languageManager()
                  ->getCurrentLanguage()
                  ->getId();
              }
              $result = $wsdata
                ->call($wsfield_config->wscall, NULL, $replacements, $wsfield_config->data, [
                'langcode' => $langcode,
              ], $wsfield_config->returnToken, [
                $entity_type_id => $entity,
              ], $tags);

              // Set the field with the wsdata results.
              $entity
                ->set($field_storage
                ->get('field_name'), $result);
            }
          }
        }
      }
    }
  }
}