You are here

function search_api_synonym_cron in Search API Synonym 8

Implements hook_cron().

File

./search_api_synonym.module, line 40
Contains search_api_synonym.module.

Code

function search_api_synonym_cron() {
  $request_time = \Drupal::time()
    ->getRequestTime();

  // Export synonyms to files.
  $conf = \Drupal::configFactory()
    ->getEditable('search_api_synonym.settings')
    ->get('cron');
  $interval = isset($conf['interval']) ? $conf['interval'] : 86400;
  $next_execution = \Drupal::state()
    ->get('search_api_synonym.export.next_execution', 0);
  if ($interval !== 0 && $request_time >= $next_execution) {
    $logger = \Drupal::logger('search_api_synonym');

    // Execute export
    $logger
      ->notice('Executing export');

    // Plugin manager
    $pluginManager = \Drupal::service('plugin.manager.search_api_synonym.export');

    // Validate option: plugin
    $plugin = $conf['plugin'];
    if (!$pluginManager
      ->validatePlugin($plugin)) {
      $logger
        ->warning('Export plugin not found');
      return;
    }

    // Setting non language specific export options
    $options = [
      'type' => $conf['type'],
      'filter' => $conf['filter'],
      'file' => '',
      'incremental' => $conf['export_if_changed'] ? $next_execution : 0,
    ];

    // Get all languages in the system
    $languages = \Drupal::languageManager()
      ->getLanguages();
    foreach ($languages as $language) {
      $options['langcode'] = $language
        ->getId();

      // Export synonyms with and without spaces into separate files
      if ($conf['separate_files'] && ($conf['filter'] == 'none' || !$conf['filter'])) {

        // Without spaces
        $options['filter'] = 'nospace';
        search_api_synonym_execute_single_import($plugin, $options);

        // With spaces
        $options['filter'] = 'onlyspace';
        search_api_synonym_execute_single_import($plugin, $options);
      }
      else {
        search_api_synonym_execute_single_import($plugin, $options);
      }
    }
    $logger
      ->info('Export done');
    \Drupal::state()
      ->set('search_api_synonym.export.next_execution', $request_time + $interval);
  }
}