You are here

class FeedsTermProcessor in Feeds 7

Same name and namespace in other branches
  1. 6 plugins/FeedsTermProcessor.inc \FeedsTermProcessor
  2. 7.2 plugins/FeedsTermProcessor.inc \FeedsTermProcessor

Feeds processor plugin. Create taxonomy terms from feed items.

Hierarchy

Expanded class hierarchy of FeedsTermProcessor

2 string references to 'FeedsTermProcessor'
FeedsCSVtoTermsTest::test in tests/feeds_processor_term.test
Test node creation, refreshing/deleting feeds and feed items.
_feeds_feeds_plugins in ./feeds.plugins.inc
Break out for feeds_feed_plugins().

File

plugins/FeedsTermProcessor.inc, line 11
FeedsTermProcessor class.

View source
class FeedsTermProcessor extends FeedsProcessor {

  /**
   * Implements FeedsProcessor::process().
   */
  public function process(FeedsImportBatch $batch, FeedsSource $source) {
    if (empty($this->config['vocabulary'])) {
      throw new Exception(t('You must define a vocabulary for Taxonomy term processor before importing.'));
    }

    // Count number of created and updated nodes.
    $created = $updated = $no_name = 0;
    while ($item = $batch
      ->shiftItem()) {
      if (!($tid = $this
        ->existingItemId($batch, $source)) || $this->config['update_existing'] != FEEDS_SKIP_EXISTING) {

        // Map item to a term.
        $term = new stdClass();
        if ($tid && $this->config['update_existing'] == FEEDS_UPDATE_EXISTING) {
          $term = taxonomy_term_load($tid);
          $term = module_invoke_all('feeds_taxonomy_load', $term);
        }
        $term->entity_type = 'taxonomy_term';
        $term = $this
          ->map($batch, $term, $source->feed_nid);

        // Check if term name is set, otherwise continue.
        if (empty($term->name)) {
          $no_name++;
          continue;
        }

        // Add term id if available.
        if (!empty($tid)) {
          $term->tid = $tid;
        }

        // Save the term.
        $term->feeds_importer_id = $this->id;
        $term->feed_nid = $source->feed_nid;
        taxonomy_term_save($term);
        if ($tid) {
          $updated++;
        }
        else {
          $created++;
        }
      }
    }

    // Set messages.
    $vocabulary = $this
      ->vocabulary();
    if ($no_name) {
      drupal_set_message(format_plural($no_name, 'There was @number term that could not be imported because their name was empty. Check mapping settings on Taxomy term processor.', 'There were @number terms that could not be imported because their name was empty. Check mapping settings on Taxomy term processor.', array(
        '@number' => $no_name,
      )), 'error');
    }
    if ($created) {
      drupal_set_message(format_plural($created, 'Created @number term in !vocabulary.', 'Created @number terms in !vocabulary.', array(
        '@number' => $created,
        '!vocabulary' => $vocabulary->name,
      )));
    }
    elseif ($updated) {
      drupal_set_message(format_plural($updated, 'Updated @number term in !vocabulary.', 'Updated @number terms in !vocabulary.', array(
        '@number' => $updated,
        '!vocabulary' => $vocabulary->name,
      )));
    }
    else {
      drupal_set_message(t('There are no new terms.'));
    }
  }

  /**
   * Implements FeedsProcessor::clear().
   */
  public function clear(FeedsBatch $batch, FeedsSource $source) {
    $deleted = 0;
    $vocabulary = $this
      ->vocabulary();
    $terms = db_query("SELECT td.tid\n                        FROM {taxonomy_term_data} td\n                        JOIN {feeds_term_item} ft ON td.tid = ft.tid\n                        WHERE td.vid = :vid\n                        AND ft.id = :id\n                        AND ft.feed_nid = :feed_nid", array(
      ':vid' => $vocabulary->vid,
      ':id' => $this->id,
      ':feed_nid' => $source->feed_nid,
    ));
    foreach ($terms as $term) {
      if (taxonomy_term_delete($term->tid) == SAVED_DELETED) {
        $deleted++;
      }
    }

    // Set messages.
    if ($deleted) {
      drupal_set_message(format_plural($deleted, 'Deleted @number term from !vocabulary.', 'Deleted @number terms from !vocabulary.', array(
        '@number' => $deleted,
        '!vocabulary' => $vocabulary->name,
      )));
    }
    else {
      drupal_set_message(t('No terms to be deleted.'));
    }
  }

