You are here

class EntityUpdateExec in Entity Update 8

Same name and namespace in other branches
  1. 2.0.x src/Form/EntityUpdateExec.php \Drupal\entity_update\Form\EntityUpdateExec

Class CheckEntityUpdate.

@package Drupal\entity_update\Form

Hierarchy

Expanded class hierarchy of EntityUpdateExec

1 string reference to 'EntityUpdateExec'
entity_update.routing.yml in ./entity_update.routing.yml
entity_update.routing.yml

File

src/Form/EntityUpdateExec.php, line 16

Namespace

Drupal\entity_update\Form
View source
class EntityUpdateExec extends FormBase {

  /**
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'entity_update_exec';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $action = 'default') {
    $link_help = '/admin/help/entity_update';
    $about_text = <<<TEXT
<p>
  This page allow to update entity types schema. Please refer to the <a href='{<span class="php-variable">$link_help</span>}'>Help page</a>.
</p>
<p>
<b>CAUTION</b>
<ul>
  <li>Use this module only as development helper, Do not use in production sites.</li>
  <li>The entity update may damage your database, therefor update the database before any action.</li>
  <li>If you use this system, you are conscience what you are doing. <b>You are the responsible of your work</b>.</li>
</ul>
</p>
<b>NOTE</b> : From here, You can update if:<br>
<ul>
  <li>Any update if the entity type has no data.</li>
  <li>Add new fields to entity type even with data.</li>
</ul>
<i>You can try "Run Full Update", but use the <b>drush</b> interface for safe execution and to have log messages. (Type : <code><b>drush help upe</b></code> for help.)</i><br>
<br>
</p>
TEXT;
    $form['messages']['about'] = [
      '#type' => 'markup',
      '#markup' => $about_text,
      '#prefix' => '<div>',
      '#suffix' => '</div>',
    ];
    $form['confirm'] = [
      '#type' => 'checkbox',
      '#default_value' => '0',
      '#title' => $this
        ->t('Yes, I want to execute the following action.'),
    ];
    $form['action'] = [
      '#type' => 'hidden',
      '#default_value' => $action,
    ];

    // Cleanup archives.
    if ($action == 'clean') {

      // Run backuped entities cleanup.
      $form['submit_clean'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Cleanup'),
        '#submit' => [
          '::submitFormClean',
        ],
        '#validate' => [
          '::validateOk',
        ],
        '#description' => '',
      ];
    }
    elseif ($action == 'rescue') {
      $form['submit_rescue'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Run Entity Rescue'),
        '#submit' => [
          '::submitFormRescue',
        ],
      ];
    }
    elseif ($action == 'type') {
      $list = EntityUpdate::getEntityTypesToUpdate();
      if (!empty($list)) {
        $form['action_entitytype'] = [
          '#type' => 'details',
          '#title' => 'Update a selected entity type',
          '#open' => TRUE,
        ];
        $options = [];
        foreach ($list as $entity_type_id => $value) {
          $options[$entity_type_id] = $entity_type_id;
        }
        $form['action_entitytype']['entity_type_id'] = [
          '#type' => 'select',
          '#title' => $this
            ->t('The entity type id to update'),
          '#options' => $options,
        ];

        // Update entity types with data. This action is not recomended from UI.
        $form['action_entitytype']['submit_type'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Run Type Update'),
          '#submit' => [
            '::submitFormSafe',
          ],
          '#validate' => [
            '::validateForm',
            '::validateSafe',
          ],
          '#description' => '',
        ];
      }
      else {
        $form['action_entitytype'] = [
          '#type' => 'markup',
          '#markup' => 'Nothing to update',
        ];
      }
    }
    else {
      $form['force'] = [
        '#type' => 'checkbox',
        '#default_value' => '0',
        '#title' => $this
          ->t('Try force update.'),
        '#description' => $this
          ->t('Run basic update using --force option.'),
      ];
      $form['submit_basic'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Run Basic Update'),
        '#submit' => [
          '::submitFormBasic',
        ],
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $list = EntityUpdate::getEntityTypesToUpdate();
    $action = $form_state
      ->getValue('action');
    $actions = [
      'rescue',
    ];
    if (!in_array($action, $actions) && empty($list)) {
      $form_state
        ->setErrorByName('about', $this
        ->t("Nothing to update. All entities are up to date;"));
    }
    elseif (!$form_state
      ->getValue('confirm')) {
      $form_state
        ->setErrorByName('confirm', $this
        ->t("If you want to execute, please check the checkbox."));
    }
  }

  /**
   * Safe mode validation.
   *
   * {@inheritdoc}
   */
  public function validateSafe(array &$form, FormStateInterface $form_state) {
    $type = $form_state
      ->getValue('entity_type_id');
    $list = EntityUpdate::getEntityTypesToUpdate($type);
    if (!isset($list[$type])) {
      $form_state
        ->setErrorByName('entity_type_id', $this
        ->t("No updates for entity_type_id"));
      return;
    }
    $entity_type_changes = $list[$type];

    // Init flags.
    $flg_has_install = FALSE;
    $flg_has_uninstall = FALSE;

    // Check install/uninstall.
    foreach ($entity_type_changes as $entity_change_summ) {
      if (strstr($entity_change_summ, "uninstalled")) {
        $flg_has_uninstall = TRUE;
      }
      else {
        $flg_has_install = TRUE;
      }
    }

    // Check and print instruction.
    if ($flg_has_install && $flg_has_uninstall) {
      $form_state
        ->setErrorByName('entity_type_id', $this
        ->t("Multiple actions detected, cant update if contains data. Use basic method."));
      return;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function validateOk(array &$form, FormStateInterface $form_state) {

    // Nothing to validate.
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Default submit actions.
  }

  /**
   * Run updates using basic method.
   */
  public function submitFormBasic(array &$form, FormStateInterface $form_state) {
    try {
      $force = $form_state
        ->getValue('force');
      $res = EntityUpdate::basicUpdate($force);
      $res_str = $res ? 'SUCCESS' : 'FAIL';
      $status = $res ? 'status' : 'error';
      drupal_set_message($this
        ->t("Entity update @res", [
        '@res' => $res_str,
      ]), $status);
    } catch (\Exception $e) {
      drupal_set_message($this
        ->t("Entity update Fail"), 'error');
      drupal_set_message($e
        ->getMessage(), 'error');
    }
  }

  /**
   * Run updates using safe (full) method.
   */
  public function submitFormSafe(array &$form, FormStateInterface $form_state) {
    try {
      $type = $form_state
        ->getValue('entity_type_id');
      $entity_type = entity_update_get_entity_type($type);

      // Update the entity type.
      $res = EntityUpdate::safeUpdateMain($entity_type);
      $res_str = $res ? 'SUCCESS' : 'FAIL';
      $status = $res ? 'status' : 'error';
      $options = [
        '@res' => $res_str,
        '@type' => $entity_type
          ->getLabel(),
      ];
      drupal_set_message($this
        ->t("Entity @type update @res", $options), $status);
    } catch (\Exception $e) {
      drupal_set_message($this
        ->t("Entity update Fail"), 'error');
      drupal_set_message($e
        ->getMessage(), 'error');
    }
  }

  /**
   * Run backuped entities cleanup.
   */
  public function submitFormClean(array &$form, FormStateInterface $form_state) {
    try {
      $res = EntityUpdate::cleanupEntityBackup();
      $res_str = $res ? 'SUCCESS' : 'FAIL';
      $status = $res ? 'status' : 'error';
      drupal_set_message($this
        ->t("Backups cleanup @res", [
        '@res' => $res_str,
      ]), $status);
    } catch (\Exception $e) {
      drupal_set_message($this
        ->t("Entity update Fail"), 'error');
      drupal_set_message($e
        ->getMessage(), 'error');
    }
  }

  /**
   * Run rescue entities.
   */
  public function submitFormRescue(array &$form, FormStateInterface $form_state) {
    try {
      $res = EntityUpdate::entityUpdateDataRestore();
      $res_str = $res ? 'SUCCESS' : 'FAIL';
      $status = $res ? 'status' : 'error';
      drupal_set_message($this
        ->t("Entity rescue @res", [
        '@res' => $res_str,
      ]), $status);
    } catch (\Exception $e) {
      drupal_set_message($this
        ->t("Entity update Fail"), 'error');
      drupal_set_message($e
        ->getMessage(), 'error');
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
EntityUpdateExec::buildForm public function Form constructor. Overrides FormInterface::buildForm
EntityUpdateExec::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
EntityUpdateExec::submitForm public function Form submission handler. Overrides FormInterface::submitForm
EntityUpdateExec::submitFormBasic public function Run updates using basic method.
EntityUpdateExec::submitFormClean public function Run backuped entities cleanup.
EntityUpdateExec::submitFormRescue public function Run rescue entities.
EntityUpdateExec::submitFormSafe public function Run updates using safe (full) method.
EntityUpdateExec::validateForm public function Form validation handler. Overrides FormBase::validateForm
EntityUpdateExec::validateOk public function
EntityUpdateExec::validateSafe public function Safe mode validation.
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.
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.