You are here

class LingotekImportForm in Lingotek Translation 8

@file Contains \Drupal\Lingotek\Form\LingotekManagementForm.

Hierarchy

Expanded class hierarchy of LingotekImportForm

1 string reference to 'LingotekImportForm'
LingotekImportController::content in src/Controller/LingotekImportController.php
Generates the import content. It has two tabs, the import form and the settings form. @author Unknown

File

src/Form/LingotekImportForm.php, line 13
Contains \Drupal\Lingotek\Form\LingotekManagementForm.

Namespace

Drupal\lingotek\Form
View source
class LingotekImportForm extends LingotekConfigFormBase {
  private $docs = array();
  private $table_docs = array();
  private $supported_extentions = array(
    'json',
    'xml',
  );
  public function getFormId() {
    return 'lingotek.import_form';
  }
  private function get_projects() {
    $communities = $this->lingotek
      ->getCommunities();
    $new_projects = array();
    foreach ($communities as $community_id => $community_name) {

      /**
       * @todo lingotek->getProjects() does not accept a parameter like this and
       * so this is not doing what was expected. It just returns the projects form
       * the defualt community.
       *
       */
      $projects = $this->lingotek
        ->getProjects($community_id);
      foreach ($projects as $project_id => $project_name) {
        $new_projects[$project_id] = $project_name;
      }
    }
    return $new_projects;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    define('ITEMS_PER_PAGE', 10);

    // TODO: use get_projects function to list all project names
    $projects = $this
      ->get_projects();
    $count = 0;
    $total = $this
      ->documentsCount();
    $page = pager_default_initialize($total, ITEMS_PER_PAGE);
    $current_page = pager_find_page();
    $args = array(
      'limit' => ITEMS_PER_PAGE,
      'offset' => $current_page * ITEMS_PER_PAGE,
    );
    $this
      ->downloadDocuments($args);
    foreach ($this->docs as $doc) {
      $unix_upload_time = $doc->properties->upload_date / 1000;
      $upload_date_str = gmdate("m/j/Y", $unix_upload_time);
      $project_name = '-';
      if (array_key_exists($doc->properties->project_id, $projects)) {
        $project_name = $projects[$doc->properties->project_id];
      }
      else {
        $project_name = $doc->properties->project_id;
      }
      $this->table_docs[] = array(
        'id' => $count,
        'title' => $doc->properties->title,
        'extension' => $doc->properties->extension,
        'locale' => $doc->entities[0]->properties->language . " - " . $doc->entities[0]->properties->code,
        'upload_date' => $upload_date_str,
        'doc_id' => $doc->properties->id,
        'project_name' => $project_name,
      );
      $count++;
    }
    $header = array(
      'title' => t('Title'),
      'extension' => t('Extension'),
      'locale' => t('Locale'),
      'upload_date' => t('Upload Date'),
      'project_name' => t('Project Name'),
      'doc_id' => t('ID'),
    );
    $options = array();
    foreach ($this->table_docs as $document) {
      $options[$document['id']] = array(
        'title' => $document['title'],
        'extension' => $document['extension'],
        'locale' => $document['locale'],
        'upload_date' => $document['upload_date'],
        'project_name' => $document['project_name'],
        'doc_id' => $document['doc_id'],
      );
    }
    $form['table'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
      '#empty' => t('No documents found'),
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Import'),
    );
    $form['pager'] = array(
      '#type' => 'pager',
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $results = $form_state
      ->getValue('table');
    $doc_ids_to_import = array();
    foreach ($results as $id => $checked) {
      if (is_string($checked) && $checked == $id) {
        array_push($doc_ids_to_import, $id);
      }
    }
    $import_success_count = 0;
    $import_failure_count = 0;
    $import_failure_doc_ids = array();
    foreach ($doc_ids_to_import as $id) {
      $response = $this
        ->import($id);
      if ($response == 0) {
        $import_failure_count++;
        array_push($import_failure_doc_ids, $this
          ->searchForDoc($id)->properties->id);
      }
      else {
        $import_success_count++;
      }
    }
    $importedCount = $import_success_count + $import_failure_count;
    if ($import_success_count > 0) {
      $plural_or_singular = \Drupal::translation()
        ->formatPlural($importedCount, 'Successfully imported @import_success_count of @importedCount Document', 'Successfully imported @import_success_count of @importedCount Documents', array(
        '@import_success_count' => $import_success_count,
        '@importedCount' => $importedCount,
      ), array());
      drupal_set_message($plural_or_singular);
      if ($import_success_count != $importedCount) {
        $document_plurality = \Drupal::translation()
          ->formatPlural($import_failure_count, 'The following document did not import: @failed_imports', 'The following documents did not import: @failed_imports', array(
          '@failed_imports' => $this
            ->toStringUnsuccessfulImports($import_failure_doc_ids),
        ), array());
        drupal_set_message($document_plurality, 'error');
      }
    }
    else {
      if ($import_success_count == 0 && $import_failure_count == 0) {
        drupal_set_message($this
          ->t('No files were selected to import. Please check the desired documents to import.'), 'error');
      }
      else {
        $file_plurality = \Drupal::translation()
          ->formatPlural($importedCount, 'There was an error importing your file. We currently only support Wordpress, Drupal, HTML, and Text files.', 'There was an error importing your files. We currently only support Wordpress, Drupal, HTML, and Text files.', array(), array());
        drupal_set_message($file_plurality, 'error');
      }
    }
  }

  /**
   * This function is to list the captured doc ids in a string separated by commas
   * so it can be displayed for the end-user in a message.
   *
   * @author TJ Murphy
   * @param array $unsuccessful_imports an array of doc ids that did not import
   * @return string $unsuccessful_imports_string this creates an HTML string that
   *   creates an unordered list of doc ids that failed to import
   **/
  protected function toStringUnsuccessfulImports($unsuccessful_imports) {
    $unsuccessful_imports_string = '';
    $count = 0;
    foreach ($unsuccessful_imports as $doc_id) {
      if ($count != 0) {
        $unsuccessful_imports_string = $unsuccessful_imports_string . ', ' . (string) $doc_id;
      }
      else {
        $unsuccessful_imports_string = $unsuccessful_imports_string . (string) $doc_id;
      }
      $count++;
    }
    $unsuccessful_imports_string = $unsuccessful_imports_string . '.';
    return $unsuccessful_imports_string;
  }
  protected function downloadDocuments($args = array()) {
    $translation_service = \Drupal::service('lingotek.content_translation');
    $response = $this->lingotek
      ->downloadDocuments($args);
    $data = json_decode($response);
    $count = 0;
    foreach ($data->entities as $entity) {
      $this->docs[] = $entity;
      $count++;
    }
    return $count;
  }
  protected function documentsCount($args = array()) {
    $translation_service = \Drupal::service('lingotek.content_translation');
    $response = $this->lingotek
      ->downloadDocuments($args);
    $data = json_decode($response);
    return $data->properties->total;
  }
  protected function downloadDocumentContent($doc_id) {
    $translation_service = \Drupal::service('lingotek.content_translation');
    $response = $translation_service
      ->downloadDocumentContent($doc_id);
    return $response;
  }
  public function import_standard_object(StandardImportObject $object) {
    $content_cloud_import_format = $this->lingotek
      ->get('preference.content_cloud_import_format');
    $content_cloud_import_status = $this->lingotek
      ->get('preference.content_cloud_import_status');
    $node = Node::create(array(
      'nid' => NULL,
      'type' => $content_cloud_import_format,
      'title' => $object
        ->getTitle(),
      'langcode' => 'en',
      'uid' => 1,
      'status' => $content_cloud_import_status,
      'body' => array(
        'value' => $object
          ->getContent(),
        'format' => 'full_html',
      ),
      'field_fields' => array(),
    ));
    $node
      ->save();
    if ($node->node_id) {
      $success = 0;
    }
    else {
      $success = 1;
    }
    return $success;
  }

  /**
   * This function is to import a document from the TMS.
   *
   * @author TJ Murphy
   * @param string id drupal table doc id, not lingotek document id
   * @return mixed will return a 0 if there is an error in the conversion, or it
   *   will return the $response if there is no error and it converts as expected
   **/
  public function import($id) {

    //
    $doc = $this
      ->searchForDoc($id);
    $format = $doc->properties->extension;
    $content = $this
      ->downloadDocumentContent($doc->properties->id);
    if ($content == null) {
      $content == 'There is no content to display';
    }
    $formatConverter = new FormatConverter($doc, $content, $format);
    $importObject = $formatConverter
      ->convert_to_standard();
    if ($importObject
      ->hasError()) {
      return 0;
    }
    $response = $this
      ->import_standard_object($importObject);
    return $response;
  }
  function searchForDoc($id) {
    $doc_id = null;
    foreach ($this->table_docs as $table_doc) {
      if ($table_doc['id'] == $id) {
        $doc_id = $table_doc['doc_id'];
        break;
      }
    }
    foreach ($this->docs as $docObject) {
      if ($docObject->properties->id == $doc_id) {
        return $docObject;
      }
    }
    return null;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LingotekConfigFormBase::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create 3
LingotekConfigFormBase::getEditableConfigNames public function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
LingotekConfigFormBase::__construct public function Constructs a \Drupal\lingotek\Form\LingotekConfigFormBase object. Overrides ConfigFormBase::__construct 3
LingotekImportForm::$docs private property
LingotekImportForm::$supported_extentions private property
LingotekImportForm::$table_docs private property
LingotekImportForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
LingotekImportForm::documentsCount protected function
LingotekImportForm::downloadDocumentContent protected function
LingotekImportForm::downloadDocuments protected function
LingotekImportForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
LingotekImportForm::get_projects private function
LingotekImportForm::import public function This function is to import a document from the TMS.
LingotekImportForm::import_standard_object public function
LingotekImportForm::searchForDoc function
LingotekImportForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
LingotekImportForm::toStringUnsuccessfulImports protected function This function is to list the captured doc ids in a string separated by commas so it can be displayed for the end-user in a message.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.