<?php

namespace Drupal\agaric_migration\Plugin\migrate\source;

use Drupal\migrate\Row;
use Drupal\node\Plugin\migrate\source\d7\Node;


/**
 * Add the Taxonomy term name in the query.
 *
 * This adds the sourceProperty field_tags_names which are the name of the terms
 *
 * @MigrateSource(
 *   id = "agaric_node",
 *   source_module = "node"
 * )
 */
class AgaricNode extends Node {

  public function prepareRow(Row $row) {
    $nid = $row->getSourceProperty('nid');
    // Get the taxonomy tags names.
    $tags = $this->getFieldValues('node', 'field_tags', $nid);
    $names = [];
    foreach ($tags as $tag) {
      $tid = $tag['tid'];

      $query = $this->select('taxonomy_term_data', 't');
      $query->condition('tid', $tid);
      $query->addField('t', 'name');
      $result = $query->execute()->fetchAssoc();
      $names[] = ['name' => $result['name']];
    }
    $row->setSourceProperty('field_tags_names', $names);

    return parent::prepareRow($row);
  }

}
