You are here

function hashtags_entity_presave in Hashtags 8

Same name and namespace in other branches
  1. 7 hashtags.module \hashtags_entity_presave()

Implements hook_entity_presave().

File

./hashtags.module, line 121

Code

function hashtags_entity_presave(EntityInterface $entity) {
  $config = \Drupal::config('hashtags.settings');
  $hashtags_field_name = $config
    ->get('hashtags_taxonomy_terms_field_name');
  $hashtags_vid = $config
    ->get('hashtags_vid');
  $entity_type = $entity
    ->getEntityTypeId();
  $bundle = $entity
    ->bundle();
  if (!_hashtags_is_field_exists($entity_type, $bundle, $hashtags_field_name)) {
    return;
  }
  $vid = $config
    ->get('hashtags_vid');
  $text = '';
  $activated_text_fields = _hashtags_get_activated_text_fields($entity_type, $bundle);
  foreach ($activated_text_fields as $field_name) {
    foreach ($entity->{$field_name} as $item) {
      $text .= ' ' . $item->value;
    }
  }
  $tags = _hashtags_parse_tags($text, FALSE);
  $tag_ids = [];
  if (!$tags) {
    return;
  }
  foreach ($tags as $tag_name) {
    $terms = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties([
      'name' => $tag_name,
    ]);
    $term = reset($terms);
    if (empty($term)) {
      $term = \Drupal\taxonomy\Entity\Term::create([
        'name' => $tag_name,
        'vid' => $vid,
      ]);
      $term
        ->save();
    }
    $tag_ids[] = $term
      ->id();
  }
  _hashtags_field_attach_terms($entity->{$hashtags_field_name}, $tag_ids, $hashtags_vid);
}