<?php

use Drupal\node\Entity\node;
use Drupal\taxonomy\Entity\Term;

$term_name = 'Repost';

$term = taxonomy_term_load_multiple_by_name($term_name, 'article_type');

// Create the term if it does not exists and load it.
if (empty($term)) {
  $term = Term::create([
    'name' => $term_name,
    'vid' => 'article_type',
  ])->save();
  $term = taxonomy_term_load_multiple_by_name($term_name, 'article_type');
}
$term = current($term);

// Add the term to all the entities that hasn't a value in the citation field.
$query = \Drupal::entityQuery('node');
$query->condition('type', 'article');
$entity_ids = $query->execute();
$db = \Drupal::database();
$query = $db->query("
  SELECT 
    n.nid 
  FROM  
    drupal7.node as n 
  LEFT JOIN 
    drupal7.field_data_field_citiations as  fdfc 
  ON 
    (n.nid = fdfc.entity_id)   
  WHERE n.type = 'story' 
  AND 
  fdfc.field_citiations_value IS null;"
);
$entity_ids = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($entity_ids as $entity) {
  $entity =  Node::load($entity['nid']);
  $entity_terms = $entity->get('field_article_type')->getValue();

  // Check if the entity hasn't the term already.
  $add_term = TRUE;
  foreach ($entity_terms as $term_node) {
    if ($term_node['target_id'] == $term->id()) {
      $add_term = FALSE;
    }
  }
  if ($add_term == TRUE) {
    $entity_terms = array_merge($entity->get('field_article_type')->getValue(), [['target_id' => $term->id()]]);
    $entity->set('field_article_type', $entity_terms);
    $entity->save();
  }

}