  /**
   * Execute mapping on an item.
   */
  protected function map(FeedsImportBatch $batch, $target_term = NULL) {

    // Prepare term object, have parent class do the iterating.
    if (!$target_term) {
      $target_term = new stdClass();
    }
    if (!($vocabulary = $this
      ->vocabulary())) {
      throw new Exception(t('No vocabulary specified for term processor'));
    }
    $target_term->vid = $vocabulary->vid;
    $target_term = parent::map($batch, $target_term);
    return $target_term;
  }

  /**
   * Override parent::configDefaults().
   */
  public function configDefaults() {
    return array(
      'vocabulary' => 0,
      'update_existing' => FEEDS_SKIP_EXISTING,
      'mappings' => array(),
    );
  }

  /**
   * Override parent::configForm().
   */
  public function configForm(&$form_state) {
    $options = array(
      0 => t('Select a vocabulary'),
    );
    foreach (taxonomy_get_vocabularies() as $vocab) {
      $options[$vocab->machine_name] = check_plain($vocab->name);
    }
    $form = array();
    $form['vocabulary'] = array(
      '#type' => 'select',
      '#title' => t('Import to vocabulary'),
      '#description' => t('Choose the vocabulary to import into. <strong>CAUTION:</strong> when deleting terms through the "Delete items" tab, Feeds will delete <em>all</em> terms from this vocabulary.'),
      '#options' => $options,
      '#default_value' => $this->config['vocabulary'],
    );
    $form['update_existing'] = array(
      '#type' => 'radios',
      '#title' => t('Update existing terms'),
      '#description' => t('Select how existing terms should be updated. Existing terms will be determined using mappings that are a "unique target".'),
      '#options' => array(
        FEEDS_SKIP_EXISTING => 'Do not update existing terms',
        FEEDS_REPLACE_EXISTING => 'Replace existing terms',
        FEEDS_UPDATE_EXISTING => 'Update existing terms (slower than replacing them)',
      ),
      '#default_value' => $this->config['update_existing'],
    );
    return $form;
  }

  /**
   * Override parent::configFormValidate().
   */
  public function configFormValidate(&$values) {
    if (empty($values['vocabulary'])) {
      form_set_error('vocabulary', t('Choose a vocabulary'));
    }
  }

  /**
   * Return available mapping targets.
   */
  public function getMappingTargets() {
    $targets = array(
      'name' => array(
        'name' => t('Term name'),
        'description' => t('Name of the taxonomy term.'),
        'optional_unique' => TRUE,
      ),
      'description' => array(
        'name' => t('Term description'),
        'description' => t('Description of the taxonomy term.'),
      ),
    );

    // Let implementers of hook_feeds_term_processor_targets() add their targets.
    if ($vocabulary = $this
      ->vocabulary()) {
      self::loadMappers();
      feeds_alter('feeds_processor_targets', $targets, 'taxonomy_term', $vocabulary->machine_name);
    }
    return $targets;
  }

  /**
   * Get id of an existing feed item term if available.
   */
  protected function existingItemId(FeedsImportBatch $batch, FeedsSource $source) {

    // The only possible unique target is name.
    foreach ($this
      ->uniqueTargets($batch) as $target => $value) {
      if ($target == 'name') {
        $vocabulary = $this
          ->vocabulary();
        if ($tid = db_query("SELECT tid FROM {taxonomy_term_data} WHERE name = :name AND vid = :vid", array(
          ':name' => $value,
          ':vid' => $vocabulary->vid,
        ))
          ->fetchField()) {
          return $tid;
        }
      }
    }
    return 0;
  }

  /**
   * Return vocabulary to map to.
   */
  public function vocabulary() {

    // Legacy handling for old feeds importers.
    if (is_numeric($this->config['vocabulary'])) {
      $vocabularies = taxonomy_get_vocabularies();
      return isset($vocabularies[$this->config['vocabulary']]) ? $vocabularies[$this->config['vocabulary']] : NULL;
    }
    else {
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($this->config['vocabulary'])) {
        return $vocabulary;
      }
      else {
        $vocabularies = taxonomy_get_vocabularies();
        foreach ($vocabularies as $vocabulary) {
          if ($vocabulary->module == $this->config['vocabulary']) {
            return $vocabulary;
          }
        }
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
FeedsConfigurable::$config protected property
FeedsConfigurable::$disabled protected property CTools export enabled status of this object.
FeedsConfigurable::$export_type protected property
FeedsConfigurable::$id protected property
FeedsConfigurable::addConfig public function Similar to setConfig but adds to existing configuration.
FeedsConfigurable::configFormSubmit public function Submission handler for configForm(). 2
FeedsConfigurable::copy public function Copy a configuration. 1
FeedsConfigurable::existing public function Determine whether this object is persistent and enabled. I. e. it is defined either in code or in the database and it is enabled. 1
FeedsConfigurable::getConfig public function Implements getConfig(). 1
FeedsConfigurable::instance public static function Instantiate a FeedsConfigurable object. 1
FeedsConfigurable::setConfig public function Set configuration.
FeedsConfigurable::__get public function Override magic method __get(). Make sure that $this->config goes through getConfig()
FeedsPlugin::all public static function Get all available plugins.
FeedsPlugin::byType public static function Gets all available plugins of a particular type.
FeedsPlugin::child public static function Determines whether given plugin is derived from given base plugin.
FeedsPlugin::hasSourceConfig public function Returns TRUE if $this->sourceForm() returns a form. Overrides FeedsSourceInterface::hasSourceConfig
FeedsPlugin::loadMappers protected static function Loads on-behalf implementations from mappers/ directory.
FeedsPlugin::save public function Save changes to the configuration of this object. Delegate saving to parent (= Feed) which will collect information from this object by way of getConfig() and store it. Overrides FeedsConfigurable::save
FeedsPlugin::sourceDefaults public function Implements FeedsSourceInterface::sourceDefaults(). Overrides FeedsSourceInterface::sourceDefaults 1
FeedsPlugin::sourceDelete public function A source is being deleted. Overrides FeedsSourceInterface::sourceDelete 2
FeedsPlugin::sourceForm public function Callback methods, exposes source form. Overrides FeedsSourceInterface::sourceForm 3
FeedsPlugin::sourceFormValidate public function Validation handler for sourceForm. Overrides FeedsSourceInterface::sourceFormValidate 2
FeedsPlugin::sourceSave public function A source is being saved. Overrides FeedsSourceInterface::sourceSave 2
FeedsPlugin::typeOf public static function Determines the type of a plugin.
FeedsPlugin::__construct protected function Constructor. Overrides FeedsConfigurable::__construct
FeedsProcessor::expire public function Delete feed items younger than now - $time. Do not invoke expire on a processor directly, but use FeedsImporter::expire() instead. 1
FeedsProcessor::expiryTime public function Per default, don't support expiry. If processor supports expiry of imported items, return the time after which items should be removed. 1
FeedsProcessor::getMappings public function Get mappings.
FeedsProcessor::setTargetElement public function Set a concrete target element. Invoked from FeedsProcessor::map(). 3
FeedsProcessor::uniqueTargets protected function Utility function that iterates over a target array and retrieves all sources that are unique.
FeedsTermProcessor::clear public function Implements FeedsProcessor::clear(). Overrides FeedsProcessor::clear
FeedsTermProcessor::configDefaults public function Override parent::configDefaults(). Overrides FeedsProcessor::configDefaults
FeedsTermProcessor::configForm public function Override parent::configForm(). Overrides FeedsConfigurable::configForm
FeedsTermProcessor::configFormValidate public function Override parent::configFormValidate(). Overrides FeedsConfigurable::configFormValidate
FeedsTermProcessor::existingItemId protected function Get id of an existing feed item term if available. Overrides FeedsProcessor::existingItemId
FeedsTermProcessor::getMappingTargets public function Return available mapping targets. Overrides FeedsProcessor::getMappingTargets
FeedsTermProcessor::map protected function Execute mapping on an item. Overrides FeedsProcessor::map
FeedsTermProcessor::process public function Implements FeedsProcessor::process(). Overrides FeedsProcessor::process
FeedsTermProcessor::vocabulary public function Return vocabulary to map to.